xref: /PHP-8.3/Zend/Optimizer/zend_cfg.c (revision 0b1d750d)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend Engine, CFG - Control Flow Graph                                |
4    +----------------------------------------------------------------------+
5    | Copyright (c) The PHP Group                                          |
6    +----------------------------------------------------------------------+
7    | This source file is subject to version 3.01 of the PHP license,      |
8    | that is bundled with this package in the file LICENSE, and is        |
9    | available through the world-wide-web at the following url:           |
10    | https://www.php.net/license/3_01.txt                                 |
11    | If you did not receive a copy of the PHP license and are unable to   |
12    | obtain it through the world-wide-web, please send a note to          |
13    | license@php.net so we can mail you a copy immediately.               |
14    +----------------------------------------------------------------------+
15    | Authors: Dmitry Stogov <dmitry@php.net>                              |
16    +----------------------------------------------------------------------+
17 */
18 
19 #include "zend_compile.h"
20 #include "zend_cfg.h"
21 #include "zend_func_info.h"
22 #include "zend_worklist.h"
23 #include "zend_optimizer.h"
24 #include "zend_optimizer_internal.h"
25 #include "zend_sort.h"
26 
zend_mark_reachable(zend_op * opcodes,zend_cfg * cfg,zend_basic_block * b)27 static void zend_mark_reachable(zend_op *opcodes, zend_cfg *cfg, zend_basic_block *b) /* {{{ */
28 {
29 	zend_basic_block *blocks = cfg->blocks;
30 
31 	while (1) {
32 		int i;
33 
34 		b->flags |= ZEND_BB_REACHABLE;
35 		if (b->successors_count == 0) {
36 			b->flags |= ZEND_BB_EXIT;
37 			return;
38 		}
39 
40 		for (i = 0; i < b->successors_count; i++) {
41 			zend_basic_block *succ = blocks + b->successors[i];
42 
43 			if (b->len != 0) {
44 				uint8_t opcode = opcodes[b->start + b->len - 1].opcode;
45 				if (opcode == ZEND_MATCH) {
46 					succ->flags |= ZEND_BB_TARGET;
47 				} else if (opcode == ZEND_SWITCH_LONG || opcode == ZEND_SWITCH_STRING) {
48 					if (i == b->successors_count - 1) {
49 						succ->flags |= ZEND_BB_FOLLOW | ZEND_BB_TARGET;
50 					} else {
51 						succ->flags |= ZEND_BB_TARGET;
52 					}
53 				} else if (b->successors_count == 1) {
54 					if (opcode == ZEND_JMP) {
55 						succ->flags |= ZEND_BB_TARGET;
56 					} else {
57 						succ->flags |= ZEND_BB_FOLLOW;
58 
59 						if ((cfg->flags & ZEND_CFG_STACKLESS)) {
60 							if (opcode == ZEND_INCLUDE_OR_EVAL ||
61 								opcode == ZEND_GENERATOR_CREATE ||
62 								opcode == ZEND_YIELD ||
63 								opcode == ZEND_YIELD_FROM ||
64 								opcode == ZEND_DO_FCALL ||
65 								opcode == ZEND_DO_UCALL ||
66 								opcode == ZEND_DO_FCALL_BY_NAME) {
67 								succ->flags |= ZEND_BB_ENTRY;
68 							}
69 						}
70 						if ((cfg->flags & ZEND_CFG_RECV_ENTRY)) {
71 							if (opcode == ZEND_RECV ||
72 								opcode == ZEND_RECV_INIT) {
73 								succ->flags |= ZEND_BB_RECV_ENTRY;
74 							}
75 						}
76 					}
77 				} else {
78 					ZEND_ASSERT(b->successors_count == 2);
79 					if (i == 0) {
80 						succ->flags |= ZEND_BB_TARGET;
81 					} else {
82 						succ->flags |= ZEND_BB_FOLLOW;
83 					}
84 				}
85 			} else {
86 				succ->flags |= ZEND_BB_FOLLOW;
87 			}
88 
89 			if (i == b->successors_count - 1) {
90 				/* Tail call optimization */
91 				if (succ->flags & ZEND_BB_REACHABLE) {
92 					return;
93 				}
94 
95 				b = succ;
96 				break;
97 			} else {
98 				/* Recursively check reachability */
99 				if (!(succ->flags & ZEND_BB_REACHABLE)) {
100 					zend_mark_reachable(opcodes, cfg, succ);
101 				}
102 			}
103 		}
104 	}
105 }
106 /* }}} */
107 
zend_mark_reachable_blocks(const zend_op_array * op_array,zend_cfg * cfg,int start)108 static void zend_mark_reachable_blocks(const zend_op_array *op_array, zend_cfg *cfg, int start) /* {{{ */
109 {
110 	zend_basic_block *blocks = cfg->blocks;
111 
112 	blocks[start].flags = ZEND_BB_START;
113 	zend_mark_reachable(op_array->opcodes, cfg, blocks + start);
114 
115 	if (op_array->last_try_catch) {
116 		zend_basic_block *b;
117 		int j, changed;
118 		uint32_t *block_map = cfg->map;
119 
120 		do {
121 			changed = 0;
122 
123 			/* Add exception paths */
124 			for (j = 0; j < op_array->last_try_catch; j++) {
125 
126 				/* check for jumps into the middle of try block */
127 				b = blocks + block_map[op_array->try_catch_array[j].try_op];
128 				if (!(b->flags & ZEND_BB_REACHABLE)) {
129 					zend_basic_block *end;
130 
131 					if (op_array->try_catch_array[j].catch_op) {
132 						end = blocks + block_map[op_array->try_catch_array[j].catch_op];
133 						while (b != end) {
134 							if (b->flags & ZEND_BB_REACHABLE) {
135 								op_array->try_catch_array[j].try_op = b->start;
136 								break;
137 							}
138 							b++;
139 						}
140 					}
141 					b = blocks + block_map[op_array->try_catch_array[j].try_op];
142 					if (!(b->flags & ZEND_BB_REACHABLE)) {
143 						if (op_array->try_catch_array[j].finally_op) {
144 							end = blocks + block_map[op_array->try_catch_array[j].finally_op];
145 							while (b != end) {
146 								if (b->flags & ZEND_BB_REACHABLE) {
147 									op_array->try_catch_array[j].try_op = op_array->try_catch_array[j].catch_op;
148 									changed = 1;
149 									zend_mark_reachable(op_array->opcodes, cfg, blocks + block_map[op_array->try_catch_array[j].try_op]);
150 									break;
151 								}
152 								b++;
153 							}
154 						}
155 					}
156 				}
157 
158 				b = blocks + block_map[op_array->try_catch_array[j].try_op];
159 				if (b->flags & ZEND_BB_REACHABLE) {
160 					b->flags |= ZEND_BB_TRY;
161 					if (op_array->try_catch_array[j].catch_op) {
162 						b = blocks + block_map[op_array->try_catch_array[j].catch_op];
163 						b->flags |= ZEND_BB_CATCH;
164 						if (!(b->flags & ZEND_BB_REACHABLE)) {
165 							changed = 1;
166 							zend_mark_reachable(op_array->opcodes, cfg, b);
167 						}
168 					}
169 					if (op_array->try_catch_array[j].finally_op) {
170 						b = blocks + block_map[op_array->try_catch_array[j].finally_op];
171 						b->flags |= ZEND_BB_FINALLY;
172 						if (!(b->flags & ZEND_BB_REACHABLE)) {
173 							changed = 1;
174 							zend_mark_reachable(op_array->opcodes, cfg, b);
175 						}
176 					}
177 					if (op_array->try_catch_array[j].finally_end) {
178 						b = blocks + block_map[op_array->try_catch_array[j].finally_end];
179 						b->flags |= ZEND_BB_FINALLY_END;
180 						if (!(b->flags & ZEND_BB_REACHABLE)) {
181 							changed = 1;
182 							zend_mark_reachable(op_array->opcodes, cfg, b);
183 						}
184 					}
185 				} else {
186 					if (op_array->try_catch_array[j].catch_op) {
187 						ZEND_ASSERT(!(blocks[block_map[op_array->try_catch_array[j].catch_op]].flags & ZEND_BB_REACHABLE));
188 					}
189 					if (op_array->try_catch_array[j].finally_op) {
190 						ZEND_ASSERT(!(blocks[block_map[op_array->try_catch_array[j].finally_op]].flags & ZEND_BB_REACHABLE));
191 					}
192 					if (op_array->try_catch_array[j].finally_end) {
193 						ZEND_ASSERT(!(blocks[block_map[op_array->try_catch_array[j].finally_end]].flags & ZEND_BB_REACHABLE));
194 					}
195 				}
196 			}
197 		} while (changed);
198 	}
199 
200 	if (cfg->flags & ZEND_FUNC_FREE_LOOP_VAR) {
201 		zend_basic_block *b;
202 		int j;
203 		uint32_t *block_map = cfg->map;
204 
205 		/* Mark blocks that are unreachable, but free a loop var created in a reachable block. */
206 		for (b = blocks; b < blocks + cfg->blocks_count; b++) {
207 			if (b->flags & ZEND_BB_REACHABLE) {
208 				continue;
209 			}
210 
211 			for (j = b->start; j < b->start + b->len; j++) {
212 				zend_op *opline = &op_array->opcodes[j];
213 				if (zend_optimizer_is_loop_var_free(opline)) {
214 					zend_op *def_opline = zend_optimizer_get_loop_var_def(op_array, opline);
215 					if (def_opline) {
216 						uint32_t def_block = block_map[def_opline - op_array->opcodes];
217 						if (blocks[def_block].flags & ZEND_BB_REACHABLE) {
218 							b->flags |= ZEND_BB_UNREACHABLE_FREE;
219 							break;
220 						}
221 					}
222 				}
223 			}
224 		}
225 	}
226 }
227 /* }}} */
228 
zend_cfg_remark_reachable_blocks(const zend_op_array * op_array,zend_cfg * cfg)229 void zend_cfg_remark_reachable_blocks(const zend_op_array *op_array, zend_cfg *cfg) /* {{{ */
230 {
231 	zend_basic_block *blocks = cfg->blocks;
232 	int i;
233 	int start = 0;
234 
235 	for (i = 0; i < cfg->blocks_count; i++) {
236 		if (blocks[i].flags & ZEND_BB_REACHABLE) {
237 			start = i;
238 			i++;
239 			break;
240 		}
241 	}
242 
243 	/* clear all flags */
244 	for (i = 0; i < cfg->blocks_count; i++) {
245 		blocks[i].flags = 0;
246 	}
247 
248 	zend_mark_reachable_blocks(op_array, cfg, start);
249 }
250 /* }}} */
251 
initialize_block(zend_basic_block * block)252 static void initialize_block(zend_basic_block *block) {
253 	block->flags = 0;
254 	block->successors = block->successors_storage;
255 	block->successors_count = 0;
256 	block->predecessors_count = 0;
257 	block->predecessor_offset = -1;
258 	block->idom = -1;
259 	block->loop_header = -1;
260 	block->level = -1;
261 	block->children = -1;
262 	block->next_child = -1;
263 }
264 
265 #define BB_START(i) do { \
266 		if (!block_map[i]) { blocks_count++;} \
267 		block_map[i]++; \
268 	} while (0)
269 
zend_build_cfg(zend_arena ** arena,const zend_op_array * op_array,uint32_t build_flags,zend_cfg * cfg)270 ZEND_API void zend_build_cfg(zend_arena **arena, const zend_op_array *op_array, uint32_t build_flags, zend_cfg *cfg) /* {{{ */
271 {
272 	uint32_t flags = 0;
273 	uint32_t i;
274 	int j;
275 	uint32_t *block_map;
276 	zend_function *fn;
277 	int blocks_count = 0;
278 	zend_basic_block *blocks;
279 	zval *zv;
280 	bool extra_entry_block = 0;
281 
282 	cfg->flags = build_flags & (ZEND_CFG_STACKLESS|ZEND_CFG_RECV_ENTRY);
283 
284 	cfg->map = block_map = zend_arena_calloc(arena, op_array->last, sizeof(uint32_t));
285 
286 	/* Build CFG, Step 1: Find basic blocks starts, calculate number of blocks */
287 	BB_START(0);
288 	for (i = 0; i < op_array->last; i++) {
289 		zend_op *opline = op_array->opcodes + i;
290 		switch (opline->opcode) {
291 			case ZEND_RECV:
292 			case ZEND_RECV_INIT:
293 				if (build_flags & ZEND_CFG_RECV_ENTRY) {
294 					BB_START(i + 1);
295 				}
296 				break;
297 			case ZEND_RETURN:
298 			case ZEND_RETURN_BY_REF:
299 			case ZEND_GENERATOR_RETURN:
300 			case ZEND_VERIFY_NEVER_TYPE:
301 				if (i + 1 < op_array->last) {
302 					BB_START(i + 1);
303 				}
304 				break;
305 			case ZEND_MATCH_ERROR:
306 			case ZEND_EXIT:
307 			case ZEND_THROW:
308 				/* Don't treat THROW as terminator if it's used in expression context,
309 				 * as we may lose live ranges when eliminating unreachable code. */
310 				if (opline->extended_value != ZEND_THROW_IS_EXPR && i + 1 < op_array->last) {
311 					BB_START(i + 1);
312 				}
313 				break;
314 			case ZEND_INCLUDE_OR_EVAL:
315 				flags |= ZEND_FUNC_INDIRECT_VAR_ACCESS;
316 				ZEND_FALLTHROUGH;
317 			case ZEND_GENERATOR_CREATE:
318 			case ZEND_YIELD:
319 			case ZEND_YIELD_FROM:
320 				if (build_flags & ZEND_CFG_STACKLESS) {
321 					BB_START(i + 1);
322 				}
323 				break;
324 			case ZEND_DO_FCALL:
325 			case ZEND_DO_UCALL:
326 			case ZEND_DO_FCALL_BY_NAME:
327 				flags |= ZEND_FUNC_HAS_CALLS;
328 				if (build_flags & ZEND_CFG_STACKLESS) {
329 					BB_START(i + 1);
330 				}
331 				break;
332 			case ZEND_DO_ICALL:
333 				flags |= ZEND_FUNC_HAS_CALLS;
334 				break;
335 			case ZEND_INIT_FCALL:
336 			case ZEND_INIT_NS_FCALL_BY_NAME:
337 				zv = CRT_CONSTANT(opline->op2);
338 				if (opline->opcode == ZEND_INIT_NS_FCALL_BY_NAME) {
339 					/* The third literal is the lowercased unqualified name */
340 					zv += 2;
341 				}
342 				if ((fn = zend_hash_find_ptr(EG(function_table), Z_STR_P(zv))) != NULL) {
343 					if (fn->type == ZEND_INTERNAL_FUNCTION) {
344 						flags |= zend_optimizer_classify_function(
345 							Z_STR_P(zv), opline->extended_value);
346 					}
347 				}
348 				break;
349 			case ZEND_FAST_CALL:
350 				BB_START(OP_JMP_ADDR(opline, opline->op1) - op_array->opcodes);
351 				BB_START(i + 1);
352 				break;
353 			case ZEND_FAST_RET:
354 				if (i + 1 < op_array->last) {
355 					BB_START(i + 1);
356 				}
357 				break;
358 			case ZEND_JMP:
359 				BB_START(OP_JMP_ADDR(opline, opline->op1) - op_array->opcodes);
360 				if (i + 1 < op_array->last) {
361 					BB_START(i + 1);
362 				}
363 				break;
364 			case ZEND_JMPZ:
365 			case ZEND_JMPNZ:
366 			case ZEND_JMPZ_EX:
367 			case ZEND_JMPNZ_EX:
368 			case ZEND_JMP_SET:
369 			case ZEND_COALESCE:
370 			case ZEND_ASSERT_CHECK:
371 			case ZEND_JMP_NULL:
372 			case ZEND_BIND_INIT_STATIC_OR_JMP:
373 				BB_START(OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes);
374 				BB_START(i + 1);
375 				break;
376 			case ZEND_CATCH:
377 				if (!(opline->extended_value & ZEND_LAST_CATCH)) {
378 					BB_START(OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes);
379 				}
380 				BB_START(i + 1);
381 				break;
382 			case ZEND_FE_FETCH_R:
383 			case ZEND_FE_FETCH_RW:
384 				BB_START(ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value));
385 				BB_START(i + 1);
386 				break;
387 			case ZEND_FE_RESET_R:
388 			case ZEND_FE_RESET_RW:
389 				BB_START(OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes);
390 				BB_START(i + 1);
391 				break;
392 			case ZEND_SWITCH_LONG:
393 			case ZEND_SWITCH_STRING:
394 			case ZEND_MATCH:
395 			{
396 				HashTable *jumptable = Z_ARRVAL_P(CRT_CONSTANT(opline->op2));
397 				zval *zv;
398 				ZEND_HASH_FOREACH_VAL(jumptable, zv) {
399 					BB_START(ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv)));
400 				} ZEND_HASH_FOREACH_END();
401 				BB_START(ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value));
402 				BB_START(i + 1);
403 				break;
404 			}
405 			case ZEND_FETCH_R:
406 			case ZEND_FETCH_W:
407 			case ZEND_FETCH_RW:
408 			case ZEND_FETCH_FUNC_ARG:
409 			case ZEND_FETCH_IS:
410 			case ZEND_FETCH_UNSET:
411 			case ZEND_UNSET_VAR:
412 			case ZEND_ISSET_ISEMPTY_VAR:
413 				if (opline->extended_value & ZEND_FETCH_LOCAL) {
414 					flags |= ZEND_FUNC_INDIRECT_VAR_ACCESS;
415 				} else if ((opline->extended_value & (ZEND_FETCH_GLOBAL | ZEND_FETCH_GLOBAL_LOCK)) &&
416 				           !op_array->function_name) {
417 					flags |= ZEND_FUNC_INDIRECT_VAR_ACCESS;
418 				}
419 				break;
420 			case ZEND_FUNC_GET_ARGS:
421 				flags |= ZEND_FUNC_VARARG;
422 				break;
423 			case ZEND_EXT_STMT:
424 				flags |= ZEND_FUNC_HAS_EXTENDED_STMT;
425 				break;
426 			case ZEND_EXT_FCALL_BEGIN:
427 			case ZEND_EXT_FCALL_END:
428 				flags |= ZEND_FUNC_HAS_EXTENDED_FCALL;
429 				break;
430 			case ZEND_FREE:
431 			case ZEND_FE_FREE:
432 				if (zend_optimizer_is_loop_var_free(opline)
433 				 && ((opline-1)->opcode != ZEND_MATCH_ERROR
434 				  || (opline-1)->extended_value != ZEND_THROW_IS_EXPR)) {
435 					BB_START(i);
436 					flags |= ZEND_FUNC_FREE_LOOP_VAR;
437 				}
438 				break;
439 		}
440 	}
441 
442 	/* If the entry block has predecessors, we may need to split it */
443 	if ((build_flags & ZEND_CFG_NO_ENTRY_PREDECESSORS)
444 			&& op_array->last > 0 && block_map[0] > 1) {
445 		extra_entry_block = 1;
446 	}
447 
448 	if (op_array->last_try_catch) {
449 		for (j = 0; j < op_array->last_try_catch; j++) {
450 			BB_START(op_array->try_catch_array[j].try_op);
451 			if (op_array->try_catch_array[j].catch_op) {
452 				BB_START(op_array->try_catch_array[j].catch_op);
453 			}
454 			if (op_array->try_catch_array[j].finally_op) {
455 				BB_START(op_array->try_catch_array[j].finally_op);
456 			}
457 			if (op_array->try_catch_array[j].finally_end) {
458 				BB_START(op_array->try_catch_array[j].finally_end);
459 			}
460 		}
461 	}
462 
463 	blocks_count += extra_entry_block;
464 	cfg->blocks_count = blocks_count;
465 
466 	/* Build CFG, Step 2: Build Array of Basic Blocks */
467 	cfg->blocks = blocks = zend_arena_calloc(arena, sizeof(zend_basic_block), blocks_count);
468 
469 	blocks_count = -1;
470 
471 	if (extra_entry_block) {
472 		initialize_block(&blocks[0]);
473 		blocks[0].start = 0;
474 		blocks[0].len = 0;
475 		blocks_count++;
476 	}
477 
478 	for (i = 0; i < op_array->last; i++) {
479 		if (block_map[i]) {
480 			if (blocks_count >= 0) {
481 				blocks[blocks_count].len = i - blocks[blocks_count].start;
482 			}
483 			blocks_count++;
484 			initialize_block(&blocks[blocks_count]);
485 			blocks[blocks_count].start = i;
486 		}
487 		block_map[i] = blocks_count;
488 	}
489 
490 	blocks[blocks_count].len = i - blocks[blocks_count].start;
491 	blocks_count++;
492 
493 	/* Build CFG, Step 3: Calculate successors */
494 	for (j = 0; j < blocks_count; j++) {
495 		zend_basic_block *block = &blocks[j];
496 		zend_op *opline;
497 		if (block->len == 0) {
498 			block->successors_count = 1;
499 			block->successors[0] = j + 1;
500 			continue;
501 		}
502 
503 		opline = op_array->opcodes + block->start + block->len - 1;
504 		switch (opline->opcode) {
505 			case ZEND_FAST_RET:
506 			case ZEND_RETURN:
507 			case ZEND_RETURN_BY_REF:
508 			case ZEND_GENERATOR_RETURN:
509 			case ZEND_EXIT:
510 			case ZEND_THROW:
511 			case ZEND_MATCH_ERROR:
512 			case ZEND_VERIFY_NEVER_TYPE:
513 				break;
514 			case ZEND_JMP:
515 				block->successors_count = 1;
516 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op1) - op_array->opcodes];
517 				break;
518 			case ZEND_JMPZ:
519 			case ZEND_JMPNZ:
520 			case ZEND_JMPZ_EX:
521 			case ZEND_JMPNZ_EX:
522 			case ZEND_JMP_SET:
523 			case ZEND_COALESCE:
524 			case ZEND_ASSERT_CHECK:
525 			case ZEND_JMP_NULL:
526 			case ZEND_BIND_INIT_STATIC_OR_JMP:
527 				block->successors_count = 2;
528 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes];
529 				block->successors[1] = j + 1;
530 				break;
531 			case ZEND_CATCH:
532 				if (!(opline->extended_value & ZEND_LAST_CATCH)) {
533 					block->successors_count = 2;
534 					block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes];
535 					block->successors[1] = j + 1;
536 				} else {
537 					block->successors_count = 1;
538 					block->successors[0] = j + 1;
539 				}
540 				break;
541 			case ZEND_FE_FETCH_R:
542 			case ZEND_FE_FETCH_RW:
543 				block->successors_count = 2;
544 				block->successors[0] = block_map[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value)];
545 				block->successors[1] = j + 1;
546 				break;
547 			case ZEND_FE_RESET_R:
548 			case ZEND_FE_RESET_RW:
549 				block->successors_count = 2;
550 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes];
551 				block->successors[1] = j + 1;
552 				break;
553 			case ZEND_FAST_CALL:
554 				block->successors_count = 2;
555 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op1) - op_array->opcodes];
556 				block->successors[1] = j + 1;
557 				break;
558 			case ZEND_SWITCH_LONG:
559 			case ZEND_SWITCH_STRING:
560 			case ZEND_MATCH:
561 			{
562 				HashTable *jumptable = Z_ARRVAL_P(CRT_CONSTANT(opline->op2));
563 				zval *zv;
564 				uint32_t s = 0;
565 
566 				block->successors_count = (opline->opcode == ZEND_MATCH ? 1 : 2) + zend_hash_num_elements(jumptable);
567 				block->successors = zend_arena_calloc(arena, block->successors_count, sizeof(int));
568 
569 				ZEND_HASH_FOREACH_VAL(jumptable, zv) {
570 					block->successors[s++] = block_map[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv))];
571 				} ZEND_HASH_FOREACH_END();
572 
573 				block->successors[s++] = block_map[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value)];
574 				if (opline->opcode != ZEND_MATCH) {
575 					block->successors[s++] = j + 1;
576 				}
577 				break;
578 			}
579 			default:
580 				block->successors_count = 1;
581 				block->successors[0] = j + 1;
582 				break;
583 		}
584 	}
585 
586 	/* Build CFG, Step 4, Mark Reachable Basic Blocks */
587 	cfg->flags |= flags;
588 	zend_mark_reachable_blocks(op_array, cfg, 0);
589 }
590 /* }}} */
591 
zend_cfg_build_predecessors(zend_arena ** arena,zend_cfg * cfg)592 ZEND_API void zend_cfg_build_predecessors(zend_arena **arena, zend_cfg *cfg) /* {{{ */
593 {
594 	int j, s, edges;
595 	zend_basic_block *b;
596 	zend_basic_block *blocks = cfg->blocks;
597 	zend_basic_block *end = blocks + cfg->blocks_count;
598 	int *predecessors;
599 
600 	edges = 0;
601 	for (b = blocks; b < end; b++) {
602 		b->predecessors_count = 0;
603 	}
604 	for (b = blocks; b < end; b++) {
605 		if (!(b->flags & ZEND_BB_REACHABLE)) {
606 			b->successors_count = 0;
607 			b->predecessors_count = 0;
608 		} else {
609 			for (s = 0; s < b->successors_count; s++) {
610 				edges++;
611 				blocks[b->successors[s]].predecessors_count++;
612 			}
613 		}
614 	}
615 
616 	cfg->edges_count = edges;
617 	cfg->predecessors = predecessors = (int*)zend_arena_calloc(arena, sizeof(int), edges);
618 
619 	edges = 0;
620 	for (b = blocks; b < end; b++) {
621 		if (b->flags & ZEND_BB_REACHABLE) {
622 			b->predecessor_offset = edges;
623 			edges += b->predecessors_count;
624 			b->predecessors_count = 0;
625 		}
626 	}
627 
628 	for (j = 0; j < cfg->blocks_count; j++) {
629 		if (blocks[j].flags & ZEND_BB_REACHABLE) {
630 			/* SWITCH_STRING/LONG may have few identical successors */
631 			for (s = 0; s < blocks[j].successors_count; s++) {
632 				int duplicate = 0;
633 				int p;
634 
635 				for (p = 0; p < s; p++) {
636 					if (blocks[j].successors[p] == blocks[j].successors[s]) {
637 						duplicate = 1;
638 						break;
639 					}
640 				}
641 				if (!duplicate) {
642 					zend_basic_block *b = blocks + blocks[j].successors[s];
643 
644 					predecessors[b->predecessor_offset + b->predecessors_count] = j;
645 					b->predecessors_count++;
646 				}
647 			}
648 		}
649 	}
650 }
651 /* }}} */
652 
653 /* Computes a postorder numbering of the CFG */
compute_postnum_recursive(int * postnum,int * cur,const zend_cfg * cfg,int block_num)654 static void compute_postnum_recursive(
655 		int *postnum, int *cur, const zend_cfg *cfg, int block_num) /* {{{ */
656 {
657 	int s;
658 	zend_basic_block *block = &cfg->blocks[block_num];
659 	if (postnum[block_num] != -1) {
660 		return;
661 	}
662 
663 	postnum[block_num] = -2; /* Marker for "currently visiting" */
664 	for (s = 0; s < block->successors_count; s++) {
665 		compute_postnum_recursive(postnum, cur, cfg, block->successors[s]);
666 	}
667 	postnum[block_num] = (*cur)++;
668 }
669 /* }}} */
670 
671 /* Computes dominator tree using algorithm from "A Simple, Fast Dominance Algorithm" by
672  * Cooper, Harvey and Kennedy. */
zend_cfg_compute_dominators_tree(const zend_op_array * op_array,zend_cfg * cfg)673 ZEND_API void zend_cfg_compute_dominators_tree(const zend_op_array *op_array, zend_cfg *cfg) /* {{{ */
674 {
675 	zend_basic_block *blocks = cfg->blocks;
676 	int blocks_count = cfg->blocks_count;
677 	int j, k, changed;
678 
679 	if (cfg->blocks_count == 1) {
680 		blocks[0].level = 0;
681 		return;
682 	}
683 
684 	ALLOCA_FLAG(use_heap)
685 	int *postnum = do_alloca(sizeof(int) * cfg->blocks_count, use_heap);
686 	memset(postnum, -1, sizeof(int) * cfg->blocks_count);
687 	j = 0;
688 	compute_postnum_recursive(postnum, &j, cfg, 0);
689 
690 	/* FIXME: move declarations */
691 	blocks[0].idom = 0;
692 	do {
693 		changed = 0;
694 		/* Iterating in RPO here would converge faster */
695 		for (j = 1; j < blocks_count; j++) {
696 			int idom = -1;
697 
698 			if ((blocks[j].flags & ZEND_BB_REACHABLE) == 0) {
699 				continue;
700 			}
701 			for (k = 0; k < blocks[j].predecessors_count; k++) {
702 				int pred = cfg->predecessors[blocks[j].predecessor_offset + k];
703 
704 				if (blocks[pred].idom >= 0) {
705 					if (idom < 0) {
706 						idom = pred;
707 					} else {
708 						while (idom != pred) {
709 							while (postnum[pred] < postnum[idom]) pred = blocks[pred].idom;
710 							while (postnum[idom] < postnum[pred]) idom = blocks[idom].idom;
711 						}
712 					}
713 				}
714 			}
715 
716 			if (idom >= 0 && blocks[j].idom != idom) {
717 				blocks[j].idom = idom;
718 				changed = 1;
719 			}
720 		}
721 	} while (changed);
722 	blocks[0].idom = -1;
723 
724 	for (j = 1; j < blocks_count; j++) {
725 		if ((blocks[j].flags & ZEND_BB_REACHABLE) == 0) {
726 			continue;
727 		}
728 		if (blocks[j].idom >= 0) {
729 			/* Sort by block number to traverse children in pre-order */
730 			if (blocks[blocks[j].idom].children < 0 ||
731 			    j < blocks[blocks[j].idom].children) {
732 				blocks[j].next_child = blocks[blocks[j].idom].children;
733 				blocks[blocks[j].idom].children = j;
734 			} else {
735 				int k = blocks[blocks[j].idom].children;
736 				while (blocks[k].next_child >=0 && j > blocks[k].next_child) {
737 					k = blocks[k].next_child;
738 				}
739 				blocks[j].next_child = blocks[k].next_child;
740 				blocks[k].next_child = j;
741 			}
742 		}
743 	}
744 
745 	for (j = 0; j < blocks_count; j++) {
746 		int idom = blocks[j].idom, level = 0;
747 		if ((blocks[j].flags & ZEND_BB_REACHABLE) == 0) {
748 			continue;
749 		}
750 		while (idom >= 0) {
751 			level++;
752 			if (blocks[idom].level >= 0) {
753 				level += blocks[idom].level;
754 				break;
755 			} else {
756 				idom = blocks[idom].idom;
757 			}
758 		}
759 		blocks[j].level = level;
760 	}
761 
762 	free_alloca(postnum, use_heap);
763 }
764 /* }}} */
765 
dominates(zend_basic_block * blocks,int a,int b)766 static bool dominates(zend_basic_block *blocks, int a, int b) /* {{{ */
767 {
768 	while (blocks[b].level > blocks[a].level) {
769 		b = blocks[b].idom;
770 	}
771 	return a == b;
772 }
773 /* }}} */
774 
zend_cfg_identify_loops(const zend_op_array * op_array,zend_cfg * cfg)775 ZEND_API void zend_cfg_identify_loops(const zend_op_array *op_array, zend_cfg *cfg) /* {{{ */
776 {
777 	int i, j, k, n;
778 	int time;
779 	zend_basic_block *blocks = cfg->blocks;
780 	int *entry_times, *exit_times;
781 	zend_worklist work;
782 	int flag = ZEND_FUNC_NO_LOOPS;
783 	int *sorted_blocks;
784 	ALLOCA_FLAG(list_use_heap)
785 	ALLOCA_FLAG(tree_use_heap)
786 
787 	if (cfg->blocks_count == 1) {
788 		cfg->flags |= flag;
789 		return;
790 	}
791 
792 	ZEND_WORKLIST_ALLOCA(&work, cfg->blocks_count, list_use_heap);
793 
794 	/* We don't materialize the DJ spanning tree explicitly, as we are only interested in ancestor
795 	 * queries. These are implemented by checking entry/exit times of the DFS search. */
796 	entry_times = do_alloca(3 * sizeof(int) * cfg->blocks_count, tree_use_heap);
797 	exit_times = entry_times + cfg->blocks_count;
798 	sorted_blocks = exit_times + cfg->blocks_count;
799 	memset(entry_times, -1, 2 * sizeof(int) * cfg->blocks_count);
800 
801 	zend_worklist_push(&work, 0);
802 	time = 0;
803 	while (zend_worklist_len(&work)) {
804 	next:
805 		i = zend_worklist_peek(&work);
806 		if (entry_times[i] == -1) {
807 			entry_times[i] = time++;
808 		}
809 		/* Visit blocks immediately dominated by i. */
810 		for (j = blocks[i].children; j >= 0; j = blocks[j].next_child) {
811 			if (zend_worklist_push(&work, j)) {
812 				goto next;
813 			}
814 		}
815 		/* Visit join edges.  */
816 		for (j = 0; j < blocks[i].successors_count; j++) {
817 			int succ = blocks[i].successors[j];
818 			if (blocks[succ].idom == i) {
819 				continue;
820 			} else if (zend_worklist_push(&work, succ)) {
821 				goto next;
822 			}
823 		}
824 		exit_times[i] = time++;
825 		zend_worklist_pop(&work);
826 	}
827 
828 	/* Sort blocks by level, which is the opposite order in which we want to process them */
829 	sorted_blocks[0] = 0;
830 	j = 0;
831 	n = 1;
832 	while (j != n) {
833 		i = j;
834 		j = n;
835 		for (; i < j; i++) {
836 			int child;
837 			for (child = blocks[sorted_blocks[i]].children; child >= 0; child = blocks[child].next_child) {
838 				sorted_blocks[n++] = child;
839 			}
840 		}
841 	}
842 
843 	/* Identify loops. See Sreedhar et al, "Identifying Loops Using DJ Graphs". */
844 	while (n > 0) {
845 		i = sorted_blocks[--n];
846 
847 		if (blocks[i].predecessors_count < 2) {
848 		    /* loop header has at least two input edges */
849 			continue;
850 		}
851 
852 		for (j = 0; j < blocks[i].predecessors_count; j++) {
853 			int pred = cfg->predecessors[blocks[i].predecessor_offset + j];
854 
855 			/* A join edge is one for which the predecessor does not
856 			   immediately dominate the successor. */
857 			if (blocks[i].idom == pred) {
858 				continue;
859 			}
860 
861 			/* In a loop back-edge (back-join edge), the successor dominates
862 			   the predecessor.  */
863 			if (dominates(blocks, i, pred)) {
864 				blocks[i].flags |= ZEND_BB_LOOP_HEADER;
865 				flag &= ~ZEND_FUNC_NO_LOOPS;
866 				if (!zend_worklist_len(&work)) {
867 					zend_bitset_clear(work.visited, zend_bitset_len(cfg->blocks_count));
868 				}
869 				zend_worklist_push(&work, pred);
870 			} else {
871 				/* Otherwise it's a cross-join edge.  See if it's a branch
872 				   to an ancestor on the DJ spanning tree.  */
873 				if (entry_times[pred] > entry_times[i] && exit_times[pred] < exit_times[i]) {
874 					blocks[i].flags |= ZEND_BB_IRREDUCIBLE_LOOP;
875 					flag |= ZEND_FUNC_IRREDUCIBLE;
876 					flag &= ~ZEND_FUNC_NO_LOOPS;
877 				}
878 			}
879 		}
880 		while (zend_worklist_len(&work)) {
881 			j = zend_worklist_pop(&work);
882 			while (blocks[j].loop_header >= 0) {
883 				j = blocks[j].loop_header;
884 			}
885 			if (j != i) {
886 				if (blocks[j].idom < 0 && j != 0) {
887 					/* Ignore blocks that are unreachable or only abnormally reachable. */
888 					continue;
889 				}
890 				blocks[j].loop_header = i;
891 				for (k = 0; k < blocks[j].predecessors_count; k++) {
892 					zend_worklist_push(&work, cfg->predecessors[blocks[j].predecessor_offset + k]);
893 				}
894 			}
895 		}
896 	}
897 
898 	free_alloca(entry_times, tree_use_heap);
899 	ZEND_WORKLIST_FREE_ALLOCA(&work, list_use_heap);
900 
901 	cfg->flags |= flag;
902 }
903 /* }}} */
904