blob: c8f7a0f41f903506a3e43b3d616d804cece3d355 [file] [log] [blame]
Serhiy Storchakab0f80b02016-05-24 09:15:14 +03001/* This file contains code shared by the compiler and the peephole
2 optimizer.
3 */
4
Serhiy Storchakaab874002016-09-11 13:48:15 +03005#ifdef WORDS_BIGENDIAN
6# define PACKOPARG(opcode, oparg) ((_Py_CODEUNIT)(((opcode) << 8) | (oparg)))
7#else
8# define PACKOPARG(opcode, oparg) ((_Py_CODEUNIT)(((oparg) << 8) | (opcode)))
9#endif
10
11/* Minimum number of code units necessary to encode instruction with
12 EXTENDED_ARGs */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030013static int
14instrsize(unsigned int oparg)
15{
Serhiy Storchakaab874002016-09-11 13:48:15 +030016 return oparg <= 0xff ? 1 :
17 oparg <= 0xffff ? 2 :
18 oparg <= 0xffffff ? 3 :
19 4;
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030020}
21
22/* Spits out op/oparg pair using ilen bytes. codestr should be pointed at the
23 desired location of the first EXTENDED_ARG */
24static void
Serhiy Storchakaab874002016-09-11 13:48:15 +030025write_op_arg(_Py_CODEUNIT *codestr, unsigned char opcode,
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030026 unsigned int oparg, int ilen)
27{
28 switch (ilen) {
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030029 case 4:
Serhiy Storchakaab874002016-09-11 13:48:15 +030030 *codestr++ = PACKOPARG(EXTENDED_ARG, (oparg >> 24) & 0xff);
Stefan Krahf432a322017-08-21 13:09:59 +020031 /* fall through */
Serhiy Storchakaab874002016-09-11 13:48:15 +030032 case 3:
33 *codestr++ = PACKOPARG(EXTENDED_ARG, (oparg >> 16) & 0xff);
Stefan Krahf432a322017-08-21 13:09:59 +020034 /* fall through */
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030035 case 2:
Serhiy Storchakaab874002016-09-11 13:48:15 +030036 *codestr++ = PACKOPARG(EXTENDED_ARG, (oparg >> 8) & 0xff);
Stefan Krahf432a322017-08-21 13:09:59 +020037 /* fall through */
Serhiy Storchakaab874002016-09-11 13:48:15 +030038 case 1:
39 *codestr++ = PACKOPARG(opcode, oparg & 0xff);
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030040 break;
41 default:
Barry Warsawb2e57942017-09-14 18:13:16 -070042 Py_UNREACHABLE();
Serhiy Storchakab0f80b02016-05-24 09:15:14 +030043 }
44}