Decoder.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. using ARMeilleure.Decoders.Optimizations;
  2. using ARMeilleure.Instructions;
  3. using ARMeilleure.Memory;
  4. using ARMeilleure.State;
  5. using System;
  6. using System.Collections.Generic;
  7. namespace ARMeilleure.Decoders
  8. {
  9. static class Decoder
  10. {
  11. // We define a limit on the number of instructions that a function may have,
  12. // this prevents functions being potentially too large, which would
  13. // take too long to compile and use too much memory.
  14. private const int MaxInstsPerFunction = 2500;
  15. // For lower code quality translation, we set a lower limit since we're blocking execution.
  16. private const int MaxInstsPerFunctionLowCq = 500;
  17. public static Block[] Decode(IMemoryManager memory, ulong address, ExecutionMode mode, bool highCq, bool singleBlock)
  18. {
  19. List<Block> blocks = new List<Block>();
  20. Queue<Block> workQueue = new Queue<Block>();
  21. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  22. int opsCount = 0;
  23. int instructionLimit = highCq ? MaxInstsPerFunction : MaxInstsPerFunctionLowCq;
  24. Block GetBlock(ulong blkAddress)
  25. {
  26. if (!visited.TryGetValue(blkAddress, out Block block))
  27. {
  28. block = new Block(blkAddress);
  29. if ((singleBlock && visited.Count >= 1) || opsCount > instructionLimit || !memory.IsMapped(blkAddress))
  30. {
  31. block.Exit = true;
  32. block.EndAddress = blkAddress;
  33. }
  34. workQueue.Enqueue(block);
  35. visited.Add(blkAddress, block);
  36. }
  37. return block;
  38. }
  39. GetBlock(address);
  40. while (workQueue.TryDequeue(out Block currBlock))
  41. {
  42. // Check if the current block is inside another block.
  43. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  44. {
  45. Block nBlock = blocks[nBlkIndex];
  46. if (nBlock.Address == currBlock.Address)
  47. {
  48. throw new InvalidOperationException("Found duplicate block address on the list.");
  49. }
  50. currBlock.Exit = false;
  51. nBlock.Split(currBlock);
  52. blocks.Insert(nBlkIndex + 1, currBlock);
  53. continue;
  54. }
  55. if (!currBlock.Exit)
  56. {
  57. // If we have a block after the current one, set the limit address.
  58. ulong limitAddress = ulong.MaxValue;
  59. if (nBlkIndex != blocks.Count)
  60. {
  61. Block nBlock = blocks[nBlkIndex];
  62. int nextIndex = nBlkIndex + 1;
  63. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  64. {
  65. limitAddress = blocks[nextIndex].Address;
  66. }
  67. else if (nBlock.Address > currBlock.Address)
  68. {
  69. limitAddress = blocks[nBlkIndex].Address;
  70. }
  71. }
  72. FillBlock(memory, mode, currBlock, limitAddress);
  73. opsCount += currBlock.OpCodes.Count;
  74. if (currBlock.OpCodes.Count != 0)
  75. {
  76. // Set child blocks. "Branch" is the block the branch instruction
  77. // points to (when taken), "Next" is the block at the next address,
  78. // executed when the branch is not taken. For Unconditional Branches
  79. // (except BL/BLR that are sub calls) or end of executable, Next is null.
  80. OpCode lastOp = currBlock.GetLastOp();
  81. bool isCall = IsCall(lastOp);
  82. if (lastOp is IOpCodeBImm op && !isCall)
  83. {
  84. currBlock.Branch = GetBlock((ulong)op.Immediate);
  85. }
  86. if (!IsUnconditionalBranch(lastOp) || isCall)
  87. {
  88. currBlock.Next = GetBlock(currBlock.EndAddress);
  89. }
  90. }
  91. }
  92. // Insert the new block on the list (sorted by address).
  93. if (blocks.Count != 0)
  94. {
  95. Block nBlock = blocks[nBlkIndex];
  96. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  97. }
  98. else
  99. {
  100. blocks.Add(currBlock);
  101. }
  102. }
  103. if (blocks.Count == 0)
  104. {
  105. throw new InvalidOperationException($"Decoded 0 blocks. Entry point = 0x{address:X}.");
  106. }
  107. if (!singleBlock)
  108. {
  109. return TailCallRemover.RunPass(address, blocks);
  110. }
  111. return blocks.ToArray();
  112. }
  113. public static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  114. {
  115. index = 0;
  116. int left = 0;
  117. int right = blocks.Count - 1;
  118. while (left <= right)
  119. {
  120. int size = right - left;
  121. int middle = left + (size >> 1);
  122. Block block = blocks[middle];
  123. index = middle;
  124. if (address >= block.Address && address < block.EndAddress)
  125. {
  126. return true;
  127. }
  128. if (address < block.Address)
  129. {
  130. right = middle - 1;
  131. }
  132. else
  133. {
  134. left = middle + 1;
  135. }
  136. }
  137. return false;
  138. }
  139. private static void FillBlock(
  140. IMemoryManager memory,
  141. ExecutionMode mode,
  142. Block block,
  143. ulong limitAddress)
  144. {
  145. ulong address = block.Address;
  146. OpCode opCode;
  147. do
  148. {
  149. if (address >= limitAddress)
  150. {
  151. break;
  152. }
  153. opCode = DecodeOpCode(memory, address, mode);
  154. block.OpCodes.Add(opCode);
  155. address += (ulong)opCode.OpCodeSizeInBytes;
  156. }
  157. while (!(IsBranch(opCode) || IsException(opCode)));
  158. block.EndAddress = address;
  159. }
  160. private static bool IsBranch(OpCode opCode)
  161. {
  162. return opCode is OpCodeBImm ||
  163. opCode is OpCodeBReg || IsAarch32Branch(opCode);
  164. }
  165. private static bool IsUnconditionalBranch(OpCode opCode)
  166. {
  167. return opCode is OpCodeBImmAl ||
  168. opCode is OpCodeBReg || IsAarch32UnconditionalBranch(opCode);
  169. }
  170. private static bool IsAarch32UnconditionalBranch(OpCode opCode)
  171. {
  172. if (!(opCode is OpCode32 op))
  173. {
  174. return false;
  175. }
  176. // Note: On ARM32, most instructions have conditional execution,
  177. // so there's no "Always" (unconditional) branch like on ARM64.
  178. // We need to check if the condition is "Always" instead.
  179. return IsAarch32Branch(op) && op.Cond >= Condition.Al;
  180. }
  181. private static bool IsAarch32Branch(OpCode opCode)
  182. {
  183. // Note: On ARM32, most ALU operations can write to R15 (PC),
  184. // so we must consider such operations as a branch in potential aswell.
  185. if (opCode is IOpCode32Alu opAlu && opAlu.Rd == RegisterAlias.Aarch32Pc)
  186. {
  187. return true;
  188. }
  189. // Same thing for memory operations. We have the cases where PC is a target
  190. // register (Rt == 15 or (mask & (1 << 15)) != 0), and cases where there is
  191. // a write back to PC (wback == true && Rn == 15), however the later may
  192. // be "undefined" depending on the CPU, so compilers should not produce that.
  193. if (opCode is IOpCode32Mem || opCode is IOpCode32MemMult)
  194. {
  195. int rt, rn;
  196. bool wBack, isLoad;
  197. if (opCode is IOpCode32Mem opMem)
  198. {
  199. rt = opMem.Rt;
  200. rn = opMem.Rn;
  201. wBack = opMem.WBack;
  202. isLoad = opMem.IsLoad;
  203. // For the dual load, we also need to take into account the
  204. // case were Rt2 == 15 (PC).
  205. if (rt == 14 && opMem.Instruction.Name == InstName.Ldrd)
  206. {
  207. rt = RegisterAlias.Aarch32Pc;
  208. }
  209. }
  210. else if (opCode is IOpCode32MemMult opMemMult)
  211. {
  212. const int pcMask = 1 << RegisterAlias.Aarch32Pc;
  213. rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0;
  214. rn = opMemMult.Rn;
  215. wBack = opMemMult.PostOffset != 0;
  216. isLoad = opMemMult.IsLoad;
  217. }
  218. else
  219. {
  220. throw new NotImplementedException($"The type \"{opCode.GetType().Name}\" is not implemented on the decoder.");
  221. }
  222. if ((rt == RegisterAlias.Aarch32Pc && isLoad) ||
  223. (rn == RegisterAlias.Aarch32Pc && wBack))
  224. {
  225. return true;
  226. }
  227. }
  228. // Explicit branch instructions.
  229. return opCode is IOpCode32BImm ||
  230. opCode is IOpCode32BReg;
  231. }
  232. private static bool IsCall(OpCode opCode)
  233. {
  234. return opCode.Instruction.Name == InstName.Bl ||
  235. opCode.Instruction.Name == InstName.Blr ||
  236. opCode.Instruction.Name == InstName.Blx;
  237. }
  238. private static bool IsException(OpCode opCode)
  239. {
  240. return opCode.Instruction.Name == InstName.Brk ||
  241. opCode.Instruction.Name == InstName.Svc ||
  242. opCode.Instruction.Name == InstName.Trap ||
  243. opCode.Instruction.Name == InstName.Und;
  244. }
  245. public static OpCode DecodeOpCode(IMemoryManager memory, ulong address, ExecutionMode mode)
  246. {
  247. int opCode = memory.Read<int>(address);
  248. InstDescriptor inst;
  249. OpCodeTable.MakeOp makeOp;
  250. if (mode == ExecutionMode.Aarch64)
  251. {
  252. (inst, makeOp) = OpCodeTable.GetInstA64(opCode);
  253. }
  254. else
  255. {
  256. if (mode == ExecutionMode.Aarch32Arm)
  257. {
  258. (inst, makeOp) = OpCodeTable.GetInstA32(opCode);
  259. }
  260. else /* if (mode == ExecutionMode.Aarch32Thumb) */
  261. {
  262. (inst, makeOp) = OpCodeTable.GetInstT32(opCode);
  263. }
  264. }
  265. if (makeOp != null)
  266. {
  267. return (OpCode)makeOp(inst, address, opCode);
  268. }
  269. else
  270. {
  271. return new OpCode(inst, address, opCode);
  272. }
  273. }
  274. }
  275. }