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