flowgraph.c 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229
  1. #include <stdbool.h>
  2. #include "Python.h"
  3. #include "pycore_flowgraph.h"
  4. #include "pycore_compile.h"
  5. #include "pycore_pymem.h" // _PyMem_IsPtrFreed()
  6. #include "pycore_opcode_utils.h"
  7. #define NEED_OPCODE_METADATA
  8. #include "opcode_metadata.h" // _PyOpcode_opcode_metadata, _PyOpcode_num_popped/pushed
  9. #undef NEED_OPCODE_METADATA
  10. #undef SUCCESS
  11. #undef ERROR
  12. #define SUCCESS 0
  13. #define ERROR -1
  14. #define RETURN_IF_ERROR(X) \
  15. if ((X) == -1) { \
  16. return ERROR; \
  17. }
  18. #define DEFAULT_BLOCK_SIZE 16
  19. typedef _PyCompilerSrcLocation location;
  20. typedef _PyCfgJumpTargetLabel jump_target_label;
  21. typedef _PyCfgBasicblock basicblock;
  22. typedef _PyCfgBuilder cfg_builder;
  23. typedef _PyCfgInstruction cfg_instr;
  24. static const jump_target_label NO_LABEL = {-1};
  25. #define SAME_LABEL(L1, L2) ((L1).id == (L2).id)
  26. #define IS_LABEL(L) (!SAME_LABEL((L), (NO_LABEL)))
  27. static inline int
  28. is_block_push(cfg_instr *i)
  29. {
  30. return IS_BLOCK_PUSH_OPCODE(i->i_opcode);
  31. }
  32. static inline int
  33. is_jump(cfg_instr *i)
  34. {
  35. return IS_JUMP_OPCODE(i->i_opcode);
  36. }
  37. /* One arg*/
  38. #define INSTR_SET_OP1(I, OP, ARG) \
  39. do { \
  40. assert(HAS_ARG(OP)); \
  41. _PyCfgInstruction *_instr__ptr_ = (I); \
  42. _instr__ptr_->i_opcode = (OP); \
  43. _instr__ptr_->i_oparg = (ARG); \
  44. } while (0);
  45. /* No args*/
  46. #define INSTR_SET_OP0(I, OP) \
  47. do { \
  48. assert(!HAS_ARG(OP)); \
  49. _PyCfgInstruction *_instr__ptr_ = (I); \
  50. _instr__ptr_->i_opcode = (OP); \
  51. _instr__ptr_->i_oparg = 0; \
  52. } while (0);
  53. /***** Blocks *****/
  54. /* Returns the offset of the next instruction in the current block's
  55. b_instr array. Resizes the b_instr as necessary.
  56. Returns -1 on failure.
  57. */
  58. static int
  59. basicblock_next_instr(basicblock *b)
  60. {
  61. assert(b != NULL);
  62. RETURN_IF_ERROR(
  63. _PyCompile_EnsureArrayLargeEnough(
  64. b->b_iused + 1,
  65. (void**)&b->b_instr,
  66. &b->b_ialloc,
  67. DEFAULT_BLOCK_SIZE,
  68. sizeof(cfg_instr)));
  69. return b->b_iused++;
  70. }
  71. /* Allocate a new block and return a pointer to it.
  72. Returns NULL on error.
  73. */
  74. static basicblock *
  75. cfg_builder_new_block(cfg_builder *g)
  76. {
  77. basicblock *b = (basicblock *)PyObject_Calloc(1, sizeof(basicblock));
  78. if (b == NULL) {
  79. PyErr_NoMemory();
  80. return NULL;
  81. }
  82. /* Extend the singly linked list of blocks with new block. */
  83. b->b_list = g->g_block_list;
  84. g->g_block_list = b;
  85. b->b_label = NO_LABEL;
  86. return b;
  87. }
  88. static int
  89. basicblock_addop(basicblock *b, int opcode, int oparg, location loc)
  90. {
  91. assert(IS_WITHIN_OPCODE_RANGE(opcode));
  92. assert(!IS_ASSEMBLER_OPCODE(opcode));
  93. assert(HAS_ARG(opcode) || HAS_TARGET(opcode) || oparg == 0);
  94. assert(0 <= oparg && oparg < (1 << 30));
  95. int off = basicblock_next_instr(b);
  96. if (off < 0) {
  97. return ERROR;
  98. }
  99. cfg_instr *i = &b->b_instr[off];
  100. i->i_opcode = opcode;
  101. i->i_oparg = oparg;
  102. i->i_target = NULL;
  103. i->i_loc = loc;
  104. return SUCCESS;
  105. }
  106. static inline int
  107. basicblock_append_instructions(basicblock *target, basicblock *source)
  108. {
  109. for (int i = 0; i < source->b_iused; i++) {
  110. int n = basicblock_next_instr(target);
  111. if (n < 0) {
  112. return ERROR;
  113. }
  114. target->b_instr[n] = source->b_instr[i];
  115. }
  116. return SUCCESS;
  117. }
  118. static basicblock *
  119. copy_basicblock(cfg_builder *g, basicblock *block)
  120. {
  121. /* Cannot copy a block if it has a fallthrough, since
  122. * a block can only have one fallthrough predecessor.
  123. */
  124. assert(BB_NO_FALLTHROUGH(block));
  125. basicblock *result = cfg_builder_new_block(g);
  126. if (result == NULL) {
  127. return NULL;
  128. }
  129. if (basicblock_append_instructions(result, block) < 0) {
  130. return NULL;
  131. }
  132. return result;
  133. }
  134. int
  135. _PyBasicblock_InsertInstruction(basicblock *block, int pos, cfg_instr *instr) {
  136. RETURN_IF_ERROR(basicblock_next_instr(block));
  137. for (int i = block->b_iused - 1; i > pos; i--) {
  138. block->b_instr[i] = block->b_instr[i-1];
  139. }
  140. block->b_instr[pos] = *instr;
  141. return SUCCESS;
  142. }
  143. static int
  144. instr_size(cfg_instr *instruction)
  145. {
  146. return _PyCompile_InstrSize(instruction->i_opcode, instruction->i_oparg);
  147. }
  148. static int
  149. blocksize(basicblock *b)
  150. {
  151. int size = 0;
  152. for (int i = 0; i < b->b_iused; i++) {
  153. size += instr_size(&b->b_instr[i]);
  154. }
  155. return size;
  156. }
  157. /* For debugging purposes only */
  158. #if 0
  159. static void
  160. dump_instr(cfg_instr *i)
  161. {
  162. const char *jump = is_jump(i) ? "jump " : "";
  163. char arg[128];
  164. *arg = '\0';
  165. if (HAS_ARG(i->i_opcode)) {
  166. sprintf(arg, "arg: %d ", i->i_oparg);
  167. }
  168. if (HAS_TARGET(i->i_opcode)) {
  169. sprintf(arg, "target: %p [%d] ", i->i_target, i->i_oparg);
  170. }
  171. fprintf(stderr, "line: %d, opcode: %d %s%s\n",
  172. i->i_loc.lineno, i->i_opcode, arg, jump);
  173. }
  174. static inline int
  175. basicblock_returns(const basicblock *b) {
  176. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  177. return last && (last->i_opcode == RETURN_VALUE || last->i_opcode == RETURN_CONST);
  178. }
  179. static void
  180. dump_basicblock(const basicblock *b)
  181. {
  182. const char *b_return = basicblock_returns(b) ? "return " : "";
  183. fprintf(stderr, "%d: [EH=%d CLD=%d WRM=%d NO_FT=%d %p] used: %d, depth: %d, offset: %d %s\n",
  184. b->b_label.id, b->b_except_handler, b->b_cold, b->b_warm, BB_NO_FALLTHROUGH(b), b, b->b_iused,
  185. b->b_startdepth, b->b_offset, b_return);
  186. if (b->b_instr) {
  187. int i;
  188. for (i = 0; i < b->b_iused; i++) {
  189. fprintf(stderr, " [%02d] ", i);
  190. dump_instr(b->b_instr + i);
  191. }
  192. }
  193. }
  194. void
  195. _PyCfgBuilder_DumpGraph(const basicblock *entryblock)
  196. {
  197. for (const basicblock *b = entryblock; b != NULL; b = b->b_next) {
  198. dump_basicblock(b);
  199. }
  200. }
  201. #endif
  202. /***** CFG construction and modification *****/
  203. static basicblock *
  204. cfg_builder_use_next_block(cfg_builder *g, basicblock *block)
  205. {
  206. assert(block != NULL);
  207. g->g_curblock->b_next = block;
  208. g->g_curblock = block;
  209. return block;
  210. }
  211. cfg_instr *
  212. _PyCfg_BasicblockLastInstr(const basicblock *b) {
  213. assert(b->b_iused >= 0);
  214. if (b->b_iused > 0) {
  215. assert(b->b_instr != NULL);
  216. return &b->b_instr[b->b_iused - 1];
  217. }
  218. return NULL;
  219. }
  220. static inline int
  221. basicblock_exits_scope(const basicblock *b) {
  222. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  223. return last && IS_SCOPE_EXIT_OPCODE(last->i_opcode);
  224. }
  225. static bool
  226. cfg_builder_current_block_is_terminated(cfg_builder *g)
  227. {
  228. cfg_instr *last = _PyCfg_BasicblockLastInstr(g->g_curblock);
  229. if (last && IS_TERMINATOR_OPCODE(last->i_opcode)) {
  230. return true;
  231. }
  232. if (IS_LABEL(g->g_current_label)) {
  233. if (last || IS_LABEL(g->g_curblock->b_label)) {
  234. return true;
  235. }
  236. else {
  237. /* current block is empty, label it */
  238. g->g_curblock->b_label = g->g_current_label;
  239. g->g_current_label = NO_LABEL;
  240. }
  241. }
  242. return false;
  243. }
  244. static int
  245. cfg_builder_maybe_start_new_block(cfg_builder *g)
  246. {
  247. if (cfg_builder_current_block_is_terminated(g)) {
  248. basicblock *b = cfg_builder_new_block(g);
  249. if (b == NULL) {
  250. return ERROR;
  251. }
  252. b->b_label = g->g_current_label;
  253. g->g_current_label = NO_LABEL;
  254. cfg_builder_use_next_block(g, b);
  255. }
  256. return SUCCESS;
  257. }
  258. #ifndef NDEBUG
  259. static bool
  260. cfg_builder_check(cfg_builder *g)
  261. {
  262. assert(g->g_entryblock->b_iused > 0);
  263. for (basicblock *block = g->g_block_list; block != NULL; block = block->b_list) {
  264. assert(!_PyMem_IsPtrFreed(block));
  265. if (block->b_instr != NULL) {
  266. assert(block->b_ialloc > 0);
  267. assert(block->b_iused >= 0);
  268. assert(block->b_ialloc >= block->b_iused);
  269. }
  270. else {
  271. assert (block->b_iused == 0);
  272. assert (block->b_ialloc == 0);
  273. }
  274. }
  275. return true;
  276. }
  277. #endif
  278. int
  279. _PyCfgBuilder_Init(cfg_builder *g)
  280. {
  281. g->g_block_list = NULL;
  282. basicblock *block = cfg_builder_new_block(g);
  283. if (block == NULL) {
  284. return ERROR;
  285. }
  286. g->g_curblock = g->g_entryblock = block;
  287. g->g_current_label = NO_LABEL;
  288. return SUCCESS;
  289. }
  290. void
  291. _PyCfgBuilder_Fini(cfg_builder* g)
  292. {
  293. assert(cfg_builder_check(g));
  294. basicblock *b = g->g_block_list;
  295. while (b != NULL) {
  296. if (b->b_instr) {
  297. PyObject_Free((void *)b->b_instr);
  298. }
  299. basicblock *next = b->b_list;
  300. PyObject_Free((void *)b);
  301. b = next;
  302. }
  303. }
  304. int
  305. _PyCfgBuilder_UseLabel(cfg_builder *g, jump_target_label lbl)
  306. {
  307. g->g_current_label = lbl;
  308. return cfg_builder_maybe_start_new_block(g);
  309. }
  310. int
  311. _PyCfgBuilder_Addop(cfg_builder *g, int opcode, int oparg, location loc)
  312. {
  313. RETURN_IF_ERROR(cfg_builder_maybe_start_new_block(g));
  314. return basicblock_addop(g->g_curblock, opcode, oparg, loc);
  315. }
  316. /***** debugging helpers *****/
  317. #ifndef NDEBUG
  318. static int remove_redundant_nops(basicblock *bb);
  319. /*
  320. static bool
  321. no_redundant_nops(cfg_builder *g) {
  322. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  323. if (remove_redundant_nops(b) != 0) {
  324. return false;
  325. }
  326. }
  327. return true;
  328. }
  329. */
  330. static bool
  331. no_empty_basic_blocks(cfg_builder *g) {
  332. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  333. if (b->b_iused == 0) {
  334. return false;
  335. }
  336. }
  337. return true;
  338. }
  339. static bool
  340. no_redundant_jumps(cfg_builder *g) {
  341. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  342. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  343. if (last != NULL) {
  344. if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
  345. assert(last->i_target != b->b_next);
  346. if (last->i_target == b->b_next) {
  347. return false;
  348. }
  349. }
  350. }
  351. }
  352. return true;
  353. }
  354. #endif
  355. /***** CFG preprocessing (jump targets and exceptions) *****/
  356. static int
  357. normalize_jumps_in_block(cfg_builder *g, basicblock *b) {
  358. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  359. if (last == NULL || !is_jump(last)) {
  360. return SUCCESS;
  361. }
  362. assert(!IS_ASSEMBLER_OPCODE(last->i_opcode));
  363. bool is_forward = last->i_target->b_visited == 0;
  364. switch(last->i_opcode) {
  365. case JUMP:
  366. last->i_opcode = is_forward ? JUMP_FORWARD : JUMP_BACKWARD;
  367. return SUCCESS;
  368. case JUMP_NO_INTERRUPT:
  369. last->i_opcode = is_forward ?
  370. JUMP_FORWARD : JUMP_BACKWARD_NO_INTERRUPT;
  371. return SUCCESS;
  372. }
  373. int reversed_opcode = 0;
  374. switch(last->i_opcode) {
  375. case POP_JUMP_IF_NOT_NONE:
  376. reversed_opcode = POP_JUMP_IF_NONE;
  377. break;
  378. case POP_JUMP_IF_NONE:
  379. reversed_opcode = POP_JUMP_IF_NOT_NONE;
  380. break;
  381. case POP_JUMP_IF_FALSE:
  382. reversed_opcode = POP_JUMP_IF_TRUE;
  383. break;
  384. case POP_JUMP_IF_TRUE:
  385. reversed_opcode = POP_JUMP_IF_FALSE;
  386. break;
  387. }
  388. if (is_forward) {
  389. return SUCCESS;
  390. }
  391. /* transform 'conditional jump T' to
  392. * 'reversed_jump b_next' followed by 'jump_backwards T'
  393. */
  394. basicblock *target = last->i_target;
  395. basicblock *backwards_jump = cfg_builder_new_block(g);
  396. if (backwards_jump == NULL) {
  397. return ERROR;
  398. }
  399. basicblock_addop(backwards_jump, JUMP, target->b_label.id, last->i_loc);
  400. backwards_jump->b_instr[0].i_target = target;
  401. last->i_opcode = reversed_opcode;
  402. last->i_target = b->b_next;
  403. backwards_jump->b_cold = b->b_cold;
  404. backwards_jump->b_next = b->b_next;
  405. b->b_next = backwards_jump;
  406. return SUCCESS;
  407. }
  408. static int
  409. normalize_jumps(_PyCfgBuilder *g)
  410. {
  411. basicblock *entryblock = g->g_entryblock;
  412. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  413. b->b_visited = 0;
  414. }
  415. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  416. b->b_visited = 1;
  417. RETURN_IF_ERROR(normalize_jumps_in_block(g, b));
  418. }
  419. return SUCCESS;
  420. }
  421. static void
  422. resolve_jump_offsets(basicblock *entryblock)
  423. {
  424. int bsize, totsize, extended_arg_recompile;
  425. /* Compute the size of each block and fixup jump args.
  426. Replace block pointer with position in bytecode. */
  427. do {
  428. totsize = 0;
  429. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  430. bsize = blocksize(b);
  431. b->b_offset = totsize;
  432. totsize += bsize;
  433. }
  434. extended_arg_recompile = 0;
  435. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  436. bsize = b->b_offset;
  437. for (int i = 0; i < b->b_iused; i++) {
  438. cfg_instr *instr = &b->b_instr[i];
  439. int isize = instr_size(instr);
  440. /* jump offsets are computed relative to
  441. * the instruction pointer after fetching
  442. * the jump instruction.
  443. */
  444. bsize += isize;
  445. if (is_jump(instr)) {
  446. instr->i_oparg = instr->i_target->b_offset;
  447. if (instr->i_oparg < bsize) {
  448. assert(IS_BACKWARDS_JUMP_OPCODE(instr->i_opcode));
  449. instr->i_oparg = bsize - instr->i_oparg;
  450. }
  451. else {
  452. assert(!IS_BACKWARDS_JUMP_OPCODE(instr->i_opcode));
  453. instr->i_oparg -= bsize;
  454. }
  455. if (instr_size(instr) != isize) {
  456. extended_arg_recompile = 1;
  457. }
  458. }
  459. }
  460. }
  461. /* XXX: This is an awful hack that could hurt performance, but
  462. on the bright side it should work until we come up
  463. with a better solution.
  464. The issue is that in the first loop blocksize() is called
  465. which calls instr_size() which requires i_oparg be set
  466. appropriately. There is a bootstrap problem because
  467. i_oparg is calculated in the second loop above.
  468. So we loop until we stop seeing new EXTENDED_ARGs.
  469. The only EXTENDED_ARGs that could be popping up are
  470. ones in jump instructions. So this should converge
  471. fairly quickly.
  472. */
  473. } while (extended_arg_recompile);
  474. }
  475. int
  476. _PyCfg_ResolveJumps(_PyCfgBuilder *g)
  477. {
  478. RETURN_IF_ERROR(normalize_jumps(g));
  479. assert(no_redundant_jumps(g));
  480. resolve_jump_offsets(g->g_entryblock);
  481. return SUCCESS;
  482. }
  483. static int
  484. check_cfg(cfg_builder *g) {
  485. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  486. /* Raise SystemError if jump or exit is not last instruction in the block. */
  487. for (int i = 0; i < b->b_iused; i++) {
  488. int opcode = b->b_instr[i].i_opcode;
  489. assert(!IS_ASSEMBLER_OPCODE(opcode));
  490. if (IS_TERMINATOR_OPCODE(opcode)) {
  491. if (i != b->b_iused - 1) {
  492. PyErr_SetString(PyExc_SystemError, "malformed control flow graph.");
  493. return ERROR;
  494. }
  495. }
  496. }
  497. }
  498. return SUCCESS;
  499. }
  500. static int
  501. get_max_label(basicblock *entryblock)
  502. {
  503. int lbl = -1;
  504. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  505. if (b->b_label.id > lbl) {
  506. lbl = b->b_label.id;
  507. }
  508. }
  509. return lbl;
  510. }
  511. /* Calculate the actual jump target from the target_label */
  512. static int
  513. translate_jump_labels_to_targets(basicblock *entryblock)
  514. {
  515. int max_label = get_max_label(entryblock);
  516. size_t mapsize = sizeof(basicblock *) * (max_label + 1);
  517. basicblock **label2block = (basicblock **)PyMem_Malloc(mapsize);
  518. if (!label2block) {
  519. PyErr_NoMemory();
  520. return ERROR;
  521. }
  522. memset(label2block, 0, mapsize);
  523. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  524. if (b->b_label.id >= 0) {
  525. label2block[b->b_label.id] = b;
  526. }
  527. }
  528. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  529. for (int i = 0; i < b->b_iused; i++) {
  530. cfg_instr *instr = &b->b_instr[i];
  531. assert(instr->i_target == NULL);
  532. if (HAS_TARGET(instr->i_opcode)) {
  533. int lbl = instr->i_oparg;
  534. assert(lbl >= 0 && lbl <= max_label);
  535. instr->i_target = label2block[lbl];
  536. assert(instr->i_target != NULL);
  537. assert(instr->i_target->b_label.id == lbl);
  538. }
  539. }
  540. }
  541. PyMem_Free(label2block);
  542. return SUCCESS;
  543. }
  544. int
  545. _PyCfg_JumpLabelsToTargets(basicblock *entryblock)
  546. {
  547. return translate_jump_labels_to_targets(entryblock);
  548. }
  549. static int
  550. mark_except_handlers(basicblock *entryblock) {
  551. #ifndef NDEBUG
  552. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  553. assert(!b->b_except_handler);
  554. }
  555. #endif
  556. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  557. for (int i=0; i < b->b_iused; i++) {
  558. cfg_instr *instr = &b->b_instr[i];
  559. if (is_block_push(instr)) {
  560. instr->i_target->b_except_handler = 1;
  561. }
  562. }
  563. }
  564. return SUCCESS;
  565. }
  566. typedef _PyCfgExceptStack ExceptStack;
  567. static basicblock *
  568. push_except_block(ExceptStack *stack, cfg_instr *setup) {
  569. assert(is_block_push(setup));
  570. int opcode = setup->i_opcode;
  571. basicblock * target = setup->i_target;
  572. if (opcode == SETUP_WITH || opcode == SETUP_CLEANUP) {
  573. target->b_preserve_lasti = 1;
  574. }
  575. assert(stack->depth <= CO_MAXBLOCKS);
  576. stack->handlers[++stack->depth] = target;
  577. return target;
  578. }
  579. static basicblock *
  580. pop_except_block(ExceptStack *stack) {
  581. assert(stack->depth > 0);
  582. return stack->handlers[--stack->depth];
  583. }
  584. static basicblock *
  585. except_stack_top(ExceptStack *stack) {
  586. return stack->handlers[stack->depth];
  587. }
  588. static ExceptStack *
  589. make_except_stack(void) {
  590. ExceptStack *new = PyMem_Malloc(sizeof(ExceptStack));
  591. if (new == NULL) {
  592. PyErr_NoMemory();
  593. return NULL;
  594. }
  595. new->depth = 0;
  596. new->handlers[0] = NULL;
  597. return new;
  598. }
  599. static ExceptStack *
  600. copy_except_stack(ExceptStack *stack) {
  601. ExceptStack *copy = PyMem_Malloc(sizeof(ExceptStack));
  602. if (copy == NULL) {
  603. PyErr_NoMemory();
  604. return NULL;
  605. }
  606. memcpy(copy, stack, sizeof(ExceptStack));
  607. return copy;
  608. }
  609. static basicblock**
  610. make_cfg_traversal_stack(basicblock *entryblock) {
  611. int nblocks = 0;
  612. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  613. b->b_visited = 0;
  614. nblocks++;
  615. }
  616. basicblock **stack = (basicblock **)PyMem_Malloc(sizeof(basicblock *) * nblocks);
  617. if (!stack) {
  618. PyErr_NoMemory();
  619. }
  620. return stack;
  621. }
  622. Py_LOCAL_INLINE(void)
  623. stackdepth_push(basicblock ***sp, basicblock *b, int depth)
  624. {
  625. assert(b->b_startdepth < 0 || b->b_startdepth == depth);
  626. if (b->b_startdepth < depth && b->b_startdepth < 100) {
  627. assert(b->b_startdepth < 0);
  628. b->b_startdepth = depth;
  629. *(*sp)++ = b;
  630. }
  631. }
  632. /* Find the flow path that needs the largest stack. We assume that
  633. * cycles in the flow graph have no net effect on the stack depth.
  634. */
  635. int
  636. _PyCfg_Stackdepth(basicblock *entryblock, int code_flags)
  637. {
  638. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  639. b->b_startdepth = INT_MIN;
  640. }
  641. basicblock **stack = make_cfg_traversal_stack(entryblock);
  642. if (!stack) {
  643. return ERROR;
  644. }
  645. int maxdepth = 0;
  646. basicblock **sp = stack;
  647. if (code_flags & (CO_GENERATOR | CO_COROUTINE | CO_ASYNC_GENERATOR)) {
  648. stackdepth_push(&sp, entryblock, 1);
  649. } else {
  650. stackdepth_push(&sp, entryblock, 0);
  651. }
  652. while (sp != stack) {
  653. basicblock *b = *--sp;
  654. int depth = b->b_startdepth;
  655. assert(depth >= 0);
  656. basicblock *next = b->b_next;
  657. for (int i = 0; i < b->b_iused; i++) {
  658. cfg_instr *instr = &b->b_instr[i];
  659. int effect = PyCompile_OpcodeStackEffectWithJump(instr->i_opcode, instr->i_oparg, 0);
  660. if (effect == PY_INVALID_STACK_EFFECT) {
  661. PyErr_Format(PyExc_SystemError,
  662. "compiler PyCompile_OpcodeStackEffectWithJump(opcode=%d, arg=%i) failed",
  663. instr->i_opcode, instr->i_oparg);
  664. return ERROR;
  665. }
  666. int new_depth = depth + effect;
  667. assert(new_depth >= 0); /* invalid code or bug in stackdepth() */
  668. if (new_depth > maxdepth) {
  669. maxdepth = new_depth;
  670. }
  671. if (HAS_TARGET(instr->i_opcode)) {
  672. effect = PyCompile_OpcodeStackEffectWithJump(instr->i_opcode, instr->i_oparg, 1);
  673. assert(effect != PY_INVALID_STACK_EFFECT);
  674. int target_depth = depth + effect;
  675. assert(target_depth >= 0); /* invalid code or bug in stackdepth() */
  676. if (target_depth > maxdepth) {
  677. maxdepth = target_depth;
  678. }
  679. stackdepth_push(&sp, instr->i_target, target_depth);
  680. }
  681. depth = new_depth;
  682. assert(!IS_ASSEMBLER_OPCODE(instr->i_opcode));
  683. if (IS_UNCONDITIONAL_JUMP_OPCODE(instr->i_opcode) ||
  684. IS_SCOPE_EXIT_OPCODE(instr->i_opcode))
  685. {
  686. /* remaining code is dead */
  687. next = NULL;
  688. break;
  689. }
  690. }
  691. if (next != NULL) {
  692. assert(BB_HAS_FALLTHROUGH(b));
  693. stackdepth_push(&sp, next, depth);
  694. }
  695. }
  696. PyMem_Free(stack);
  697. return maxdepth;
  698. }
  699. static int
  700. label_exception_targets(basicblock *entryblock) {
  701. basicblock **todo_stack = make_cfg_traversal_stack(entryblock);
  702. if (todo_stack == NULL) {
  703. return ERROR;
  704. }
  705. ExceptStack *except_stack = make_except_stack();
  706. if (except_stack == NULL) {
  707. PyMem_Free(todo_stack);
  708. PyErr_NoMemory();
  709. return ERROR;
  710. }
  711. except_stack->depth = 0;
  712. todo_stack[0] = entryblock;
  713. entryblock->b_visited = 1;
  714. entryblock->b_exceptstack = except_stack;
  715. basicblock **todo = &todo_stack[1];
  716. basicblock *handler = NULL;
  717. while (todo > todo_stack) {
  718. todo--;
  719. basicblock *b = todo[0];
  720. assert(b->b_visited == 1);
  721. except_stack = b->b_exceptstack;
  722. assert(except_stack != NULL);
  723. b->b_exceptstack = NULL;
  724. handler = except_stack_top(except_stack);
  725. for (int i = 0; i < b->b_iused; i++) {
  726. cfg_instr *instr = &b->b_instr[i];
  727. if (is_block_push(instr)) {
  728. if (!instr->i_target->b_visited) {
  729. ExceptStack *copy = copy_except_stack(except_stack);
  730. if (copy == NULL) {
  731. goto error;
  732. }
  733. instr->i_target->b_exceptstack = copy;
  734. todo[0] = instr->i_target;
  735. instr->i_target->b_visited = 1;
  736. todo++;
  737. }
  738. handler = push_except_block(except_stack, instr);
  739. }
  740. else if (instr->i_opcode == POP_BLOCK) {
  741. handler = pop_except_block(except_stack);
  742. }
  743. else if (is_jump(instr)) {
  744. instr->i_except = handler;
  745. assert(i == b->b_iused -1);
  746. if (!instr->i_target->b_visited) {
  747. if (BB_HAS_FALLTHROUGH(b)) {
  748. ExceptStack *copy = copy_except_stack(except_stack);
  749. if (copy == NULL) {
  750. goto error;
  751. }
  752. instr->i_target->b_exceptstack = copy;
  753. }
  754. else {
  755. instr->i_target->b_exceptstack = except_stack;
  756. except_stack = NULL;
  757. }
  758. todo[0] = instr->i_target;
  759. instr->i_target->b_visited = 1;
  760. todo++;
  761. }
  762. }
  763. else {
  764. if (instr->i_opcode == YIELD_VALUE) {
  765. instr->i_oparg = except_stack->depth;
  766. }
  767. instr->i_except = handler;
  768. }
  769. }
  770. if (BB_HAS_FALLTHROUGH(b) && !b->b_next->b_visited) {
  771. assert(except_stack != NULL);
  772. b->b_next->b_exceptstack = except_stack;
  773. todo[0] = b->b_next;
  774. b->b_next->b_visited = 1;
  775. todo++;
  776. }
  777. else if (except_stack != NULL) {
  778. PyMem_Free(except_stack);
  779. }
  780. }
  781. #ifdef Py_DEBUG
  782. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  783. assert(b->b_exceptstack == NULL);
  784. }
  785. #endif
  786. PyMem_Free(todo_stack);
  787. return SUCCESS;
  788. error:
  789. PyMem_Free(todo_stack);
  790. PyMem_Free(except_stack);
  791. return ERROR;
  792. }
  793. /***** CFG optimizations *****/
  794. static int
  795. mark_reachable(basicblock *entryblock) {
  796. basicblock **stack = make_cfg_traversal_stack(entryblock);
  797. if (stack == NULL) {
  798. return ERROR;
  799. }
  800. basicblock **sp = stack;
  801. entryblock->b_predecessors = 1;
  802. *sp++ = entryblock;
  803. while (sp > stack) {
  804. basicblock *b = *(--sp);
  805. b->b_visited = 1;
  806. if (b->b_next && BB_HAS_FALLTHROUGH(b)) {
  807. if (!b->b_next->b_visited) {
  808. assert(b->b_next->b_predecessors == 0);
  809. *sp++ = b->b_next;
  810. }
  811. b->b_next->b_predecessors++;
  812. }
  813. for (int i = 0; i < b->b_iused; i++) {
  814. basicblock *target;
  815. cfg_instr *instr = &b->b_instr[i];
  816. if (is_jump(instr) || is_block_push(instr)) {
  817. target = instr->i_target;
  818. if (!target->b_visited) {
  819. assert(target->b_predecessors == 0 || target == b->b_next);
  820. *sp++ = target;
  821. }
  822. target->b_predecessors++;
  823. }
  824. }
  825. }
  826. PyMem_Free(stack);
  827. return SUCCESS;
  828. }
  829. static void
  830. eliminate_empty_basic_blocks(cfg_builder *g) {
  831. /* Eliminate empty blocks */
  832. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  833. basicblock *next = b->b_next;
  834. while (next && next->b_iused == 0) {
  835. next = next->b_next;
  836. }
  837. b->b_next = next;
  838. }
  839. while(g->g_entryblock && g->g_entryblock->b_iused == 0) {
  840. g->g_entryblock = g->g_entryblock->b_next;
  841. }
  842. int next_lbl = get_max_label(g->g_entryblock) + 1;
  843. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  844. assert(b->b_iused > 0);
  845. for (int i = 0; i < b->b_iused; i++) {
  846. cfg_instr *instr = &b->b_instr[i];
  847. if (HAS_TARGET(instr->i_opcode)) {
  848. basicblock *target = instr->i_target;
  849. while (target->b_iused == 0) {
  850. target = target->b_next;
  851. }
  852. if (instr->i_target != target) {
  853. if (!IS_LABEL(target->b_label)) {
  854. target->b_label.id = next_lbl++;
  855. }
  856. instr->i_target = target;
  857. instr->i_oparg = target->b_label.id;
  858. }
  859. assert(instr->i_target && instr->i_target->b_iused > 0);
  860. }
  861. }
  862. }
  863. }
  864. static int
  865. remove_redundant_nops(basicblock *bb) {
  866. /* Remove NOPs when legal to do so. */
  867. int dest = 0;
  868. int prev_lineno = -1;
  869. for (int src = 0; src < bb->b_iused; src++) {
  870. int lineno = bb->b_instr[src].i_loc.lineno;
  871. if (bb->b_instr[src].i_opcode == NOP) {
  872. /* Eliminate no-op if it doesn't have a line number */
  873. if (lineno < 0) {
  874. continue;
  875. }
  876. /* or, if the previous instruction had the same line number. */
  877. if (prev_lineno == lineno) {
  878. continue;
  879. }
  880. /* or, if the next instruction has same line number or no line number */
  881. if (src < bb->b_iused - 1) {
  882. int next_lineno = bb->b_instr[src+1].i_loc.lineno;
  883. if (next_lineno == lineno) {
  884. continue;
  885. }
  886. if (next_lineno < 0) {
  887. bb->b_instr[src+1].i_loc = bb->b_instr[src].i_loc;
  888. continue;
  889. }
  890. }
  891. else {
  892. basicblock* next = bb->b_next;
  893. while (next && next->b_iused == 0) {
  894. next = next->b_next;
  895. }
  896. /* or if last instruction in BB and next BB has same line number */
  897. if (next) {
  898. location next_loc = NO_LOCATION;
  899. for (int next_i=0; next_i < next->b_iused; next_i++) {
  900. cfg_instr *instr = &next->b_instr[next_i];
  901. if (instr->i_opcode == NOP && instr->i_loc.lineno == NO_LOCATION.lineno) {
  902. /* Skip over NOPs without location, they will be removed */
  903. continue;
  904. }
  905. next_loc = instr->i_loc;
  906. break;
  907. }
  908. if (lineno == next_loc.lineno) {
  909. continue;
  910. }
  911. }
  912. }
  913. }
  914. if (dest != src) {
  915. bb->b_instr[dest] = bb->b_instr[src];
  916. }
  917. dest++;
  918. prev_lineno = lineno;
  919. }
  920. assert(dest <= bb->b_iused);
  921. int num_removed = bb->b_iused - dest;
  922. bb->b_iused = dest;
  923. return num_removed;
  924. }
  925. static int
  926. remove_redundant_nops_and_pairs(basicblock *entryblock)
  927. {
  928. bool done = false;
  929. while (! done) {
  930. done = true;
  931. cfg_instr *prev_instr = NULL;
  932. cfg_instr *instr = NULL;
  933. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  934. remove_redundant_nops(b);
  935. if (IS_LABEL(b->b_label)) {
  936. /* this block is a jump target, forget instr */
  937. instr = NULL;
  938. }
  939. for (int i = 0; i < b->b_iused; i++) {
  940. prev_instr = instr;
  941. instr = &b->b_instr[i];
  942. int prev_opcode = prev_instr ? prev_instr->i_opcode : 0;
  943. int prev_oparg = prev_instr ? prev_instr->i_oparg : 0;
  944. int opcode = instr->i_opcode;
  945. bool is_redundant_pair = false;
  946. if (opcode == POP_TOP) {
  947. if (prev_opcode == LOAD_CONST) {
  948. is_redundant_pair = true;
  949. }
  950. else if (prev_opcode == COPY && prev_oparg == 1) {
  951. is_redundant_pair = true;
  952. }
  953. }
  954. if (is_redundant_pair) {
  955. INSTR_SET_OP0(prev_instr, NOP);
  956. INSTR_SET_OP0(instr, NOP);
  957. done = false;
  958. }
  959. }
  960. if ((instr && is_jump(instr)) || !BB_HAS_FALLTHROUGH(b)) {
  961. instr = NULL;
  962. }
  963. }
  964. }
  965. return SUCCESS;
  966. }
  967. static int
  968. remove_redundant_jumps(cfg_builder *g) {
  969. /* If a non-empty block ends with a jump instruction, check if the next
  970. * non-empty block reached through normal flow control is the target
  971. * of that jump. If it is, then the jump instruction is redundant and
  972. * can be deleted.
  973. */
  974. assert(no_empty_basic_blocks(g));
  975. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  976. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  977. assert(last != NULL);
  978. assert(!IS_ASSEMBLER_OPCODE(last->i_opcode));
  979. if (IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
  980. if (last->i_target == NULL) {
  981. PyErr_SetString(PyExc_SystemError, "jump with NULL target");
  982. return ERROR;
  983. }
  984. if (last->i_target == b->b_next) {
  985. assert(b->b_next->b_iused);
  986. INSTR_SET_OP0(last, NOP);
  987. }
  988. }
  989. }
  990. return SUCCESS;
  991. }
  992. /* Maximum size of basic block that should be copied in optimizer */
  993. #define MAX_COPY_SIZE 4
  994. /* If this block ends with an unconditional jump to a small exit block, then
  995. * remove the jump and extend this block with the target.
  996. * Returns 1 if extended, 0 if no change, and -1 on error.
  997. */
  998. static int
  999. inline_small_exit_blocks(basicblock *bb) {
  1000. cfg_instr *last = _PyCfg_BasicblockLastInstr(bb);
  1001. if (last == NULL) {
  1002. return 0;
  1003. }
  1004. if (!IS_UNCONDITIONAL_JUMP_OPCODE(last->i_opcode)) {
  1005. return 0;
  1006. }
  1007. basicblock *target = last->i_target;
  1008. if (basicblock_exits_scope(target) && target->b_iused <= MAX_COPY_SIZE) {
  1009. INSTR_SET_OP0(last, NOP);
  1010. RETURN_IF_ERROR(basicblock_append_instructions(bb, target));
  1011. return 1;
  1012. }
  1013. return 0;
  1014. }
  1015. // Attempt to eliminate jumps to jumps by updating inst to jump to
  1016. // target->i_target using the provided opcode. Return whether or not the
  1017. // optimization was successful.
  1018. static bool
  1019. jump_thread(cfg_instr *inst, cfg_instr *target, int opcode)
  1020. {
  1021. assert(is_jump(inst));
  1022. assert(is_jump(target));
  1023. // bpo-45773: If inst->i_target == target->i_target, then nothing actually
  1024. // changes (and we fall into an infinite loop):
  1025. if ((inst->i_loc.lineno == target->i_loc.lineno || target->i_loc.lineno == -1) &&
  1026. inst->i_target != target->i_target)
  1027. {
  1028. inst->i_target = target->i_target;
  1029. inst->i_opcode = opcode;
  1030. return true;
  1031. }
  1032. return false;
  1033. }
  1034. static PyObject*
  1035. get_const_value(int opcode, int oparg, PyObject *co_consts)
  1036. {
  1037. PyObject *constant = NULL;
  1038. assert(HAS_CONST(opcode));
  1039. if (opcode == LOAD_CONST) {
  1040. constant = PyList_GET_ITEM(co_consts, oparg);
  1041. }
  1042. if (constant == NULL) {
  1043. PyErr_SetString(PyExc_SystemError,
  1044. "Internal error: failed to get value of a constant");
  1045. return NULL;
  1046. }
  1047. return Py_NewRef(constant);
  1048. }
  1049. /* Replace LOAD_CONST c1, LOAD_CONST c2 ... LOAD_CONST cn, BUILD_TUPLE n
  1050. with LOAD_CONST (c1, c2, ... cn).
  1051. The consts table must still be in list form so that the
  1052. new constant (c1, c2, ... cn) can be appended.
  1053. Called with codestr pointing to the first LOAD_CONST.
  1054. */
  1055. static int
  1056. fold_tuple_on_constants(PyObject *const_cache,
  1057. cfg_instr *inst,
  1058. int n, PyObject *consts)
  1059. {
  1060. /* Pre-conditions */
  1061. assert(PyDict_CheckExact(const_cache));
  1062. assert(PyList_CheckExact(consts));
  1063. assert(inst[n].i_opcode == BUILD_TUPLE);
  1064. assert(inst[n].i_oparg == n);
  1065. for (int i = 0; i < n; i++) {
  1066. if (!HAS_CONST(inst[i].i_opcode)) {
  1067. return SUCCESS;
  1068. }
  1069. }
  1070. /* Buildup new tuple of constants */
  1071. PyObject *newconst = PyTuple_New(n);
  1072. if (newconst == NULL) {
  1073. return ERROR;
  1074. }
  1075. for (int i = 0; i < n; i++) {
  1076. int op = inst[i].i_opcode;
  1077. int arg = inst[i].i_oparg;
  1078. PyObject *constant = get_const_value(op, arg, consts);
  1079. if (constant == NULL) {
  1080. return ERROR;
  1081. }
  1082. PyTuple_SET_ITEM(newconst, i, constant);
  1083. }
  1084. if (_PyCompile_ConstCacheMergeOne(const_cache, &newconst) < 0) {
  1085. Py_DECREF(newconst);
  1086. return ERROR;
  1087. }
  1088. Py_ssize_t index;
  1089. for (index = 0; index < PyList_GET_SIZE(consts); index++) {
  1090. if (PyList_GET_ITEM(consts, index) == newconst) {
  1091. break;
  1092. }
  1093. }
  1094. if (index == PyList_GET_SIZE(consts)) {
  1095. if ((size_t)index >= (size_t)INT_MAX - 1) {
  1096. Py_DECREF(newconst);
  1097. PyErr_SetString(PyExc_OverflowError, "too many constants");
  1098. return ERROR;
  1099. }
  1100. if (PyList_Append(consts, newconst)) {
  1101. Py_DECREF(newconst);
  1102. return ERROR;
  1103. }
  1104. }
  1105. Py_DECREF(newconst);
  1106. for (int i = 0; i < n; i++) {
  1107. INSTR_SET_OP0(&inst[i], NOP);
  1108. }
  1109. INSTR_SET_OP1(&inst[n], LOAD_CONST, (int)index);
  1110. return SUCCESS;
  1111. }
  1112. #define VISITED (-1)
  1113. // Replace an arbitrary run of SWAPs and NOPs with an optimal one that has the
  1114. // same effect.
  1115. static int
  1116. swaptimize(basicblock *block, int *ix)
  1117. {
  1118. // NOTE: "./python -m test test_patma" serves as a good, quick stress test
  1119. // for this function. Make sure to blow away cached *.pyc files first!
  1120. assert(*ix < block->b_iused);
  1121. cfg_instr *instructions = &block->b_instr[*ix];
  1122. // Find the length of the current sequence of SWAPs and NOPs, and record the
  1123. // maximum depth of the stack manipulations:
  1124. assert(instructions[0].i_opcode == SWAP);
  1125. int depth = instructions[0].i_oparg;
  1126. int len = 0;
  1127. int more = false;
  1128. int limit = block->b_iused - *ix;
  1129. while (++len < limit) {
  1130. int opcode = instructions[len].i_opcode;
  1131. if (opcode == SWAP) {
  1132. depth = Py_MAX(depth, instructions[len].i_oparg);
  1133. more = true;
  1134. }
  1135. else if (opcode != NOP) {
  1136. break;
  1137. }
  1138. }
  1139. // It's already optimal if there's only one SWAP:
  1140. if (!more) {
  1141. return SUCCESS;
  1142. }
  1143. // Create an array with elements {0, 1, 2, ..., depth - 1}:
  1144. int *stack = PyMem_Malloc(depth * sizeof(int));
  1145. if (stack == NULL) {
  1146. PyErr_NoMemory();
  1147. return ERROR;
  1148. }
  1149. for (int i = 0; i < depth; i++) {
  1150. stack[i] = i;
  1151. }
  1152. // Simulate the combined effect of these instructions by "running" them on
  1153. // our "stack":
  1154. for (int i = 0; i < len; i++) {
  1155. if (instructions[i].i_opcode == SWAP) {
  1156. int oparg = instructions[i].i_oparg;
  1157. int top = stack[0];
  1158. // SWAPs are 1-indexed:
  1159. stack[0] = stack[oparg - 1];
  1160. stack[oparg - 1] = top;
  1161. }
  1162. }
  1163. // Now we can begin! Our approach here is based on a solution to a closely
  1164. // related problem (https://cs.stackexchange.com/a/13938). It's easiest to
  1165. // think of this algorithm as determining the steps needed to efficiently
  1166. // "un-shuffle" our stack. By performing the moves in *reverse* order,
  1167. // though, we can efficiently *shuffle* it! For this reason, we will be
  1168. // replacing instructions starting from the *end* of the run. Since the
  1169. // solution is optimal, we don't need to worry about running out of space:
  1170. int current = len - 1;
  1171. for (int i = 0; i < depth; i++) {
  1172. // Skip items that have already been visited, or just happen to be in
  1173. // the correct location:
  1174. if (stack[i] == VISITED || stack[i] == i) {
  1175. continue;
  1176. }
  1177. // Okay, we've found an item that hasn't been visited. It forms a cycle
  1178. // with other items; traversing the cycle and swapping each item with
  1179. // the next will put them all in the correct place. The weird
  1180. // loop-and-a-half is necessary to insert 0 into every cycle, since we
  1181. // can only swap from that position:
  1182. int j = i;
  1183. while (true) {
  1184. // Skip the actual swap if our item is zero, since swapping the top
  1185. // item with itself is pointless:
  1186. if (j) {
  1187. assert(0 <= current);
  1188. // SWAPs are 1-indexed:
  1189. instructions[current].i_opcode = SWAP;
  1190. instructions[current--].i_oparg = j + 1;
  1191. }
  1192. if (stack[j] == VISITED) {
  1193. // Completed the cycle:
  1194. assert(j == i);
  1195. break;
  1196. }
  1197. int next_j = stack[j];
  1198. stack[j] = VISITED;
  1199. j = next_j;
  1200. }
  1201. }
  1202. // NOP out any unused instructions:
  1203. while (0 <= current) {
  1204. INSTR_SET_OP0(&instructions[current--], NOP);
  1205. }
  1206. PyMem_Free(stack);
  1207. *ix += len - 1;
  1208. return SUCCESS;
  1209. }
  1210. // This list is pretty small, since it's only okay to reorder opcodes that:
  1211. // - can't affect control flow (like jumping or raising exceptions)
  1212. // - can't invoke arbitrary code (besides finalizers)
  1213. // - only touch the TOS (and pop it when finished)
  1214. #define SWAPPABLE(opcode) \
  1215. ((opcode) == STORE_FAST || \
  1216. (opcode) == STORE_FAST_MAYBE_NULL || \
  1217. (opcode) == POP_TOP)
  1218. #define STORES_TO(instr) \
  1219. (((instr).i_opcode == STORE_FAST || \
  1220. (instr).i_opcode == STORE_FAST_MAYBE_NULL) \
  1221. ? (instr).i_oparg : -1)
  1222. static int
  1223. next_swappable_instruction(basicblock *block, int i, int lineno)
  1224. {
  1225. while (++i < block->b_iused) {
  1226. cfg_instr *instruction = &block->b_instr[i];
  1227. if (0 <= lineno && instruction->i_loc.lineno != lineno) {
  1228. // Optimizing across this instruction could cause user-visible
  1229. // changes in the names bound between line tracing events!
  1230. return -1;
  1231. }
  1232. if (instruction->i_opcode == NOP) {
  1233. continue;
  1234. }
  1235. if (SWAPPABLE(instruction->i_opcode)) {
  1236. return i;
  1237. }
  1238. return -1;
  1239. }
  1240. return -1;
  1241. }
  1242. // Attempt to apply SWAPs statically by swapping *instructions* rather than
  1243. // stack items. For example, we can replace SWAP(2), POP_TOP, STORE_FAST(42)
  1244. // with the more efficient NOP, STORE_FAST(42), POP_TOP.
  1245. static void
  1246. apply_static_swaps(basicblock *block, int i)
  1247. {
  1248. // SWAPs are to our left, and potential swaperands are to our right:
  1249. for (; 0 <= i; i--) {
  1250. assert(i < block->b_iused);
  1251. cfg_instr *swap = &block->b_instr[i];
  1252. if (swap->i_opcode != SWAP) {
  1253. if (swap->i_opcode == NOP || SWAPPABLE(swap->i_opcode)) {
  1254. // Nope, but we know how to handle these. Keep looking:
  1255. continue;
  1256. }
  1257. // We can't reason about what this instruction does. Bail:
  1258. return;
  1259. }
  1260. int j = next_swappable_instruction(block, i, -1);
  1261. if (j < 0) {
  1262. return;
  1263. }
  1264. int k = j;
  1265. int lineno = block->b_instr[j].i_loc.lineno;
  1266. for (int count = swap->i_oparg - 1; 0 < count; count--) {
  1267. k = next_swappable_instruction(block, k, lineno);
  1268. if (k < 0) {
  1269. return;
  1270. }
  1271. }
  1272. // The reordering is not safe if the two instructions to be swapped
  1273. // store to the same location, or if any intervening instruction stores
  1274. // to the same location as either of them.
  1275. int store_j = STORES_TO(block->b_instr[j]);
  1276. int store_k = STORES_TO(block->b_instr[k]);
  1277. if (store_j >= 0 || store_k >= 0) {
  1278. if (store_j == store_k) {
  1279. return;
  1280. }
  1281. for (int idx = j + 1; idx < k; idx++) {
  1282. int store_idx = STORES_TO(block->b_instr[idx]);
  1283. if (store_idx >= 0 && (store_idx == store_j || store_idx == store_k)) {
  1284. return;
  1285. }
  1286. }
  1287. }
  1288. // Success!
  1289. INSTR_SET_OP0(swap, NOP);
  1290. cfg_instr temp = block->b_instr[j];
  1291. block->b_instr[j] = block->b_instr[k];
  1292. block->b_instr[k] = temp;
  1293. }
  1294. }
  1295. static int
  1296. optimize_basic_block(PyObject *const_cache, basicblock *bb, PyObject *consts)
  1297. {
  1298. assert(PyDict_CheckExact(const_cache));
  1299. assert(PyList_CheckExact(consts));
  1300. cfg_instr nop;
  1301. INSTR_SET_OP0(&nop, NOP);
  1302. cfg_instr *target = &nop;
  1303. int opcode = 0;
  1304. int oparg = 0;
  1305. int nextop = 0;
  1306. for (int i = 0; i < bb->b_iused; i++) {
  1307. cfg_instr *inst = &bb->b_instr[i];
  1308. bool is_copy_of_load_const = (opcode == LOAD_CONST &&
  1309. inst->i_opcode == COPY &&
  1310. inst->i_oparg == 1);
  1311. if (! is_copy_of_load_const) {
  1312. opcode = inst->i_opcode;
  1313. oparg = inst->i_oparg;
  1314. if (HAS_TARGET(opcode)) {
  1315. assert(inst->i_target->b_iused > 0);
  1316. target = &inst->i_target->b_instr[0];
  1317. assert(!IS_ASSEMBLER_OPCODE(target->i_opcode));
  1318. }
  1319. else {
  1320. target = &nop;
  1321. }
  1322. }
  1323. nextop = i+1 < bb->b_iused ? bb->b_instr[i+1].i_opcode : 0;
  1324. assert(!IS_ASSEMBLER_OPCODE(opcode));
  1325. switch (opcode) {
  1326. /* Remove LOAD_CONST const; conditional jump */
  1327. case LOAD_CONST:
  1328. {
  1329. PyObject* cnt;
  1330. int is_true;
  1331. int jump_if_true;
  1332. switch(nextop) {
  1333. case POP_JUMP_IF_FALSE:
  1334. case POP_JUMP_IF_TRUE:
  1335. cnt = get_const_value(opcode, oparg, consts);
  1336. if (cnt == NULL) {
  1337. goto error;
  1338. }
  1339. is_true = PyObject_IsTrue(cnt);
  1340. Py_DECREF(cnt);
  1341. if (is_true == -1) {
  1342. goto error;
  1343. }
  1344. INSTR_SET_OP0(inst, NOP);
  1345. jump_if_true = nextop == POP_JUMP_IF_TRUE;
  1346. if (is_true == jump_if_true) {
  1347. bb->b_instr[i+1].i_opcode = JUMP;
  1348. }
  1349. else {
  1350. INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
  1351. }
  1352. break;
  1353. case IS_OP:
  1354. cnt = get_const_value(opcode, oparg, consts);
  1355. if (cnt == NULL) {
  1356. goto error;
  1357. }
  1358. int jump_op = i+2 < bb->b_iused ? bb->b_instr[i+2].i_opcode : 0;
  1359. if (Py_IsNone(cnt) && (jump_op == POP_JUMP_IF_FALSE || jump_op == POP_JUMP_IF_TRUE)) {
  1360. unsigned char nextarg = bb->b_instr[i+1].i_oparg;
  1361. INSTR_SET_OP0(inst, NOP);
  1362. INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
  1363. bb->b_instr[i+2].i_opcode = nextarg ^ (jump_op == POP_JUMP_IF_FALSE) ?
  1364. POP_JUMP_IF_NOT_NONE : POP_JUMP_IF_NONE;
  1365. }
  1366. Py_DECREF(cnt);
  1367. break;
  1368. case RETURN_VALUE:
  1369. INSTR_SET_OP0(inst, NOP);
  1370. INSTR_SET_OP1(&bb->b_instr[++i], RETURN_CONST, oparg);
  1371. break;
  1372. }
  1373. break;
  1374. }
  1375. /* Try to fold tuples of constants.
  1376. Skip over BUILD_TUPLE(1) UNPACK_SEQUENCE(1).
  1377. Replace BUILD_TUPLE(2) UNPACK_SEQUENCE(2) with SWAP(2).
  1378. Replace BUILD_TUPLE(3) UNPACK_SEQUENCE(3) with SWAP(3). */
  1379. case BUILD_TUPLE:
  1380. if (nextop == UNPACK_SEQUENCE && oparg == bb->b_instr[i+1].i_oparg) {
  1381. switch(oparg) {
  1382. case 1:
  1383. INSTR_SET_OP0(inst, NOP);
  1384. INSTR_SET_OP0(&bb->b_instr[i + 1], NOP);
  1385. continue;
  1386. case 2:
  1387. case 3:
  1388. INSTR_SET_OP0(inst, NOP);
  1389. bb->b_instr[i+1].i_opcode = SWAP;
  1390. continue;
  1391. }
  1392. }
  1393. if (i >= oparg) {
  1394. if (fold_tuple_on_constants(const_cache, inst-oparg, oparg, consts)) {
  1395. goto error;
  1396. }
  1397. }
  1398. break;
  1399. case POP_JUMP_IF_NOT_NONE:
  1400. case POP_JUMP_IF_NONE:
  1401. switch (target->i_opcode) {
  1402. case JUMP:
  1403. i -= jump_thread(inst, target, inst->i_opcode);
  1404. }
  1405. break;
  1406. case POP_JUMP_IF_FALSE:
  1407. switch (target->i_opcode) {
  1408. case JUMP:
  1409. i -= jump_thread(inst, target, POP_JUMP_IF_FALSE);
  1410. }
  1411. break;
  1412. case POP_JUMP_IF_TRUE:
  1413. switch (target->i_opcode) {
  1414. case JUMP:
  1415. i -= jump_thread(inst, target, POP_JUMP_IF_TRUE);
  1416. }
  1417. break;
  1418. case JUMP:
  1419. switch (target->i_opcode) {
  1420. case JUMP:
  1421. i -= jump_thread(inst, target, JUMP);
  1422. }
  1423. break;
  1424. case FOR_ITER:
  1425. if (target->i_opcode == JUMP) {
  1426. /* This will not work now because the jump (at target) could
  1427. * be forward or backward and FOR_ITER only jumps forward. We
  1428. * can re-enable this if ever we implement a backward version
  1429. * of FOR_ITER.
  1430. */
  1431. /*
  1432. i -= jump_thread(inst, target, FOR_ITER);
  1433. */
  1434. }
  1435. break;
  1436. case SWAP:
  1437. if (oparg == 1) {
  1438. INSTR_SET_OP0(inst, NOP);
  1439. break;
  1440. }
  1441. if (swaptimize(bb, &i) < 0) {
  1442. goto error;
  1443. }
  1444. apply_static_swaps(bb, i);
  1445. break;
  1446. case KW_NAMES:
  1447. break;
  1448. case PUSH_NULL:
  1449. if (nextop == LOAD_GLOBAL && (bb->b_instr[i+1].i_oparg & 1) == 0) {
  1450. INSTR_SET_OP0(inst, NOP);
  1451. bb->b_instr[i+1].i_oparg |= 1;
  1452. }
  1453. break;
  1454. default:
  1455. /* All HAS_CONST opcodes should be handled with LOAD_CONST */
  1456. assert (!HAS_CONST(inst->i_opcode));
  1457. }
  1458. }
  1459. return SUCCESS;
  1460. error:
  1461. return ERROR;
  1462. }
  1463. /* Perform optimizations on a control flow graph.
  1464. The consts object should still be in list form to allow new constants
  1465. to be appended.
  1466. Code trasnformations that reduce code size initially fill the gaps with
  1467. NOPs. Later those NOPs are removed.
  1468. */
  1469. static int
  1470. optimize_cfg(cfg_builder *g, PyObject *consts, PyObject *const_cache)
  1471. {
  1472. assert(PyDict_CheckExact(const_cache));
  1473. RETURN_IF_ERROR(check_cfg(g));
  1474. eliminate_empty_basic_blocks(g);
  1475. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  1476. RETURN_IF_ERROR(inline_small_exit_blocks(b));
  1477. }
  1478. assert(no_empty_basic_blocks(g));
  1479. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  1480. RETURN_IF_ERROR(optimize_basic_block(const_cache, b, consts));
  1481. assert(b->b_predecessors == 0);
  1482. }
  1483. RETURN_IF_ERROR(remove_redundant_nops_and_pairs(g->g_entryblock));
  1484. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  1485. RETURN_IF_ERROR(inline_small_exit_blocks(b));
  1486. }
  1487. RETURN_IF_ERROR(mark_reachable(g->g_entryblock));
  1488. /* Delete unreachable instructions */
  1489. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  1490. if (b->b_predecessors == 0) {
  1491. b->b_iused = 0;
  1492. }
  1493. }
  1494. for (basicblock *b = g->g_entryblock; b != NULL; b = b->b_next) {
  1495. remove_redundant_nops(b);
  1496. }
  1497. eliminate_empty_basic_blocks(g);
  1498. /* This assertion fails in an edge case (See gh-109889).
  1499. * Remove it for the release (it's just one more NOP in the
  1500. * bytecode for unlikely code).
  1501. */
  1502. // assert(no_redundant_nops(g));
  1503. RETURN_IF_ERROR(remove_redundant_jumps(g));
  1504. return SUCCESS;
  1505. }
  1506. // helper functions for add_checks_for_loads_of_unknown_variables
  1507. static inline void
  1508. maybe_push(basicblock *b, uint64_t unsafe_mask, basicblock ***sp)
  1509. {
  1510. // Push b if the unsafe mask is giving us any new information.
  1511. // To avoid overflowing the stack, only allow each block once.
  1512. // Use b->b_visited=1 to mean that b is currently on the stack.
  1513. uint64_t both = b->b_unsafe_locals_mask | unsafe_mask;
  1514. if (b->b_unsafe_locals_mask != both) {
  1515. b->b_unsafe_locals_mask = both;
  1516. // More work left to do.
  1517. if (!b->b_visited) {
  1518. // not on the stack, so push it.
  1519. *(*sp)++ = b;
  1520. b->b_visited = 1;
  1521. }
  1522. }
  1523. }
  1524. static void
  1525. scan_block_for_locals(basicblock *b, basicblock ***sp)
  1526. {
  1527. // bit i is set if local i is potentially uninitialized
  1528. uint64_t unsafe_mask = b->b_unsafe_locals_mask;
  1529. for (int i = 0; i < b->b_iused; i++) {
  1530. cfg_instr *instr = &b->b_instr[i];
  1531. assert(instr->i_opcode != EXTENDED_ARG);
  1532. assert(!IS_SUPERINSTRUCTION_OPCODE(instr->i_opcode));
  1533. if (instr->i_except != NULL) {
  1534. maybe_push(instr->i_except, unsafe_mask, sp);
  1535. }
  1536. if (instr->i_oparg >= 64) {
  1537. continue;
  1538. }
  1539. assert(instr->i_oparg >= 0);
  1540. uint64_t bit = (uint64_t)1 << instr->i_oparg;
  1541. switch (instr->i_opcode) {
  1542. case DELETE_FAST:
  1543. case LOAD_FAST_AND_CLEAR:
  1544. case STORE_FAST_MAYBE_NULL:
  1545. unsafe_mask |= bit;
  1546. break;
  1547. case STORE_FAST:
  1548. unsafe_mask &= ~bit;
  1549. break;
  1550. case LOAD_FAST_CHECK:
  1551. // If this doesn't raise, then the local is defined.
  1552. unsafe_mask &= ~bit;
  1553. break;
  1554. case LOAD_FAST:
  1555. if (unsafe_mask & bit) {
  1556. instr->i_opcode = LOAD_FAST_CHECK;
  1557. }
  1558. unsafe_mask &= ~bit;
  1559. break;
  1560. }
  1561. }
  1562. if (b->b_next && BB_HAS_FALLTHROUGH(b)) {
  1563. maybe_push(b->b_next, unsafe_mask, sp);
  1564. }
  1565. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  1566. if (last && is_jump(last)) {
  1567. assert(last->i_target != NULL);
  1568. maybe_push(last->i_target, unsafe_mask, sp);
  1569. }
  1570. }
  1571. static int
  1572. fast_scan_many_locals(basicblock *entryblock, int nlocals)
  1573. {
  1574. assert(nlocals > 64);
  1575. Py_ssize_t *states = PyMem_Calloc(nlocals - 64, sizeof(Py_ssize_t));
  1576. if (states == NULL) {
  1577. PyErr_NoMemory();
  1578. return ERROR;
  1579. }
  1580. Py_ssize_t blocknum = 0;
  1581. // state[i - 64] == blocknum if local i is guaranteed to
  1582. // be initialized, i.e., if it has had a previous LOAD_FAST or
  1583. // STORE_FAST within that basicblock (not followed by
  1584. // DELETE_FAST/LOAD_FAST_AND_CLEAR/STORE_FAST_MAYBE_NULL).
  1585. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1586. blocknum++;
  1587. for (int i = 0; i < b->b_iused; i++) {
  1588. cfg_instr *instr = &b->b_instr[i];
  1589. assert(instr->i_opcode != EXTENDED_ARG);
  1590. assert(!IS_SUPERINSTRUCTION_OPCODE(instr->i_opcode));
  1591. int arg = instr->i_oparg;
  1592. if (arg < 64) {
  1593. continue;
  1594. }
  1595. assert(arg >= 0);
  1596. switch (instr->i_opcode) {
  1597. case DELETE_FAST:
  1598. case LOAD_FAST_AND_CLEAR:
  1599. case STORE_FAST_MAYBE_NULL:
  1600. states[arg - 64] = blocknum - 1;
  1601. break;
  1602. case STORE_FAST:
  1603. states[arg - 64] = blocknum;
  1604. break;
  1605. case LOAD_FAST:
  1606. if (states[arg - 64] != blocknum) {
  1607. instr->i_opcode = LOAD_FAST_CHECK;
  1608. }
  1609. states[arg - 64] = blocknum;
  1610. break;
  1611. Py_UNREACHABLE();
  1612. }
  1613. }
  1614. }
  1615. PyMem_Free(states);
  1616. return SUCCESS;
  1617. }
  1618. static int
  1619. remove_unused_consts(basicblock *entryblock, PyObject *consts)
  1620. {
  1621. assert(PyList_CheckExact(consts));
  1622. Py_ssize_t nconsts = PyList_GET_SIZE(consts);
  1623. if (nconsts == 0) {
  1624. return SUCCESS; /* nothing to do */
  1625. }
  1626. Py_ssize_t *index_map = NULL;
  1627. Py_ssize_t *reverse_index_map = NULL;
  1628. int err = ERROR;
  1629. index_map = PyMem_Malloc(nconsts * sizeof(Py_ssize_t));
  1630. if (index_map == NULL) {
  1631. goto end;
  1632. }
  1633. for (Py_ssize_t i = 1; i < nconsts; i++) {
  1634. index_map[i] = -1;
  1635. }
  1636. // The first constant may be docstring; keep it always.
  1637. index_map[0] = 0;
  1638. /* mark used consts */
  1639. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1640. for (int i = 0; i < b->b_iused; i++) {
  1641. if (HAS_CONST(b->b_instr[i].i_opcode)) {
  1642. int index = b->b_instr[i].i_oparg;
  1643. index_map[index] = index;
  1644. }
  1645. }
  1646. }
  1647. /* now index_map[i] == i if consts[i] is used, -1 otherwise */
  1648. /* condense consts */
  1649. Py_ssize_t n_used_consts = 0;
  1650. for (int i = 0; i < nconsts; i++) {
  1651. if (index_map[i] != -1) {
  1652. assert(index_map[i] == i);
  1653. index_map[n_used_consts++] = index_map[i];
  1654. }
  1655. }
  1656. if (n_used_consts == nconsts) {
  1657. /* nothing to do */
  1658. err = SUCCESS;
  1659. goto end;
  1660. }
  1661. /* move all used consts to the beginning of the consts list */
  1662. assert(n_used_consts < nconsts);
  1663. for (Py_ssize_t i = 0; i < n_used_consts; i++) {
  1664. Py_ssize_t old_index = index_map[i];
  1665. assert(i <= old_index && old_index < nconsts);
  1666. if (i != old_index) {
  1667. PyObject *value = PyList_GET_ITEM(consts, index_map[i]);
  1668. assert(value != NULL);
  1669. PyList_SetItem(consts, i, Py_NewRef(value));
  1670. }
  1671. }
  1672. /* truncate the consts list at its new size */
  1673. if (PyList_SetSlice(consts, n_used_consts, nconsts, NULL) < 0) {
  1674. goto end;
  1675. }
  1676. /* adjust const indices in the bytecode */
  1677. reverse_index_map = PyMem_Malloc(nconsts * sizeof(Py_ssize_t));
  1678. if (reverse_index_map == NULL) {
  1679. goto end;
  1680. }
  1681. for (Py_ssize_t i = 0; i < nconsts; i++) {
  1682. reverse_index_map[i] = -1;
  1683. }
  1684. for (Py_ssize_t i = 0; i < n_used_consts; i++) {
  1685. assert(index_map[i] != -1);
  1686. assert(reverse_index_map[index_map[i]] == -1);
  1687. reverse_index_map[index_map[i]] = i;
  1688. }
  1689. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1690. for (int i = 0; i < b->b_iused; i++) {
  1691. if (HAS_CONST(b->b_instr[i].i_opcode)) {
  1692. int index = b->b_instr[i].i_oparg;
  1693. assert(reverse_index_map[index] >= 0);
  1694. assert(reverse_index_map[index] < n_used_consts);
  1695. b->b_instr[i].i_oparg = (int)reverse_index_map[index];
  1696. }
  1697. }
  1698. }
  1699. err = SUCCESS;
  1700. end:
  1701. PyMem_Free(index_map);
  1702. PyMem_Free(reverse_index_map);
  1703. return err;
  1704. }
  1705. static int
  1706. add_checks_for_loads_of_uninitialized_variables(basicblock *entryblock,
  1707. int nlocals,
  1708. int nparams)
  1709. {
  1710. if (nlocals == 0) {
  1711. return SUCCESS;
  1712. }
  1713. if (nlocals > 64) {
  1714. // To avoid O(nlocals**2) compilation, locals beyond the first
  1715. // 64 are only analyzed one basicblock at a time: initialization
  1716. // info is not passed between basicblocks.
  1717. if (fast_scan_many_locals(entryblock, nlocals) < 0) {
  1718. return ERROR;
  1719. }
  1720. nlocals = 64;
  1721. }
  1722. basicblock **stack = make_cfg_traversal_stack(entryblock);
  1723. if (stack == NULL) {
  1724. return ERROR;
  1725. }
  1726. basicblock **sp = stack;
  1727. // First origin of being uninitialized:
  1728. // The non-parameter locals in the entry block.
  1729. uint64_t start_mask = 0;
  1730. for (int i = nparams; i < nlocals; i++) {
  1731. start_mask |= (uint64_t)1 << i;
  1732. }
  1733. maybe_push(entryblock, start_mask, &sp);
  1734. // Second origin of being uninitialized:
  1735. // There could be DELETE_FAST somewhere, so
  1736. // be sure to scan each basicblock at least once.
  1737. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1738. scan_block_for_locals(b, &sp);
  1739. }
  1740. // Now propagate the uncertainty from the origins we found: Use
  1741. // LOAD_FAST_CHECK for any LOAD_FAST where the local could be undefined.
  1742. while (sp > stack) {
  1743. basicblock *b = *--sp;
  1744. // mark as no longer on stack
  1745. b->b_visited = 0;
  1746. scan_block_for_locals(b, &sp);
  1747. }
  1748. PyMem_Free(stack);
  1749. return SUCCESS;
  1750. }
  1751. static int
  1752. mark_warm(basicblock *entryblock) {
  1753. basicblock **stack = make_cfg_traversal_stack(entryblock);
  1754. if (stack == NULL) {
  1755. return ERROR;
  1756. }
  1757. basicblock **sp = stack;
  1758. *sp++ = entryblock;
  1759. entryblock->b_visited = 1;
  1760. while (sp > stack) {
  1761. basicblock *b = *(--sp);
  1762. assert(!b->b_except_handler);
  1763. b->b_warm = 1;
  1764. basicblock *next = b->b_next;
  1765. if (next && BB_HAS_FALLTHROUGH(b) && !next->b_visited) {
  1766. *sp++ = next;
  1767. next->b_visited = 1;
  1768. }
  1769. for (int i=0; i < b->b_iused; i++) {
  1770. cfg_instr *instr = &b->b_instr[i];
  1771. if (is_jump(instr) && !instr->i_target->b_visited) {
  1772. *sp++ = instr->i_target;
  1773. instr->i_target->b_visited = 1;
  1774. }
  1775. }
  1776. }
  1777. PyMem_Free(stack);
  1778. return SUCCESS;
  1779. }
  1780. static int
  1781. mark_cold(basicblock *entryblock) {
  1782. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1783. assert(!b->b_cold && !b->b_warm);
  1784. }
  1785. if (mark_warm(entryblock) < 0) {
  1786. return ERROR;
  1787. }
  1788. basicblock **stack = make_cfg_traversal_stack(entryblock);
  1789. if (stack == NULL) {
  1790. return ERROR;
  1791. }
  1792. basicblock **sp = stack;
  1793. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1794. if (b->b_except_handler) {
  1795. assert(!b->b_warm);
  1796. *sp++ = b;
  1797. b->b_visited = 1;
  1798. }
  1799. }
  1800. while (sp > stack) {
  1801. basicblock *b = *(--sp);
  1802. b->b_cold = 1;
  1803. basicblock *next = b->b_next;
  1804. if (next && BB_HAS_FALLTHROUGH(b)) {
  1805. if (!next->b_warm && !next->b_visited) {
  1806. *sp++ = next;
  1807. next->b_visited = 1;
  1808. }
  1809. }
  1810. for (int i = 0; i < b->b_iused; i++) {
  1811. cfg_instr *instr = &b->b_instr[i];
  1812. if (is_jump(instr)) {
  1813. assert(i == b->b_iused - 1);
  1814. basicblock *target = b->b_instr[i].i_target;
  1815. if (!target->b_warm && !target->b_visited) {
  1816. *sp++ = target;
  1817. target->b_visited = 1;
  1818. }
  1819. }
  1820. }
  1821. }
  1822. PyMem_Free(stack);
  1823. return SUCCESS;
  1824. }
  1825. static int
  1826. push_cold_blocks_to_end(cfg_builder *g, int code_flags) {
  1827. basicblock *entryblock = g->g_entryblock;
  1828. if (entryblock->b_next == NULL) {
  1829. /* single basicblock, no need to reorder */
  1830. return SUCCESS;
  1831. }
  1832. RETURN_IF_ERROR(mark_cold(entryblock));
  1833. int next_lbl = get_max_label(g->g_entryblock) + 1;
  1834. /* If we have a cold block with fallthrough to a warm block, add */
  1835. /* an explicit jump instead of fallthrough */
  1836. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1837. if (b->b_cold && BB_HAS_FALLTHROUGH(b) && b->b_next && b->b_next->b_warm) {
  1838. basicblock *explicit_jump = cfg_builder_new_block(g);
  1839. if (explicit_jump == NULL) {
  1840. return ERROR;
  1841. }
  1842. if (!IS_LABEL(b->b_next->b_label)) {
  1843. b->b_next->b_label.id = next_lbl++;
  1844. }
  1845. basicblock_addop(explicit_jump, JUMP, b->b_next->b_label.id, NO_LOCATION);
  1846. explicit_jump->b_cold = 1;
  1847. explicit_jump->b_next = b->b_next;
  1848. b->b_next = explicit_jump;
  1849. /* set target */
  1850. cfg_instr *last = _PyCfg_BasicblockLastInstr(explicit_jump);
  1851. last->i_target = explicit_jump->b_next;
  1852. }
  1853. }
  1854. assert(!entryblock->b_cold); /* First block can't be cold */
  1855. basicblock *cold_blocks = NULL;
  1856. basicblock *cold_blocks_tail = NULL;
  1857. basicblock *b = entryblock;
  1858. while(b->b_next) {
  1859. assert(!b->b_cold);
  1860. while (b->b_next && !b->b_next->b_cold) {
  1861. b = b->b_next;
  1862. }
  1863. if (b->b_next == NULL) {
  1864. /* no more cold blocks */
  1865. break;
  1866. }
  1867. /* b->b_next is the beginning of a cold streak */
  1868. assert(!b->b_cold && b->b_next->b_cold);
  1869. basicblock *b_end = b->b_next;
  1870. while (b_end->b_next && b_end->b_next->b_cold) {
  1871. b_end = b_end->b_next;
  1872. }
  1873. /* b_end is the end of the cold streak */
  1874. assert(b_end && b_end->b_cold);
  1875. assert(b_end->b_next == NULL || !b_end->b_next->b_cold);
  1876. if (cold_blocks == NULL) {
  1877. cold_blocks = b->b_next;
  1878. }
  1879. else {
  1880. cold_blocks_tail->b_next = b->b_next;
  1881. }
  1882. cold_blocks_tail = b_end;
  1883. b->b_next = b_end->b_next;
  1884. b_end->b_next = NULL;
  1885. }
  1886. assert(b != NULL && b->b_next == NULL);
  1887. b->b_next = cold_blocks;
  1888. if (cold_blocks != NULL) {
  1889. RETURN_IF_ERROR(remove_redundant_jumps(g));
  1890. }
  1891. return SUCCESS;
  1892. }
  1893. void
  1894. _PyCfg_ConvertPseudoOps(basicblock *entryblock)
  1895. {
  1896. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1897. for (int i = 0; i < b->b_iused; i++) {
  1898. cfg_instr *instr = &b->b_instr[i];
  1899. if (is_block_push(instr) || instr->i_opcode == POP_BLOCK) {
  1900. INSTR_SET_OP0(instr, NOP);
  1901. }
  1902. else if (instr->i_opcode == STORE_FAST_MAYBE_NULL) {
  1903. instr->i_opcode = STORE_FAST;
  1904. }
  1905. }
  1906. }
  1907. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1908. remove_redundant_nops(b);
  1909. }
  1910. }
  1911. static inline bool
  1912. is_exit_without_lineno(basicblock *b) {
  1913. if (!basicblock_exits_scope(b)) {
  1914. return false;
  1915. }
  1916. for (int i = 0; i < b->b_iused; i++) {
  1917. if (b->b_instr[i].i_loc.lineno >= 0) {
  1918. return false;
  1919. }
  1920. }
  1921. return true;
  1922. }
  1923. /* PEP 626 mandates that the f_lineno of a frame is correct
  1924. * after a frame terminates. It would be prohibitively expensive
  1925. * to continuously update the f_lineno field at runtime,
  1926. * so we make sure that all exiting instruction (raises and returns)
  1927. * have a valid line number, allowing us to compute f_lineno lazily.
  1928. * We can do this by duplicating the exit blocks without line number
  1929. * so that none have more than one predecessor. We can then safely
  1930. * copy the line number from the sole predecessor block.
  1931. */
  1932. static int
  1933. duplicate_exits_without_lineno(cfg_builder *g)
  1934. {
  1935. assert(no_empty_basic_blocks(g));
  1936. int next_lbl = get_max_label(g->g_entryblock) + 1;
  1937. /* Copy all exit blocks without line number that are targets of a jump.
  1938. */
  1939. basicblock *entryblock = g->g_entryblock;
  1940. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1941. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  1942. assert(last != NULL);
  1943. if (is_jump(last)) {
  1944. basicblock *target = last->i_target;
  1945. if (is_exit_without_lineno(target) && target->b_predecessors > 1) {
  1946. basicblock *new_target = copy_basicblock(g, target);
  1947. if (new_target == NULL) {
  1948. return ERROR;
  1949. }
  1950. new_target->b_instr[0].i_loc = last->i_loc;
  1951. last->i_target = new_target;
  1952. target->b_predecessors--;
  1953. new_target->b_predecessors = 1;
  1954. new_target->b_next = target->b_next;
  1955. new_target->b_label.id = next_lbl++;
  1956. target->b_next = new_target;
  1957. }
  1958. }
  1959. }
  1960. /* Any remaining reachable exit blocks without line number can only be reached by
  1961. * fall through, and thus can only have a single predecessor */
  1962. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1963. if (BB_HAS_FALLTHROUGH(b) && b->b_next && b->b_iused > 0) {
  1964. if (is_exit_without_lineno(b->b_next)) {
  1965. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  1966. assert(last != NULL);
  1967. b->b_next->b_instr[0].i_loc = last->i_loc;
  1968. }
  1969. }
  1970. }
  1971. return SUCCESS;
  1972. }
  1973. /* If an instruction has no line number, but it's predecessor in the BB does,
  1974. * then copy the line number. If a successor block has no line number, and only
  1975. * one predecessor, then inherit the line number.
  1976. * This ensures that all exit blocks (with one predecessor) receive a line number.
  1977. * Also reduces the size of the line number table,
  1978. * but has no impact on the generated line number events.
  1979. */
  1980. static void
  1981. propagate_line_numbers(basicblock *entryblock) {
  1982. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  1983. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  1984. if (last == NULL) {
  1985. continue;
  1986. }
  1987. location prev_location = NO_LOCATION;
  1988. for (int i = 0; i < b->b_iused; i++) {
  1989. if (b->b_instr[i].i_loc.lineno < 0) {
  1990. b->b_instr[i].i_loc = prev_location;
  1991. }
  1992. else {
  1993. prev_location = b->b_instr[i].i_loc;
  1994. }
  1995. }
  1996. if (BB_HAS_FALLTHROUGH(b) && b->b_next->b_predecessors == 1) {
  1997. assert(b->b_next->b_iused);
  1998. if (b->b_next->b_instr[0].i_loc.lineno < 0) {
  1999. b->b_next->b_instr[0].i_loc = prev_location;
  2000. }
  2001. }
  2002. if (is_jump(last)) {
  2003. basicblock *target = last->i_target;
  2004. if (target->b_predecessors == 1) {
  2005. if (target->b_instr[0].i_loc.lineno < 0) {
  2006. target->b_instr[0].i_loc = prev_location;
  2007. }
  2008. }
  2009. }
  2010. }
  2011. }
  2012. /* Make sure that all returns have a line number, even if early passes
  2013. * have failed to propagate a correct line number.
  2014. * The resulting line number may not be correct according to PEP 626,
  2015. * but should be "good enough", and no worse than in older versions. */
  2016. static void
  2017. guarantee_lineno_for_exits(basicblock *entryblock, int firstlineno) {
  2018. int lineno = firstlineno;
  2019. assert(lineno > 0);
  2020. for (basicblock *b = entryblock; b != NULL; b = b->b_next) {
  2021. cfg_instr *last = _PyCfg_BasicblockLastInstr(b);
  2022. if (last == NULL) {
  2023. continue;
  2024. }
  2025. if (last->i_loc.lineno < 0) {
  2026. if (last->i_opcode == RETURN_VALUE) {
  2027. for (int i = 0; i < b->b_iused; i++) {
  2028. assert(b->b_instr[i].i_loc.lineno < 0);
  2029. b->b_instr[i].i_loc.lineno = lineno;
  2030. }
  2031. }
  2032. }
  2033. else {
  2034. lineno = last->i_loc.lineno;
  2035. }
  2036. }
  2037. }
  2038. static int
  2039. resolve_line_numbers(cfg_builder *g, int firstlineno)
  2040. {
  2041. RETURN_IF_ERROR(duplicate_exits_without_lineno(g));
  2042. propagate_line_numbers(g->g_entryblock);
  2043. guarantee_lineno_for_exits(g->g_entryblock, firstlineno);
  2044. return SUCCESS;
  2045. }
  2046. int
  2047. _PyCfg_OptimizeCodeUnit(cfg_builder *g, PyObject *consts, PyObject *const_cache,
  2048. int code_flags, int nlocals, int nparams, int firstlineno)
  2049. {
  2050. assert(cfg_builder_check(g));
  2051. /** Preprocessing **/
  2052. /* Map labels to targets and mark exception handlers */
  2053. RETURN_IF_ERROR(translate_jump_labels_to_targets(g->g_entryblock));
  2054. RETURN_IF_ERROR(mark_except_handlers(g->g_entryblock));
  2055. RETURN_IF_ERROR(label_exception_targets(g->g_entryblock));
  2056. /** Optimization **/
  2057. RETURN_IF_ERROR(optimize_cfg(g, consts, const_cache));
  2058. RETURN_IF_ERROR(remove_unused_consts(g->g_entryblock, consts));
  2059. RETURN_IF_ERROR(
  2060. add_checks_for_loads_of_uninitialized_variables(
  2061. g->g_entryblock, nlocals, nparams));
  2062. RETURN_IF_ERROR(push_cold_blocks_to_end(g, code_flags));
  2063. RETURN_IF_ERROR(resolve_line_numbers(g, firstlineno));
  2064. return SUCCESS;
  2065. }