Decoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. using ChocolArm64.Instructions;
  2. using ChocolArm64.Memory;
  3. using ChocolArm64.State;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.Reflection.Emit;
  8. namespace ChocolArm64.Decoders
  9. {
  10. static class Decoder
  11. {
  12. private delegate object OpActivator(Inst inst, long position, int opCode);
  13. private static ConcurrentDictionary<Type, OpActivator> _opActivators;
  14. static Decoder()
  15. {
  16. _opActivators = new ConcurrentDictionary<Type, OpActivator>();
  17. }
  18. public static Block[] DecodeBasicBlock(MemoryManager memory, ulong address, ExecutionMode mode)
  19. {
  20. Block block = new Block(address);
  21. FillBlock(memory, mode, block, ulong.MaxValue);
  22. OpCode64 lastOp = block.GetLastOp();
  23. if (IsBranch(lastOp) && !IsCall(lastOp) && lastOp is IOpCodeBImm op)
  24. {
  25. // It's possible that the branch on this block lands on the middle of the block.
  26. // This is more common on tight loops. In this case, we can improve the codegen
  27. // a bit by changing the CFG and either making the branch point to the same block
  28. // (which indicates that the block is a loop that jumps back to the start), and the
  29. // other possible case is a jump somewhere on the middle of the block, which is
  30. // also a loop, but in this case we need to split the block in half.
  31. if ((ulong)op.Imm == address)
  32. {
  33. block.Branch = block;
  34. }
  35. else if ((ulong)op.Imm > address &&
  36. (ulong)op.Imm < block.EndAddress)
  37. {
  38. Block rightBlock = new Block((ulong)op.Imm);
  39. block.Split(rightBlock);
  40. return new Block[] { block, rightBlock };
  41. }
  42. }
  43. return new Block[] { block };
  44. }
  45. public static Block[] DecodeSubroutine(MemoryManager memory, ulong address, ExecutionMode mode)
  46. {
  47. List<Block> blocks = new List<Block>();
  48. Queue<Block> workQueue = new Queue<Block>();
  49. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  50. Block GetBlock(ulong blkAddress)
  51. {
  52. if (!visited.TryGetValue(blkAddress, out Block block))
  53. {
  54. block = new Block(blkAddress);
  55. workQueue.Enqueue(block);
  56. visited.Add(blkAddress, block);
  57. }
  58. return block;
  59. }
  60. GetBlock(address);
  61. while (workQueue.TryDequeue(out Block currBlock))
  62. {
  63. // Check if the current block is inside another block.
  64. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  65. {
  66. Block nBlock = blocks[nBlkIndex];
  67. if (nBlock.Address == currBlock.Address)
  68. {
  69. throw new InvalidOperationException("Found duplicate block address on the list.");
  70. }
  71. nBlock.Split(currBlock);
  72. blocks.Insert(nBlkIndex + 1, currBlock);
  73. continue;
  74. }
  75. // If we have a block after the current one, set the limit address.
  76. ulong limitAddress = ulong.MaxValue;
  77. if (nBlkIndex != blocks.Count)
  78. {
  79. Block nBlock = blocks[nBlkIndex];
  80. int nextIndex = nBlkIndex + 1;
  81. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  82. {
  83. limitAddress = blocks[nextIndex].Address;
  84. }
  85. else if (nBlock.Address > currBlock.Address)
  86. {
  87. limitAddress = blocks[nBlkIndex].Address;
  88. }
  89. }
  90. FillBlock(memory, mode, currBlock, limitAddress);
  91. if (currBlock.OpCodes.Count != 0)
  92. {
  93. // Set child blocks. "Branch" is the block the branch instruction
  94. // points to (when taken), "Next" is the block at the next address,
  95. // executed when the branch is not taken. For Unconditional Branches
  96. // (except BL/BLR that are sub calls) or end of executable, Next is null.
  97. OpCode64 lastOp = currBlock.GetLastOp();
  98. bool isCall = IsCall(lastOp);
  99. if (lastOp is IOpCodeBImm op && !isCall)
  100. {
  101. currBlock.Branch = GetBlock((ulong)op.Imm);
  102. }
  103. if (!IsUnconditionalBranch(lastOp) || isCall)
  104. {
  105. currBlock.Next = GetBlock(currBlock.EndAddress);
  106. }
  107. }
  108. // Insert the new block on the list (sorted by address).
  109. if (blocks.Count != 0)
  110. {
  111. Block nBlock = blocks[nBlkIndex];
  112. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  113. }
  114. else
  115. {
  116. blocks.Add(currBlock);
  117. }
  118. }
  119. return blocks.ToArray();
  120. }
  121. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  122. {
  123. index = 0;
  124. int left = 0;
  125. int right = blocks.Count - 1;
  126. while (left <= right)
  127. {
  128. int size = right - left;
  129. int middle = left + (size >> 1);
  130. Block block = blocks[middle];
  131. index = middle;
  132. if (address >= block.Address && address < block.EndAddress)
  133. {
  134. return true;
  135. }
  136. if (address < block.Address)
  137. {
  138. right = middle - 1;
  139. }
  140. else
  141. {
  142. left = middle + 1;
  143. }
  144. }
  145. return false;
  146. }
  147. private static void FillBlock(
  148. MemoryManager memory,
  149. ExecutionMode mode,
  150. Block block,
  151. ulong limitAddress)
  152. {
  153. ulong address = block.Address;
  154. OpCode64 opCode;
  155. do
  156. {
  157. if (address >= limitAddress)
  158. {
  159. break;
  160. }
  161. opCode = DecodeOpCode(memory, address, mode);
  162. block.OpCodes.Add(opCode);
  163. address += (ulong)opCode.OpCodeSizeInBytes;
  164. }
  165. while (!(IsBranch(opCode) || IsException(opCode)));
  166. block.EndAddress = address;
  167. }
  168. private static bool IsBranch(OpCode64 opCode)
  169. {
  170. return opCode is OpCodeBImm64 ||
  171. opCode is OpCodeBReg64 || IsAarch32Branch(opCode);
  172. }
  173. private static bool IsUnconditionalBranch(OpCode64 opCode)
  174. {
  175. return opCode is OpCodeBImmAl64 ||
  176. opCode is OpCodeBReg64 || IsAarch32UnconditionalBranch(opCode);
  177. }
  178. private static bool IsAarch32UnconditionalBranch(OpCode64 opCode)
  179. {
  180. if (!(opCode is OpCode32 op))
  181. {
  182. return false;
  183. }
  184. // Note: On ARM32, most instructions have conditional execution,
  185. // so there's no "Always" (unconditional) branch like on ARM64.
  186. // We need to check if the condition is "Always" instead.
  187. return IsAarch32Branch(op) && op.Cond >= Condition.Al;
  188. }
  189. private static bool IsAarch32Branch(OpCode64 opCode)
  190. {
  191. // Note: On ARM32, most ALU operations can write to R15 (PC),
  192. // so we must consider such operations as a branch in potential as well.
  193. if (opCode is IOpCode32Alu opAlu && opAlu.Rd == RegisterAlias.Aarch32Pc)
  194. {
  195. return true;
  196. }
  197. // Same thing for memory operations. We have the cases where PC is a target
  198. // register (Rt == 15 or (mask & (1 << 15)) != 0), and cases where there is
  199. // a write back to PC (wback == true && Rn == 15), however the later may
  200. // be "undefined" depending on the CPU, so compilers should not produce that.
  201. if (opCode is IOpCode32Mem || opCode is IOpCode32MemMult)
  202. {
  203. int rt, rn;
  204. bool wBack, isLoad;
  205. if (opCode is IOpCode32Mem opMem)
  206. {
  207. rt = opMem.Rt;
  208. rn = opMem.Rn;
  209. wBack = opMem.WBack;
  210. isLoad = opMem.IsLoad;
  211. // For the dual load, we also need to take into account the
  212. // case were Rt2 == 15 (PC).
  213. if (rt == 14 && opMem.Emitter == InstEmit32.Ldrd)
  214. {
  215. rt = RegisterAlias.Aarch32Pc;
  216. }
  217. }
  218. else if (opCode is IOpCode32MemMult opMemMult)
  219. {
  220. const int pcMask = 1 << RegisterAlias.Aarch32Pc;
  221. rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0;
  222. rn = opMemMult.Rn;
  223. wBack = opMemMult.PostOffset != 0;
  224. isLoad = opMemMult.IsLoad;
  225. }
  226. else
  227. {
  228. throw new NotImplementedException($"The type \"{opCode.GetType().Name}\" is not implemented on the decoder.");
  229. }
  230. if ((rt == RegisterAlias.Aarch32Pc && isLoad) ||
  231. (rn == RegisterAlias.Aarch32Pc && wBack))
  232. {
  233. return true;
  234. }
  235. }
  236. // Explicit branch instructions.
  237. return opCode is IOpCode32BImm ||
  238. opCode is IOpCode32BReg;
  239. }
  240. private static bool IsCall(OpCode64 opCode)
  241. {
  242. // TODO (CQ): ARM32 support.
  243. return opCode.Emitter == InstEmit.Bl ||
  244. opCode.Emitter == InstEmit.Blr;
  245. }
  246. private static bool IsException(OpCode64 opCode)
  247. {
  248. return opCode.Emitter == InstEmit.Brk ||
  249. opCode.Emitter == InstEmit.Svc ||
  250. opCode.Emitter == InstEmit.Und;
  251. }
  252. public static OpCode64 DecodeOpCode(MemoryManager memory, ulong address, ExecutionMode mode)
  253. {
  254. int opCode = memory.ReadInt32((long)address);
  255. Inst inst;
  256. if (mode == ExecutionMode.Aarch64)
  257. {
  258. inst = OpCodeTable.GetInstA64(opCode);
  259. }
  260. else
  261. {
  262. if (mode == ExecutionMode.Aarch32Arm)
  263. {
  264. inst = OpCodeTable.GetInstA32(opCode);
  265. }
  266. else /* if (mode == ExecutionMode.Aarch32Thumb) */
  267. {
  268. inst = OpCodeTable.GetInstT32(opCode);
  269. }
  270. }
  271. OpCode64 decodedOpCode = new OpCode64(Inst.Undefined, (long)address, opCode);
  272. if (inst.Type != null)
  273. {
  274. decodedOpCode = MakeOpCode(inst.Type, inst, (long)address, opCode);
  275. }
  276. return decodedOpCode;
  277. }
  278. private static OpCode64 MakeOpCode(Type type, Inst inst, long position, int opCode)
  279. {
  280. if (type == null)
  281. {
  282. throw new ArgumentNullException(nameof(type));
  283. }
  284. OpActivator createInstance = _opActivators.GetOrAdd(type, CacheOpActivator);
  285. return (OpCode64)createInstance(inst, position, opCode);
  286. }
  287. private static OpActivator CacheOpActivator(Type type)
  288. {
  289. Type[] argTypes = new Type[] { typeof(Inst), typeof(long), typeof(int) };
  290. DynamicMethod mthd = new DynamicMethod($"Make{type.Name}", type, argTypes);
  291. ILGenerator generator = mthd.GetILGenerator();
  292. generator.Emit(OpCodes.Ldarg_0);
  293. generator.Emit(OpCodes.Ldarg_1);
  294. generator.Emit(OpCodes.Ldarg_2);
  295. generator.Emit(OpCodes.Newobj, type.GetConstructor(argTypes));
  296. generator.Emit(OpCodes.Ret);
  297. return (OpActivator)mthd.CreateDelegate(typeof(OpActivator));
  298. }
  299. }
  300. }