Decoder.cs 12 KB

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