Decoder.cs 12 KB

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