xref: /PHP-8.2/Zend/Optimizer/zend_cfg.c (revision eecbb60d)
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 				zend_uchar 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 				BB_START(OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes);
373 				BB_START(i + 1);
374 				break;
375 			case ZEND_CATCH:
376 				if (!(opline->extended_value & ZEND_LAST_CATCH)) {
377 					BB_START(OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes);
378 				}
379 				BB_START(i + 1);
380 				break;
381 			case ZEND_FE_FETCH_R:
382 			case ZEND_FE_FETCH_RW:
383 				BB_START(ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value));
384 				BB_START(i + 1);
385 				break;
386 			case ZEND_FE_RESET_R:
387 			case ZEND_FE_RESET_RW:
388 				BB_START(OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes);
389 				BB_START(i + 1);
390 				break;
391 			case ZEND_SWITCH_LONG:
392 			case ZEND_SWITCH_STRING:
393 			case ZEND_MATCH:
394 			{
395 				HashTable *jumptable = Z_ARRVAL_P(CRT_CONSTANT(opline->op2));
396 				zval *zv;
397 				ZEND_HASH_FOREACH_VAL(jumptable, zv) {
398 					BB_START(ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv)));
399 				} ZEND_HASH_FOREACH_END();
400 				BB_START(ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value));
401 				BB_START(i + 1);
402 				break;
403 			}
404 			case ZEND_FETCH_R:
405 			case ZEND_FETCH_W:
406 			case ZEND_FETCH_RW:
407 			case ZEND_FETCH_FUNC_ARG:
408 			case ZEND_FETCH_IS:
409 			case ZEND_FETCH_UNSET:
410 			case ZEND_UNSET_VAR:
411 			case ZEND_ISSET_ISEMPTY_VAR:
412 				if (opline->extended_value & ZEND_FETCH_LOCAL) {
413 					flags |= ZEND_FUNC_INDIRECT_VAR_ACCESS;
414 				} else if ((opline->extended_value & (ZEND_FETCH_GLOBAL | ZEND_FETCH_GLOBAL_LOCK)) &&
415 				           !op_array->function_name) {
416 					flags |= ZEND_FUNC_INDIRECT_VAR_ACCESS;
417 				}
418 				break;
419 			case ZEND_FUNC_GET_ARGS:
420 				flags |= ZEND_FUNC_VARARG;
421 				break;
422 			case ZEND_EXT_STMT:
423 				flags |= ZEND_FUNC_HAS_EXTENDED_STMT;
424 				break;
425 			case ZEND_EXT_FCALL_BEGIN:
426 			case ZEND_EXT_FCALL_END:
427 				flags |= ZEND_FUNC_HAS_EXTENDED_FCALL;
428 				break;
429 			case ZEND_FREE:
430 			case ZEND_FE_FREE:
431 				if (zend_optimizer_is_loop_var_free(opline)
432 				 && ((opline-1)->opcode != ZEND_MATCH_ERROR
433 				  || (opline-1)->extended_value != ZEND_THROW_IS_EXPR)) {
434 					BB_START(i);
435 					flags |= ZEND_FUNC_FREE_LOOP_VAR;
436 				}
437 				break;
438 		}
439 	}
440 
441 	/* If the entry block has predecessors, we may need to split it */
442 	if ((build_flags & ZEND_CFG_NO_ENTRY_PREDECESSORS)
443 			&& op_array->last > 0 && block_map[0] > 1) {
444 		extra_entry_block = 1;
445 	}
446 
447 	if (op_array->last_try_catch) {
448 		for (j = 0; j < op_array->last_try_catch; j++) {
449 			BB_START(op_array->try_catch_array[j].try_op);
450 			if (op_array->try_catch_array[j].catch_op) {
451 				BB_START(op_array->try_catch_array[j].catch_op);
452 			}
453 			if (op_array->try_catch_array[j].finally_op) {
454 				BB_START(op_array->try_catch_array[j].finally_op);
455 			}
456 			if (op_array->try_catch_array[j].finally_end) {
457 				BB_START(op_array->try_catch_array[j].finally_end);
458 			}
459 		}
460 	}
461 
462 	blocks_count += extra_entry_block;
463 	cfg->blocks_count = blocks_count;
464 
465 	/* Build CFG, Step 2: Build Array of Basic Blocks */
466 	cfg->blocks = blocks = zend_arena_calloc(arena, sizeof(zend_basic_block), blocks_count);
467 
468 	blocks_count = -1;
469 
470 	if (extra_entry_block) {
471 		initialize_block(&blocks[0]);
472 		blocks[0].start = 0;
473 		blocks[0].len = 0;
474 		blocks_count++;
475 	}
476 
477 	for (i = 0; i < op_array->last; i++) {
478 		if (block_map[i]) {
479 			if (blocks_count >= 0) {
480 				blocks[blocks_count].len = i - blocks[blocks_count].start;
481 			}
482 			blocks_count++;
483 			initialize_block(&blocks[blocks_count]);
484 			blocks[blocks_count].start = i;
485 		}
486 		block_map[i] = blocks_count;
487 	}
488 
489 	blocks[blocks_count].len = i - blocks[blocks_count].start;
490 	blocks_count++;
491 
492 	/* Build CFG, Step 3: Calculate successors */
493 	for (j = 0; j < blocks_count; j++) {
494 		zend_basic_block *block = &blocks[j];
495 		zend_op *opline;
496 		if (block->len == 0) {
497 			block->successors_count = 1;
498 			block->successors[0] = j + 1;
499 			continue;
500 		}
501 
502 		opline = op_array->opcodes + block->start + block->len - 1;
503 		switch (opline->opcode) {
504 			case ZEND_FAST_RET:
505 			case ZEND_RETURN:
506 			case ZEND_RETURN_BY_REF:
507 			case ZEND_GENERATOR_RETURN:
508 			case ZEND_EXIT:
509 			case ZEND_THROW:
510 			case ZEND_MATCH_ERROR:
511 			case ZEND_VERIFY_NEVER_TYPE:
512 				break;
513 			case ZEND_JMP:
514 				block->successors_count = 1;
515 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op1) - op_array->opcodes];
516 				break;
517 			case ZEND_JMPZ:
518 			case ZEND_JMPNZ:
519 			case ZEND_JMPZ_EX:
520 			case ZEND_JMPNZ_EX:
521 			case ZEND_JMP_SET:
522 			case ZEND_COALESCE:
523 			case ZEND_ASSERT_CHECK:
524 			case ZEND_JMP_NULL:
525 				block->successors_count = 2;
526 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes];
527 				block->successors[1] = j + 1;
528 				break;
529 			case ZEND_CATCH:
530 				if (!(opline->extended_value & ZEND_LAST_CATCH)) {
531 					block->successors_count = 2;
532 					block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes];
533 					block->successors[1] = j + 1;
534 				} else {
535 					block->successors_count = 1;
536 					block->successors[0] = j + 1;
537 				}
538 				break;
539 			case ZEND_FE_FETCH_R:
540 			case ZEND_FE_FETCH_RW:
541 				block->successors_count = 2;
542 				block->successors[0] = block_map[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value)];
543 				block->successors[1] = j + 1;
544 				break;
545 			case ZEND_FE_RESET_R:
546 			case ZEND_FE_RESET_RW:
547 				block->successors_count = 2;
548 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op2) - op_array->opcodes];
549 				block->successors[1] = j + 1;
550 				break;
551 			case ZEND_FAST_CALL:
552 				block->successors_count = 2;
553 				block->successors[0] = block_map[OP_JMP_ADDR(opline, opline->op1) - op_array->opcodes];
554 				block->successors[1] = j + 1;
555 				break;
556 			case ZEND_SWITCH_LONG:
557 			case ZEND_SWITCH_STRING:
558 			case ZEND_MATCH:
559 			{
560 				HashTable *jumptable = Z_ARRVAL_P(CRT_CONSTANT(opline->op2));
561 				zval *zv;
562 				uint32_t s = 0;
563 
564 				block->successors_count = (opline->opcode == ZEND_MATCH ? 1 : 2) + zend_hash_num_elements(jumptable);
565 				block->successors = zend_arena_calloc(arena, block->successors_count, sizeof(int));
566 
567 				ZEND_HASH_FOREACH_VAL(jumptable, zv) {
568 					block->successors[s++] = block_map[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv))];
569 				} ZEND_HASH_FOREACH_END();
570 
571 				block->successors[s++] = block_map[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value)];
572 				if (opline->opcode != ZEND_MATCH) {
573 					block->successors[s++] = j + 1;
574 				}
575 				break;
576 			}
577 			default:
578 				block->successors_count = 1;
579 				block->successors[0] = j + 1;
580 				break;
581 		}
582 	}
583 
584 	/* Build CFG, Step 4, Mark Reachable Basic Blocks */
585 	cfg->flags |= flags;
586 	zend_mark_reachable_blocks(op_array, cfg, 0);
587 }
588 /* }}} */
589 
zend_cfg_build_predecessors(zend_arena ** arena,zend_cfg * cfg)590 ZEND_API void zend_cfg_build_predecessors(zend_arena **arena, zend_cfg *cfg) /* {{{ */
591 {
592 	int j, s, edges;
593 	zend_basic_block *b;
594 	zend_basic_block *blocks = cfg->blocks;
595 	zend_basic_block *end = blocks + cfg->blocks_count;
596 	int *predecessors;
597 
598 	edges = 0;
599 	for (b = blocks; b < end; b++) {
600 		b->predecessors_count = 0;
601 	}
602 	for (b = blocks; b < end; b++) {
603 		if (!(b->flags & ZEND_BB_REACHABLE)) {
604 			b->successors_count = 0;
605 			b->predecessors_count = 0;
606 		} else {
607 			for (s = 0; s < b->successors_count; s++) {
608 				edges++;
609 				blocks[b->successors[s]].predecessors_count++;
610 			}
611 		}
612 	}
613 
614 	cfg->edges_count = edges;
615 	cfg->predecessors = predecessors = (int*)zend_arena_calloc(arena, sizeof(int), edges);
616 
617 	edges = 0;
618 	for (b = blocks; b < end; b++) {
619 		if (b->flags & ZEND_BB_REACHABLE) {
620 			b->predecessor_offset = edges;
621 			edges += b->predecessors_count;
622 			b->predecessors_count = 0;
623 		}
624 	}
625 
626 	for (j = 0; j < cfg->blocks_count; j++) {
627 		if (blocks[j].flags & ZEND_BB_REACHABLE) {
628 			/* SWITCH_STRING/LONG may have few identical successors */
629 			for (s = 0; s < blocks[j].successors_count; s++) {
630 				int duplicate = 0;
631 				int p;
632 
633 				for (p = 0; p < s; p++) {
634 					if (blocks[j].successors[p] == blocks[j].successors[s]) {
635 						duplicate = 1;
636 						break;
637 					}
638 				}
639 				if (!duplicate) {
640 					zend_basic_block *b = blocks + blocks[j].successors[s];
641 
642 					predecessors[b->predecessor_offset + b->predecessors_count] = j;
643 					b->predecessors_count++;
644 				}
645 			}
646 		}
647 	}
648 }
649 /* }}} */
650 
651 /* Computes a postorder numbering of the CFG */
compute_postnum_recursive(int * postnum,int * cur,const zend_cfg * cfg,int block_num)652 static void compute_postnum_recursive(
653 		int *postnum, int *cur, const zend_cfg *cfg, int block_num) /* {{{ */
654 {
655 	int s;
656 	zend_basic_block *block = &cfg->blocks[block_num];
657 	if (postnum[block_num] != -1) {
658 		return;
659 	}
660 
661 	postnum[block_num] = -2; /* Marker for "currently visiting" */
662 	for (s = 0; s < block->successors_count; s++) {
663 		compute_postnum_recursive(postnum, cur, cfg, block->successors[s]);
664 	}
665 	postnum[block_num] = (*cur)++;
666 }
667 /* }}} */
668 
669 /* Computes dominator tree using algorithm from "A Simple, Fast Dominance Algorithm" by
670  * Cooper, Harvey and Kennedy. */
zend_cfg_compute_dominators_tree(const zend_op_array * op_array,zend_cfg * cfg)671 ZEND_API void zend_cfg_compute_dominators_tree(const zend_op_array *op_array, zend_cfg *cfg) /* {{{ */
672 {
673 	zend_basic_block *blocks = cfg->blocks;
674 	int blocks_count = cfg->blocks_count;
675 	int j, k, changed;
676 
677 	if (cfg->blocks_count == 1) {
678 		blocks[0].level = 0;
679 		return;
680 	}
681 
682 	ALLOCA_FLAG(use_heap)
683 	int *postnum = do_alloca(sizeof(int) * cfg->blocks_count, use_heap);
684 	memset(postnum, -1, sizeof(int) * cfg->blocks_count);
685 	j = 0;
686 	compute_postnum_recursive(postnum, &j, cfg, 0);
687 
688 	/* FIXME: move declarations */
689 	blocks[0].idom = 0;
690 	do {
691 		changed = 0;
692 		/* Iterating in RPO here would converge faster */
693 		for (j = 1; j < blocks_count; j++) {
694 			int idom = -1;
695 
696 			if ((blocks[j].flags & ZEND_BB_REACHABLE) == 0) {
697 				continue;
698 			}
699 			for (k = 0; k < blocks[j].predecessors_count; k++) {
700 				int pred = cfg->predecessors[blocks[j].predecessor_offset + k];
701 
702 				if (blocks[pred].idom >= 0) {
703 					if (idom < 0) {
704 						idom = pred;
705 					} else {
706 						while (idom != pred) {
707 							while (postnum[pred] < postnum[idom]) pred = blocks[pred].idom;
708 							while (postnum[idom] < postnum[pred]) idom = blocks[idom].idom;
709 						}
710 					}
711 				}
712 			}
713 
714 			if (idom >= 0 && blocks[j].idom != idom) {
715 				blocks[j].idom = idom;
716 				changed = 1;
717 			}
718 		}
719 	} while (changed);
720 	blocks[0].idom = -1;
721 
722 	for (j = 1; j < blocks_count; j++) {
723 		if ((blocks[j].flags & ZEND_BB_REACHABLE) == 0) {
724 			continue;
725 		}
726 		if (blocks[j].idom >= 0) {
727 			/* Sort by block number to traverse children in pre-order */
728 			if (blocks[blocks[j].idom].children < 0 ||
729 			    j < blocks[blocks[j].idom].children) {
730 				blocks[j].next_child = blocks[blocks[j].idom].children;
731 				blocks[blocks[j].idom].children = j;
732 			} else {
733 				int k = blocks[blocks[j].idom].children;
734 				while (blocks[k].next_child >=0 && j > blocks[k].next_child) {
735 					k = blocks[k].next_child;
736 				}
737 				blocks[j].next_child = blocks[k].next_child;
738 				blocks[k].next_child = j;
739 			}
740 		}
741 	}
742 
743 	for (j = 0; j < blocks_count; j++) {
744 		int idom = blocks[j].idom, level = 0;
745 		if ((blocks[j].flags & ZEND_BB_REACHABLE) == 0) {
746 			continue;
747 		}
748 		while (idom >= 0) {
749 			level++;
750 			if (blocks[idom].level >= 0) {
751 				level += blocks[idom].level;
752 				break;
753 			} else {
754 				idom = blocks[idom].idom;
755 			}
756 		}
757 		blocks[j].level = level;
758 	}
759 
760 	free_alloca(postnum, use_heap);
761 }
762 /* }}} */
763 
dominates(zend_basic_block * blocks,int a,int b)764 static bool dominates(zend_basic_block *blocks, int a, int b) /* {{{ */
765 {
766 	while (blocks[b].level > blocks[a].level) {
767 		b = blocks[b].idom;
768 	}
769 	return a == b;
770 }
771 /* }}} */
772 
zend_cfg_identify_loops(const zend_op_array * op_array,zend_cfg * cfg)773 ZEND_API void zend_cfg_identify_loops(const zend_op_array *op_array, zend_cfg *cfg) /* {{{ */
774 {
775 	int i, j, k, n;
776 	int time;
777 	zend_basic_block *blocks = cfg->blocks;
778 	int *entry_times, *exit_times;
779 	zend_worklist work;
780 	int flag = ZEND_FUNC_NO_LOOPS;
781 	int *sorted_blocks;
782 	ALLOCA_FLAG(list_use_heap)
783 	ALLOCA_FLAG(tree_use_heap)
784 
785 	if (cfg->blocks_count == 1) {
786 		cfg->flags |= flag;
787 		return;
788 	}
789 
790 	ZEND_WORKLIST_ALLOCA(&work, cfg->blocks_count, list_use_heap);
791 
792 	/* We don't materialize the DJ spanning tree explicitly, as we are only interested in ancestor
793 	 * queries. These are implemented by checking entry/exit times of the DFS search. */
794 	entry_times = do_alloca(3 * sizeof(int) * cfg->blocks_count, tree_use_heap);
795 	exit_times = entry_times + cfg->blocks_count;
796 	sorted_blocks = exit_times + cfg->blocks_count;
797 	memset(entry_times, -1, 2 * sizeof(int) * cfg->blocks_count);
798 
799 	zend_worklist_push(&work, 0);
800 	time = 0;
801 	while (zend_worklist_len(&work)) {
802 	next:
803 		i = zend_worklist_peek(&work);
804 		if (entry_times[i] == -1) {
805 			entry_times[i] = time++;
806 		}
807 		/* Visit blocks immediately dominated by i. */
808 		for (j = blocks[i].children; j >= 0; j = blocks[j].next_child) {
809 			if (zend_worklist_push(&work, j)) {
810 				goto next;
811 			}
812 		}
813 		/* Visit join edges.  */
814 		for (j = 0; j < blocks[i].successors_count; j++) {
815 			int succ = blocks[i].successors[j];
816 			if (blocks[succ].idom == i) {
817 				continue;
818 			} else if (zend_worklist_push(&work, succ)) {
819 				goto next;
820 			}
821 		}
822 		exit_times[i] = time++;
823 		zend_worklist_pop(&work);
824 	}
825 
826 	/* Sort blocks by level, which is the opposite order in which we want to process them */
827 	sorted_blocks[0] = 0;
828 	j = 0;
829 	n = 1;
830 	while (j != n) {
831 		i = j;
832 		j = n;
833 		for (; i < j; i++) {
834 			int child;
835 			for (child = blocks[sorted_blocks[i]].children; child >= 0; child = blocks[child].next_child) {
836 				sorted_blocks[n++] = child;
837 			}
838 		}
839 	}
840 
841 	/* Identify loops. See Sreedhar et al, "Identifying Loops Using DJ Graphs". */
842 	while (n > 0) {
843 		i = sorted_blocks[--n];
844 
845 		if (blocks[i].predecessors_count < 2) {
846 		    /* loop header has at least two input edges */
847 			continue;
848 		}
849 
850 		for (j = 0; j < blocks[i].predecessors_count; j++) {
851 			int pred = cfg->predecessors[blocks[i].predecessor_offset + j];
852 
853 			/* A join edge is one for which the predecessor does not
854 			   immediately dominate the successor. */
855 			if (blocks[i].idom == pred) {
856 				continue;
857 			}
858 
859 			/* In a loop back-edge (back-join edge), the successor dominates
860 			   the predecessor.  */
861 			if (dominates(blocks, i, pred)) {
862 				blocks[i].flags |= ZEND_BB_LOOP_HEADER;
863 				flag &= ~ZEND_FUNC_NO_LOOPS;
864 				if (!zend_worklist_len(&work)) {
865 					zend_bitset_clear(work.visited, zend_bitset_len(cfg->blocks_count));
866 				}
867 				zend_worklist_push(&work, pred);
868 			} else {
869 				/* Otherwise it's a cross-join edge.  See if it's a branch
870 				   to an ancestor on the DJ spanning tree.  */
871 				if (entry_times[pred] > entry_times[i] && exit_times[pred] < exit_times[i]) {
872 					blocks[i].flags |= ZEND_BB_IRREDUCIBLE_LOOP;
873 					flag |= ZEND_FUNC_IRREDUCIBLE;
874 					flag &= ~ZEND_FUNC_NO_LOOPS;
875 				}
876 			}
877 		}
878 		while (zend_worklist_len(&work)) {
879 			j = zend_worklist_pop(&work);
880 			while (blocks[j].loop_header >= 0) {
881 				j = blocks[j].loop_header;
882 			}
883 			if (j != i) {
884 				if (blocks[j].idom < 0 && j != 0) {
885 					/* Ignore blocks that are unreachable or only abnormally reachable. */
886 					continue;
887 				}
888 				blocks[j].loop_header = i;
889 				for (k = 0; k < blocks[j].predecessors_count; k++) {
890 					zend_worklist_push(&work, cfg->predecessors[blocks[j].predecessor_offset + k]);
891 				}
892 			}
893 		}
894 	}
895 
896 	free_alloca(entry_times, tree_use_heap);
897 	ZEND_WORKLIST_FREE_ALLOCA(&work, list_use_heap);
898 
899 	cfg->flags |= flag;
900 }
901 /* }}} */
902