Decoder.cs 13 KB

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