xref: /php-src/Zend/Optimizer/zend_optimizer.c (revision 2e9cc9bc)
1 /*
2    +----------------------------------------------------------------------+
3    | Zend OPcache                                                         |
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: Andi Gutmans <andi@php.net>                                 |
16    |          Zeev Suraski <zeev@php.net>                                 |
17    |          Stanislav Malyshev <stas@zend.com>                          |
18    |          Dmitry Stogov <dmitry@php.net>                              |
19    +----------------------------------------------------------------------+
20 */
21 
22 #include "Optimizer/zend_optimizer.h"
23 #include "Optimizer/zend_optimizer_internal.h"
24 #include "zend_API.h"
25 #include "zend_constants.h"
26 #include "zend_execute.h"
27 #include "zend_vm.h"
28 #include "zend_cfg.h"
29 #include "zend_func_info.h"
30 #include "zend_call_graph.h"
31 #include "zend_inference.h"
32 #include "zend_dump.h"
33 #include "php.h"
34 
35 #ifndef ZEND_OPTIMIZER_MAX_REGISTERED_PASSES
36 # define ZEND_OPTIMIZER_MAX_REGISTERED_PASSES 32
37 #endif
38 
39 struct {
40 	zend_optimizer_pass_t pass[ZEND_OPTIMIZER_MAX_REGISTERED_PASSES];
41 	int last;
42 } zend_optimizer_registered_passes = {{NULL}, 0};
43 
zend_optimizer_collect_constant(zend_optimizer_ctx * ctx,zval * name,zval * value)44 void zend_optimizer_collect_constant(zend_optimizer_ctx *ctx, zval *name, zval* value)
45 {
46 	if (!ctx->constants) {
47 		ctx->constants = zend_arena_alloc(&ctx->arena, sizeof(HashTable));
48 		zend_hash_init(ctx->constants, 16, NULL, zval_ptr_dtor_nogc, 0);
49 	}
50 
51 	if (zend_hash_add(ctx->constants, Z_STR_P(name), value)) {
52 		Z_TRY_ADDREF_P(value);
53 	}
54 }
55 
zend_optimizer_eval_binary_op(zval * result,uint8_t opcode,zval * op1,zval * op2)56 zend_result zend_optimizer_eval_binary_op(zval *result, uint8_t opcode, zval *op1, zval *op2) /* {{{ */
57 {
58 	if (zend_binary_op_produces_error(opcode, op1, op2)) {
59 		return FAILURE;
60 	}
61 
62 	binary_op_type binary_op = get_binary_op(opcode);
63 	return binary_op(result, op1, op2);
64 }
65 /* }}} */
66 
zend_optimizer_eval_unary_op(zval * result,uint8_t opcode,zval * op1)67 zend_result zend_optimizer_eval_unary_op(zval *result, uint8_t opcode, zval *op1) /* {{{ */
68 {
69 	unary_op_type unary_op = get_unary_op(opcode);
70 
71 	if (unary_op) {
72 		if (zend_unary_op_produces_error(opcode, op1)) {
73 			return FAILURE;
74 		}
75 		return unary_op(result, op1);
76 	} else { /* ZEND_BOOL */
77 		ZVAL_BOOL(result, zend_is_true(op1));
78 		return SUCCESS;
79 	}
80 }
81 /* }}} */
82 
zend_optimizer_eval_cast(zval * result,uint32_t type,zval * op1)83 zend_result zend_optimizer_eval_cast(zval *result, uint32_t type, zval *op1) /* {{{ */
84 {
85 	switch (type) {
86 		case IS_NULL:
87 			ZVAL_NULL(result);
88 			return SUCCESS;
89 		case _IS_BOOL:
90 			ZVAL_BOOL(result, zval_is_true(op1));
91 			return SUCCESS;
92 		case IS_LONG:
93 			ZVAL_LONG(result, zval_get_long(op1));
94 			return SUCCESS;
95 		case IS_DOUBLE:
96 			ZVAL_DOUBLE(result, zval_get_double(op1));
97 			return SUCCESS;
98 		case IS_STRING:
99 			/* Conversion from double to string takes into account run-time
100 			   'precision' setting and cannot be evaluated at compile-time */
101 			if (Z_TYPE_P(op1) != IS_ARRAY && Z_TYPE_P(op1) != IS_DOUBLE) {
102 				ZVAL_STR(result, zval_get_string(op1));
103 				return SUCCESS;
104 			}
105 			break;
106 		case IS_ARRAY:
107 			ZVAL_COPY(result, op1);
108 			convert_to_array(result);
109 			return SUCCESS;
110 	}
111 	return FAILURE;
112 }
113 /* }}} */
114 
zend_optimizer_eval_strlen(zval * result,const zval * op1)115 zend_result zend_optimizer_eval_strlen(zval *result, const zval *op1) /* {{{ */
116 {
117 	if (Z_TYPE_P(op1) != IS_STRING) {
118 		return FAILURE;
119 	}
120 	ZVAL_LONG(result, Z_STRLEN_P(op1));
121 	return SUCCESS;
122 }
123 /* }}} */
124 
zend_optimizer_eval_special_func_call(zval * result,zend_string * name,zend_string * arg)125 zend_result zend_optimizer_eval_special_func_call(
126 		zval *result, zend_string *name, zend_string *arg) {
127 	if (zend_string_equals_literal(name, "function_exists") ||
128 			zend_string_equals_literal(name, "is_callable")) {
129 		zend_string *lc_name = zend_string_tolower(arg);
130 		zend_internal_function *func = zend_hash_find_ptr(EG(function_table), lc_name);
131 		zend_string_release_ex(lc_name, 0);
132 
133 		if (func && func->type == ZEND_INTERNAL_FUNCTION
134 				&& func->module->type == MODULE_PERSISTENT
135 #ifdef ZEND_WIN32
136 				&& func->module->handle == NULL
137 #endif
138 		) {
139 			ZVAL_TRUE(result);
140 			return SUCCESS;
141 		}
142 		return FAILURE;
143 	}
144 	if (zend_string_equals_literal(name, "extension_loaded")) {
145 		zend_string *lc_name = zend_string_tolower(arg);
146 		zend_module_entry *m = zend_hash_find_ptr(&module_registry, lc_name);
147 		zend_string_release_ex(lc_name, 0);
148 
149 		if (!m) {
150 			if (PG(enable_dl)) {
151 				return FAILURE;
152 			}
153 			ZVAL_FALSE(result);
154 			return SUCCESS;
155 		}
156 
157 		if (m->type == MODULE_PERSISTENT
158 #ifdef ZEND_WIN32
159 			&& m->handle == NULL
160 #endif
161 		) {
162 			ZVAL_TRUE(result);
163 			return SUCCESS;
164 		}
165 		return FAILURE;
166 	}
167 	if (zend_string_equals_literal(name, "constant")) {
168 		return zend_optimizer_get_persistent_constant(arg, result, 1) ? SUCCESS : FAILURE;
169 	}
170 	if (zend_string_equals_literal(name, "dirname")) {
171 		if (!IS_ABSOLUTE_PATH(ZSTR_VAL(arg), ZSTR_LEN(arg))) {
172 			return FAILURE;
173 		}
174 
175 		zend_string *dirname = zend_string_init(ZSTR_VAL(arg), ZSTR_LEN(arg), 0);
176 		ZSTR_LEN(dirname) = zend_dirname(ZSTR_VAL(dirname), ZSTR_LEN(dirname));
177 		if (IS_ABSOLUTE_PATH(ZSTR_VAL(dirname), ZSTR_LEN(dirname))) {
178 			ZVAL_STR(result, dirname);
179 			return SUCCESS;
180 		}
181 		zend_string_release_ex(dirname, 0);
182 		return FAILURE;
183 	}
184 	if (zend_string_equals_literal(name, "ini_get")) {
185 		zend_ini_entry *ini_entry = zend_hash_find_ptr(EG(ini_directives), arg);
186 		if (!ini_entry) {
187 			if (PG(enable_dl)) {
188 				return FAILURE;
189 			}
190 			ZVAL_FALSE(result);
191 		} else if (ini_entry->modifiable != ZEND_INI_SYSTEM) {
192 			return FAILURE;
193 		} else if (ini_entry->value) {
194 			ZVAL_STR_COPY(result, ini_entry->value);
195 		} else {
196 			ZVAL_EMPTY_STRING(result);
197 		}
198 		return SUCCESS;
199 	}
200 	return FAILURE;
201 }
202 
zend_optimizer_get_collected_constant(HashTable * constants,zval * name,zval * value)203 bool zend_optimizer_get_collected_constant(HashTable *constants, zval *name, zval* value)
204 {
205 	zval *val;
206 
207 	if ((val = zend_hash_find(constants, Z_STR_P(name))) != NULL) {
208 		ZVAL_COPY(value, val);
209 		return 1;
210 	}
211 	return 0;
212 }
213 
zend_optimizer_convert_to_free_op1(zend_op_array * op_array,zend_op * opline)214 void zend_optimizer_convert_to_free_op1(zend_op_array *op_array, zend_op *opline)
215 {
216 	if (opline->op1_type == IS_CV) {
217 		opline->opcode = ZEND_CHECK_VAR;
218 		SET_UNUSED(opline->op2);
219 		SET_UNUSED(opline->result);
220 		opline->extended_value = 0;
221 	} else if (opline->op1_type & (IS_TMP_VAR|IS_VAR)) {
222 		opline->opcode = ZEND_FREE;
223 		SET_UNUSED(opline->op2);
224 		SET_UNUSED(opline->result);
225 		opline->extended_value = 0;
226 	} else {
227 		ZEND_ASSERT(opline->op1_type == IS_CONST);
228 		literal_dtor(&ZEND_OP1_LITERAL(opline));
229 		MAKE_NOP(opline);
230 	}
231 }
232 
zend_optimizer_add_literal(zend_op_array * op_array,const zval * zv)233 int zend_optimizer_add_literal(zend_op_array *op_array, const zval *zv)
234 {
235 	int i = op_array->last_literal;
236 	op_array->last_literal++;
237 	op_array->literals = (zval*)erealloc(op_array->literals, op_array->last_literal * sizeof(zval));
238 	ZVAL_COPY_VALUE(&op_array->literals[i], zv);
239 	Z_EXTRA(op_array->literals[i]) = 0;
240 	return i;
241 }
242 
zend_optimizer_add_literal_string(zend_op_array * op_array,zend_string * str)243 static inline int zend_optimizer_add_literal_string(zend_op_array *op_array, zend_string *str) {
244 	zval zv;
245 	ZVAL_STR(&zv, str);
246 	zend_string_hash_val(str);
247 	return zend_optimizer_add_literal(op_array, &zv);
248 }
249 
drop_leading_backslash(zval * val)250 static inline void drop_leading_backslash(zval *val) {
251 	if (Z_STRVAL_P(val)[0] == '\\') {
252 		zend_string *str = zend_string_init(Z_STRVAL_P(val) + 1, Z_STRLEN_P(val) - 1, 0);
253 		zval_ptr_dtor_nogc(val);
254 		ZVAL_STR(val, str);
255 	}
256 }
257 
alloc_cache_slots(zend_op_array * op_array,uint32_t num)258 static inline uint32_t alloc_cache_slots(zend_op_array *op_array, uint32_t num) {
259 	uint32_t ret = op_array->cache_size;
260 	op_array->cache_size += num * sizeof(void *);
261 	return ret;
262 }
263 
264 #define REQUIRES_STRING(val) do { \
265 	if (Z_TYPE_P(val) != IS_STRING) { \
266 		return 0; \
267 	} \
268 } while (0)
269 
270 #define TO_STRING_NOWARN(val) do { \
271 	if (Z_TYPE_P(val) >= IS_ARRAY) { \
272 		return 0; \
273 	} \
274 	convert_to_string(val); \
275 } while (0)
276 
zend_optimizer_update_op1_const(zend_op_array * op_array,zend_op * opline,zval * val)277 bool zend_optimizer_update_op1_const(zend_op_array *op_array,
278                                     zend_op       *opline,
279                                     zval          *val)
280 {
281 	switch (opline->opcode) {
282 		case ZEND_OP_DATA:
283 			switch ((opline-1)->opcode) {
284 				case ZEND_ASSIGN_OBJ_REF:
285 				case ZEND_ASSIGN_STATIC_PROP_REF:
286 					return 0;
287 			}
288 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
289 			break;
290 		case ZEND_FREE:
291 		case ZEND_CHECK_VAR:
292 			MAKE_NOP(opline);
293 			zval_ptr_dtor_nogc(val);
294 			return 1;
295 		case ZEND_SEND_VAR_EX:
296 		case ZEND_SEND_FUNC_ARG:
297 		case ZEND_FETCH_DIM_W:
298 		case ZEND_FETCH_DIM_RW:
299 		case ZEND_FETCH_DIM_FUNC_ARG:
300 		case ZEND_FETCH_DIM_UNSET:
301 		case ZEND_FETCH_LIST_W:
302 		case ZEND_ASSIGN_DIM:
303 		case ZEND_RETURN_BY_REF:
304 		case ZEND_INSTANCEOF:
305 		case ZEND_MAKE_REF:
306 		case ZEND_SEPARATE:
307 		case ZEND_SEND_VAR_NO_REF:
308 		case ZEND_SEND_VAR_NO_REF_EX:
309 			return 0;
310 		case ZEND_CATCH:
311 			REQUIRES_STRING(val);
312 			drop_leading_backslash(val);
313 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
314 			opline->extended_value = alloc_cache_slots(op_array, 1) | (opline->extended_value & ZEND_LAST_CATCH);
315 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
316 			break;
317 		case ZEND_DEFINED:
318 			REQUIRES_STRING(val);
319 			drop_leading_backslash(val);
320 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
321 			opline->extended_value = alloc_cache_slots(op_array, 1);
322 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
323 			break;
324 		case ZEND_NEW:
325 			REQUIRES_STRING(val);
326 			drop_leading_backslash(val);
327 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
328 			opline->op2.num = alloc_cache_slots(op_array, 1);
329 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
330 			break;
331 		case ZEND_INIT_STATIC_METHOD_CALL:
332 			REQUIRES_STRING(val);
333 			drop_leading_backslash(val);
334 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
335 			if (opline->op2_type != IS_CONST) {
336 				opline->result.num = alloc_cache_slots(op_array, 1);
337 			}
338 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
339 			break;
340 		case ZEND_FETCH_CLASS_CONSTANT:
341 			REQUIRES_STRING(val);
342 			drop_leading_backslash(val);
343 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
344 			if (opline->op2_type != IS_CONST) {
345 				opline->extended_value = alloc_cache_slots(op_array, 1);
346 			}
347 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
348 			break;
349 		case ZEND_ASSIGN_OP:
350 		case ZEND_ASSIGN_DIM_OP:
351 		case ZEND_ASSIGN_OBJ_OP:
352 			break;
353 		case ZEND_ASSIGN_STATIC_PROP_OP:
354 		case ZEND_ASSIGN_STATIC_PROP:
355 		case ZEND_ASSIGN_STATIC_PROP_REF:
356 		case ZEND_FETCH_STATIC_PROP_R:
357 		case ZEND_FETCH_STATIC_PROP_W:
358 		case ZEND_FETCH_STATIC_PROP_RW:
359 		case ZEND_FETCH_STATIC_PROP_IS:
360 		case ZEND_FETCH_STATIC_PROP_UNSET:
361 		case ZEND_FETCH_STATIC_PROP_FUNC_ARG:
362 		case ZEND_UNSET_STATIC_PROP:
363 		case ZEND_ISSET_ISEMPTY_STATIC_PROP:
364 		case ZEND_PRE_INC_STATIC_PROP:
365 		case ZEND_PRE_DEC_STATIC_PROP:
366 		case ZEND_POST_INC_STATIC_PROP:
367 		case ZEND_POST_DEC_STATIC_PROP:
368 			TO_STRING_NOWARN(val);
369 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
370 			if (opline->op2_type == IS_CONST && (opline->extended_value & ~ZEND_FETCH_OBJ_FLAGS) + sizeof(void*) == op_array->cache_size) {
371 				op_array->cache_size += sizeof(void *);
372 			} else {
373 				opline->extended_value = alloc_cache_slots(op_array, 3) | (opline->extended_value & ZEND_FETCH_OBJ_FLAGS);
374 			}
375 			break;
376 		case ZEND_SEND_VAR:
377 			opline->opcode = ZEND_SEND_VAL;
378 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
379 			break;
380 		case ZEND_CASE:
381 			opline->opcode = ZEND_IS_EQUAL;
382 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
383 			break;
384 		case ZEND_CASE_STRICT:
385 			opline->opcode = ZEND_IS_IDENTICAL;
386 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
387 			break;
388 		case ZEND_VERIFY_RETURN_TYPE:
389 			/* This would require a non-local change.
390 			 * zend_optimizer_replace_by_const() supports this. */
391 			return 0;
392 		case ZEND_COPY_TMP:
393 		case ZEND_FETCH_CLASS_NAME:
394 			return 0;
395 		case ZEND_ECHO:
396 		{
397 			zval zv;
398 			if (Z_TYPE_P(val) != IS_STRING && zend_optimizer_eval_cast(&zv, IS_STRING, val) == SUCCESS) {
399 				zval_ptr_dtor_nogc(val);
400 				val = &zv;
401 			}
402 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
403 			if (Z_TYPE_P(val) == IS_STRING && Z_STRLEN_P(val) == 0) {
404 				MAKE_NOP(opline);
405 				return 1;
406 			}
407 			/* TODO: In a subsequent pass, *after* this step and compacting nops, combine consecutive ZEND_ECHOs using the block information from ssa->cfg */
408 			/* (e.g. for ext/opcache/tests/opt/sccp_010.phpt) */
409 			break;
410 		}
411 		case ZEND_CONCAT:
412 		case ZEND_FAST_CONCAT:
413 		case ZEND_FETCH_R:
414 		case ZEND_FETCH_W:
415 		case ZEND_FETCH_RW:
416 		case ZEND_FETCH_IS:
417 		case ZEND_FETCH_UNSET:
418 		case ZEND_FETCH_FUNC_ARG:
419 		case ZEND_ISSET_ISEMPTY_VAR:
420 		case ZEND_UNSET_VAR:
421 			TO_STRING_NOWARN(val);
422 			if (opline->opcode == ZEND_CONCAT && opline->op2_type == IS_CONST) {
423 				opline->opcode = ZEND_FAST_CONCAT;
424 			}
425 			ZEND_FALLTHROUGH;
426 		default:
427 			opline->op1.constant = zend_optimizer_add_literal(op_array, val);
428 			break;
429 	}
430 
431 	opline->op1_type = IS_CONST;
432 	if (Z_TYPE(ZEND_OP1_LITERAL(opline)) == IS_STRING) {
433 		zend_string_hash_val(Z_STR(ZEND_OP1_LITERAL(opline)));
434 	}
435 	return 1;
436 }
437 
zend_optimizer_update_op2_const(zend_op_array * op_array,zend_op * opline,zval * val)438 bool zend_optimizer_update_op2_const(zend_op_array *op_array,
439                                     zend_op       *opline,
440                                     zval          *val)
441 {
442 	zval tmp;
443 
444 	switch (opline->opcode) {
445 		case ZEND_ASSIGN_REF:
446 		case ZEND_FAST_CALL:
447 			return 0;
448 		case ZEND_FETCH_CLASS:
449 		case ZEND_INSTANCEOF:
450 			REQUIRES_STRING(val);
451 			drop_leading_backslash(val);
452 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
453 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
454 			opline->extended_value = alloc_cache_slots(op_array, 1);
455 			break;
456 		case ZEND_INIT_FCALL_BY_NAME:
457 			REQUIRES_STRING(val);
458 			drop_leading_backslash(val);
459 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
460 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
461 			opline->result.num = alloc_cache_slots(op_array, 1);
462 			break;
463 		case ZEND_ASSIGN_STATIC_PROP:
464 		case ZEND_ASSIGN_STATIC_PROP_REF:
465 		case ZEND_FETCH_STATIC_PROP_R:
466 		case ZEND_FETCH_STATIC_PROP_W:
467 		case ZEND_FETCH_STATIC_PROP_RW:
468 		case ZEND_FETCH_STATIC_PROP_IS:
469 		case ZEND_FETCH_STATIC_PROP_UNSET:
470 		case ZEND_FETCH_STATIC_PROP_FUNC_ARG:
471 		case ZEND_UNSET_STATIC_PROP:
472 		case ZEND_ISSET_ISEMPTY_STATIC_PROP:
473 		case ZEND_PRE_INC_STATIC_PROP:
474 		case ZEND_PRE_DEC_STATIC_PROP:
475 		case ZEND_POST_INC_STATIC_PROP:
476 		case ZEND_POST_DEC_STATIC_PROP:
477 		case ZEND_ASSIGN_STATIC_PROP_OP:
478 			REQUIRES_STRING(val);
479 			drop_leading_backslash(val);
480 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
481 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
482 			if (opline->op1_type != IS_CONST) {
483 				opline->extended_value = alloc_cache_slots(op_array, 1) | (opline->extended_value & (ZEND_RETURNS_FUNCTION|ZEND_ISEMPTY|ZEND_FETCH_OBJ_FLAGS));
484 			}
485 			break;
486 		case ZEND_INIT_FCALL:
487 			REQUIRES_STRING(val);
488 			if (Z_REFCOUNT_P(val) == 1) {
489 				zend_str_tolower(Z_STRVAL_P(val), Z_STRLEN_P(val));
490 			} else {
491 				ZVAL_STR(&tmp, zend_string_tolower(Z_STR_P(val)));
492 				zval_ptr_dtor_nogc(val);
493 				val = &tmp;
494 			}
495 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
496 			opline->result.num = alloc_cache_slots(op_array, 1);
497 			break;
498 		case ZEND_INIT_DYNAMIC_CALL:
499 			if (Z_TYPE_P(val) == IS_STRING) {
500 				if (zend_memrchr(Z_STRVAL_P(val), ':', Z_STRLEN_P(val))) {
501 					return 0;
502 				}
503 
504 				if (zend_optimizer_classify_function(Z_STR_P(val), opline->extended_value)) {
505 					/* Dynamic call to various special functions must stay dynamic,
506 					 * otherwise would drop a warning */
507 					return 0;
508 				}
509 
510 				opline->opcode = ZEND_INIT_FCALL_BY_NAME;
511 				drop_leading_backslash(val);
512 				opline->op2.constant = zend_optimizer_add_literal(op_array, val);
513 				zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
514 				opline->result.num = alloc_cache_slots(op_array, 1);
515 			} else {
516 				opline->op2.constant = zend_optimizer_add_literal(op_array, val);
517 			}
518 			break;
519 		case ZEND_INIT_METHOD_CALL:
520 			REQUIRES_STRING(val);
521 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
522 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
523 			opline->result.num = alloc_cache_slots(op_array, 2);
524 			break;
525 		case ZEND_INIT_STATIC_METHOD_CALL:
526 			REQUIRES_STRING(val);
527 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
528 			zend_optimizer_add_literal_string(op_array, zend_string_tolower(Z_STR_P(val)));
529 			if (opline->op1_type != IS_CONST) {
530 				opline->result.num = alloc_cache_slots(op_array, 2);
531 			}
532 			break;
533 		case ZEND_ASSIGN_OBJ:
534 		case ZEND_ASSIGN_OBJ_REF:
535 		case ZEND_FETCH_OBJ_R:
536 		case ZEND_FETCH_OBJ_W:
537 		case ZEND_FETCH_OBJ_RW:
538 		case ZEND_FETCH_OBJ_IS:
539 		case ZEND_FETCH_OBJ_UNSET:
540 		case ZEND_FETCH_OBJ_FUNC_ARG:
541 		case ZEND_UNSET_OBJ:
542 		case ZEND_PRE_INC_OBJ:
543 		case ZEND_PRE_DEC_OBJ:
544 		case ZEND_POST_INC_OBJ:
545 		case ZEND_POST_DEC_OBJ:
546 			TO_STRING_NOWARN(val);
547 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
548 			opline->extended_value = alloc_cache_slots(op_array, 3);
549 			break;
550 		case ZEND_ASSIGN_OBJ_OP:
551 			TO_STRING_NOWARN(val);
552 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
553 			ZEND_ASSERT((opline + 1)->opcode == ZEND_OP_DATA);
554 			(opline + 1)->extended_value = alloc_cache_slots(op_array, 3);
555 			break;
556 		case ZEND_ISSET_ISEMPTY_PROP_OBJ:
557 			TO_STRING_NOWARN(val);
558 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
559 			opline->extended_value = alloc_cache_slots(op_array, 3) | (opline->extended_value & ZEND_ISEMPTY);
560 			break;
561 		case ZEND_ASSIGN_DIM_OP:
562 		case ZEND_ISSET_ISEMPTY_DIM_OBJ:
563 		case ZEND_ASSIGN_DIM:
564 		case ZEND_UNSET_DIM:
565 		case ZEND_FETCH_DIM_R:
566 		case ZEND_FETCH_DIM_W:
567 		case ZEND_FETCH_DIM_RW:
568 		case ZEND_FETCH_DIM_IS:
569 		case ZEND_FETCH_DIM_FUNC_ARG:
570 		case ZEND_FETCH_DIM_UNSET:
571 		case ZEND_FETCH_LIST_R:
572 		case ZEND_FETCH_LIST_W:
573 			if (Z_TYPE_P(val) == IS_STRING) {
574 				zend_ulong index;
575 
576 				if (ZEND_HANDLE_NUMERIC(Z_STR_P(val), index)) {
577 					ZVAL_LONG(&tmp, index);
578 					opline->op2.constant = zend_optimizer_add_literal(op_array, &tmp);
579 					zend_string_hash_val(Z_STR_P(val));
580 					zend_optimizer_add_literal(op_array, val);
581 					Z_EXTRA(op_array->literals[opline->op2.constant]) = ZEND_EXTRA_VALUE;
582 					break;
583 				}
584 			}
585 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
586 			break;
587 		case ZEND_ADD_ARRAY_ELEMENT:
588 		case ZEND_INIT_ARRAY:
589 			if (Z_TYPE_P(val) == IS_STRING) {
590 				zend_ulong index;
591 				if (ZEND_HANDLE_NUMERIC(Z_STR_P(val), index)) {
592 					zval_ptr_dtor_nogc(val);
593 					ZVAL_LONG(val, index);
594 				}
595 			}
596 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
597 			break;
598 		case ZEND_ROPE_INIT:
599 		case ZEND_ROPE_ADD:
600 		case ZEND_ROPE_END:
601 		case ZEND_CONCAT:
602 		case ZEND_FAST_CONCAT:
603 			TO_STRING_NOWARN(val);
604 			if (opline->opcode == ZEND_CONCAT && opline->op1_type == IS_CONST) {
605 				opline->opcode = ZEND_FAST_CONCAT;
606 			}
607 			ZEND_FALLTHROUGH;
608 		default:
609 			opline->op2.constant = zend_optimizer_add_literal(op_array, val);
610 			break;
611 	}
612 
613 	opline->op2_type = IS_CONST;
614 	if (Z_TYPE(ZEND_OP2_LITERAL(opline)) == IS_STRING) {
615 		zend_string_hash_val(Z_STR(ZEND_OP2_LITERAL(opline)));
616 	}
617 	return 1;
618 }
619 
zend_optimizer_replace_by_const(zend_op_array * op_array,zend_op * opline,uint8_t type,uint32_t var,zval * val)620 bool zend_optimizer_replace_by_const(zend_op_array *op_array,
621                                     zend_op       *opline,
622                                     uint8_t        type,
623                                     uint32_t       var,
624                                     zval          *val)
625 {
626 	zend_op *end = op_array->opcodes + op_array->last;
627 
628 	while (opline < end) {
629 		if (opline->op1_type == type &&
630 			opline->op1.var == var) {
631 			switch (opline->opcode) {
632 				/* In most cases IS_TMP_VAR operand may be used only once.
633 				 * The operands are usually destroyed by the opcode handler.
634 				 * However, there are some exception which keep the operand alive. In that case
635 				 * we want to try to replace all uses of the temporary.
636 				 */
637 				case ZEND_FETCH_LIST_R:
638 				case ZEND_CASE:
639 				case ZEND_CASE_STRICT:
640 				case ZEND_SWITCH_LONG:
641 				case ZEND_SWITCH_STRING:
642 				case ZEND_MATCH:
643 				case ZEND_JMP_NULL: {
644 					zend_op *end = op_array->opcodes + op_array->last;
645 					while (opline < end) {
646 						if (opline->op1_type == type && opline->op1.var == var) {
647 							/* If this opcode doesn't keep the operand alive, we're done. Check
648 							 * this early, because op replacement may modify the opline. */
649 							bool is_last = opline->opcode != ZEND_FETCH_LIST_R
650 								&& opline->opcode != ZEND_CASE
651 								&& opline->opcode != ZEND_CASE_STRICT
652 								&& opline->opcode != ZEND_SWITCH_LONG
653 								&& opline->opcode != ZEND_SWITCH_STRING
654 								&& opline->opcode != ZEND_MATCH
655 								&& opline->opcode != ZEND_JMP_NULL
656 								&& (opline->opcode != ZEND_FREE
657 									|| opline->extended_value != ZEND_FREE_ON_RETURN);
658 
659 							Z_TRY_ADDREF_P(val);
660 							if (!zend_optimizer_update_op1_const(op_array, opline, val)) {
661 								zval_ptr_dtor(val);
662 								return 0;
663 							}
664 							if (is_last) {
665 								break;
666 							}
667 						}
668 						opline++;
669 					}
670 					zval_ptr_dtor_nogc(val);
671 					return 1;
672 				}
673 				case ZEND_VERIFY_RETURN_TYPE: {
674 					zend_arg_info *ret_info = op_array->arg_info - 1;
675 					if (!ZEND_TYPE_CONTAINS_CODE(ret_info->type, Z_TYPE_P(val))
676 						|| (op_array->fn_flags & ZEND_ACC_RETURN_REFERENCE)) {
677 						return 0;
678 					}
679 					MAKE_NOP(opline);
680 
681 					/* zend_handle_loops_and_finally may inserts other oplines */
682 					do {
683 						++opline;
684 					} while (opline->opcode != ZEND_RETURN && opline->opcode != ZEND_RETURN_BY_REF);
685 					ZEND_ASSERT(opline->op1.var == var);
686 
687 					break;
688 				}
689 				default:
690 					break;
691 			}
692 			return zend_optimizer_update_op1_const(op_array, opline, val);
693 		}
694 
695 		if (opline->op2_type == type &&
696 			opline->op2.var == var) {
697 			return zend_optimizer_update_op2_const(op_array, opline, val);
698 		}
699 		opline++;
700 	}
701 
702 	return 1;
703 }
704 
705 /* Update jump offsets after a jump was migrated to another opline */
zend_optimizer_migrate_jump(zend_op_array * op_array,zend_op * new_opline,zend_op * opline)706 void zend_optimizer_migrate_jump(zend_op_array *op_array, zend_op *new_opline, zend_op *opline) {
707 	switch (new_opline->opcode) {
708 		case ZEND_JMP:
709 		case ZEND_FAST_CALL:
710 			ZEND_SET_OP_JMP_ADDR(new_opline, new_opline->op1, ZEND_OP1_JMP_ADDR(opline));
711 			break;
712 		case ZEND_JMPZ:
713 		case ZEND_JMPNZ:
714 		case ZEND_JMPZ_EX:
715 		case ZEND_JMPNZ_EX:
716 		case ZEND_FE_RESET_R:
717 		case ZEND_FE_RESET_RW:
718 		case ZEND_JMP_SET:
719 		case ZEND_COALESCE:
720 		case ZEND_ASSERT_CHECK:
721 		case ZEND_JMP_NULL:
722 		case ZEND_BIND_INIT_STATIC_OR_JMP:
723 		case ZEND_JMP_FRAMELESS:
724 			ZEND_SET_OP_JMP_ADDR(new_opline, new_opline->op2, ZEND_OP2_JMP_ADDR(opline));
725 			break;
726 		case ZEND_FE_FETCH_R:
727 		case ZEND_FE_FETCH_RW:
728 			new_opline->extended_value = ZEND_OPLINE_NUM_TO_OFFSET(op_array, new_opline, ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value));
729 			break;
730 		case ZEND_CATCH:
731 			if (!(opline->extended_value & ZEND_LAST_CATCH)) {
732 				ZEND_SET_OP_JMP_ADDR(new_opline, new_opline->op2, ZEND_OP2_JMP_ADDR(opline));
733 			}
734 			break;
735 		case ZEND_SWITCH_LONG:
736 		case ZEND_SWITCH_STRING:
737 		case ZEND_MATCH:
738 		{
739 			HashTable *jumptable = Z_ARRVAL(ZEND_OP2_LITERAL(opline));
740 			zval *zv;
741 			ZEND_HASH_FOREACH_VAL(jumptable, zv) {
742 				Z_LVAL_P(zv) = ZEND_OPLINE_NUM_TO_OFFSET(op_array, new_opline, ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv)));
743 			} ZEND_HASH_FOREACH_END();
744 			new_opline->extended_value = ZEND_OPLINE_NUM_TO_OFFSET(op_array, new_opline, ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value));
745 			break;
746 		}
747 	}
748 }
749 
750 /* Shift jump offsets based on shiftlist */
zend_optimizer_shift_jump(zend_op_array * op_array,zend_op * opline,uint32_t * shiftlist)751 void zend_optimizer_shift_jump(zend_op_array *op_array, zend_op *opline, uint32_t *shiftlist) {
752 	switch (opline->opcode) {
753 		case ZEND_JMP:
754 		case ZEND_FAST_CALL:
755 			ZEND_SET_OP_JMP_ADDR(opline, opline->op1, ZEND_OP1_JMP_ADDR(opline) - shiftlist[ZEND_OP1_JMP_ADDR(opline) - op_array->opcodes]);
756 			break;
757 		case ZEND_JMPZ:
758 		case ZEND_JMPNZ:
759 		case ZEND_JMPZ_EX:
760 		case ZEND_JMPNZ_EX:
761 		case ZEND_FE_RESET_R:
762 		case ZEND_FE_RESET_RW:
763 		case ZEND_JMP_SET:
764 		case ZEND_COALESCE:
765 		case ZEND_ASSERT_CHECK:
766 		case ZEND_JMP_NULL:
767 		case ZEND_BIND_INIT_STATIC_OR_JMP:
768 		case ZEND_JMP_FRAMELESS:
769 			ZEND_SET_OP_JMP_ADDR(opline, opline->op2, ZEND_OP2_JMP_ADDR(opline) - shiftlist[ZEND_OP2_JMP_ADDR(opline) - op_array->opcodes]);
770 			break;
771 		case ZEND_CATCH:
772 			if (!(opline->extended_value & ZEND_LAST_CATCH)) {
773 				ZEND_SET_OP_JMP_ADDR(opline, opline->op2, ZEND_OP2_JMP_ADDR(opline) - shiftlist[ZEND_OP2_JMP_ADDR(opline) - op_array->opcodes]);
774 			}
775 			break;
776 		case ZEND_FE_FETCH_R:
777 		case ZEND_FE_FETCH_RW:
778 			opline->extended_value = ZEND_OPLINE_NUM_TO_OFFSET(op_array, opline, ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value) - shiftlist[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value)]);
779 			break;
780 		case ZEND_SWITCH_LONG:
781 		case ZEND_SWITCH_STRING:
782 		case ZEND_MATCH:
783 		{
784 			HashTable *jumptable = Z_ARRVAL(ZEND_OP2_LITERAL(opline));
785 			zval *zv;
786 			ZEND_HASH_FOREACH_VAL(jumptable, zv) {
787 				Z_LVAL_P(zv) = ZEND_OPLINE_NUM_TO_OFFSET(op_array, opline, ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv)) - shiftlist[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, Z_LVAL_P(zv))]);
788 			} ZEND_HASH_FOREACH_END();
789 			opline->extended_value = ZEND_OPLINE_NUM_TO_OFFSET(op_array, opline, ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value) - shiftlist[ZEND_OFFSET_TO_OPLINE_NUM(op_array, opline, opline->extended_value)]);
790 			break;
791 		}
792 	}
793 }
794 
zend_optimizer_ignore_class(zval * ce_zv,zend_string * filename)795 static bool zend_optimizer_ignore_class(zval *ce_zv, zend_string *filename)
796 {
797 	zend_class_entry *ce = Z_PTR_P(ce_zv);
798 
799 	if (ce->ce_flags & ZEND_ACC_PRELOADED) {
800 		Bucket *ce_bucket = (Bucket*)((uintptr_t)ce_zv - XtOffsetOf(Bucket, val));
801 		size_t offset = ce_bucket - EG(class_table)->arData;
802 		if (offset < EG(persistent_classes_count)) {
803 			return false;
804 		}
805 	}
806 	return ce->type == ZEND_USER_CLASS
807 		&& (!ce->info.user.filename || ce->info.user.filename != filename);
808 }
809 
zend_optimizer_ignore_function(zval * fbc_zv,zend_string * filename)810 static bool zend_optimizer_ignore_function(zval *fbc_zv, zend_string *filename)
811 {
812 	zend_function *fbc = Z_PTR_P(fbc_zv);
813 
814 	if (fbc->type == ZEND_INTERNAL_FUNCTION) {
815 		return false;
816 	} else if (fbc->type == ZEND_USER_FUNCTION) {
817 		if (fbc->op_array.fn_flags & ZEND_ACC_PRELOADED) {
818 			Bucket *fbc_bucket = (Bucket*)((uintptr_t)fbc_zv - XtOffsetOf(Bucket, val));
819 			size_t offset = fbc_bucket - EG(function_table)->arData;
820 			if (offset < EG(persistent_functions_count)) {
821 				return false;
822 			}
823 		}
824 		return !fbc->op_array.filename || fbc->op_array.filename != filename;
825 	} else {
826 		ZEND_ASSERT(fbc->type == ZEND_EVAL_CODE);
827 		return true;
828 	}
829 }
830 
zend_optimizer_get_class_entry(const zend_script * script,const zend_op_array * op_array,zend_string * lcname)831 zend_class_entry *zend_optimizer_get_class_entry(
832 		const zend_script *script, const zend_op_array *op_array, zend_string *lcname) {
833 	zend_class_entry *ce = script ? zend_hash_find_ptr(&script->class_table, lcname) : NULL;
834 	if (ce) {
835 		return ce;
836 	}
837 
838 	zval *ce_zv = zend_hash_find(CG(class_table), lcname);
839 	if (ce_zv && !zend_optimizer_ignore_class(ce_zv, op_array ? op_array->filename : NULL)) {
840 		return Z_PTR_P(ce_zv);
841 	}
842 
843 	if (op_array && op_array->scope && zend_string_equals_ci(op_array->scope->name, lcname)) {
844 		return op_array->scope;
845 	}
846 
847 	return NULL;
848 }
849 
zend_optimizer_get_class_entry_from_op1(const zend_script * script,const zend_op_array * op_array,const zend_op * opline)850 zend_class_entry *zend_optimizer_get_class_entry_from_op1(
851 		const zend_script *script, const zend_op_array *op_array, const zend_op *opline) {
852 	if (opline->op1_type == IS_CONST) {
853 		zval *op1 = CRT_CONSTANT(opline->op1);
854 		if (Z_TYPE_P(op1) == IS_STRING) {
855 			return zend_optimizer_get_class_entry(script, op_array, Z_STR_P(op1 + 1));
856 		}
857 	} else if (opline->op1_type == IS_UNUSED && op_array->scope
858 			&& !(op_array->scope->ce_flags & ZEND_ACC_TRAIT)
859 			&& ((opline->op1.num & ZEND_FETCH_CLASS_MASK) == ZEND_FETCH_CLASS_SELF
860 				|| ((opline->op1.num & ZEND_FETCH_CLASS_MASK) == ZEND_FETCH_CLASS_STATIC
861 					&& (op_array->scope->ce_flags & ZEND_ACC_FINAL)))) {
862 		return op_array->scope;
863 	}
864 	return NULL;
865 }
866 
zend_fetch_class_const_info(const zend_script * script,const zend_op_array * op_array,const zend_op * opline,bool * is_prototype)867 const zend_class_constant *zend_fetch_class_const_info(
868 	const zend_script *script, const zend_op_array *op_array, const zend_op *opline, bool *is_prototype) {
869 	const zend_class_entry *ce = NULL;
870 	bool is_static_reference = false;
871 
872 	if (!opline || !op_array || opline->op2_type != IS_CONST || Z_TYPE_P(CRT_CONSTANT(opline->op2)) != IS_STRING) {
873 		return NULL;
874 	}
875 	if (opline->op1_type == IS_CONST) {
876 		zval *op1 = CRT_CONSTANT(opline->op1);
877 		if (Z_TYPE_P(op1) == IS_STRING) {
878 			if (script) {
879 				ce = zend_optimizer_get_class_entry(script, op_array, Z_STR_P(op1 + 1));
880 			} else {
881 				zval *ce_zv = zend_hash_find(EG(class_table), Z_STR_P(op1 + 1));
882 				if (ce_zv && !zend_optimizer_ignore_class(ce_zv, op_array->filename)) {
883 					ce = Z_PTR_P(ce_zv);
884 				}
885 			}
886 		}
887 	} else if (opline->op1_type == IS_UNUSED
888 		&& op_array->scope && !(op_array->scope->ce_flags & ZEND_ACC_TRAIT)
889 		&& !(op_array->fn_flags & ZEND_ACC_TRAIT_CLONE)) {
890 		int fetch_type = opline->op1.num & ZEND_FETCH_CLASS_MASK;
891 		if (fetch_type == ZEND_FETCH_CLASS_SELF) {
892 			ce = op_array->scope;
893 		} else if (fetch_type == ZEND_FETCH_CLASS_STATIC) {
894 			ce = op_array->scope;
895 			is_static_reference = true;
896 		} else if (fetch_type == ZEND_FETCH_CLASS_PARENT) {
897 			if (op_array->scope->ce_flags & ZEND_ACC_LINKED) {
898 				ce = op_array->scope->parent;
899 			}
900 		}
901 	}
902 	if (!ce || (ce->ce_flags & ZEND_ACC_TRAIT)) {
903 		return NULL;
904 	}
905 	zend_class_constant *const_info = zend_hash_find_ptr(&ce->constants_table, Z_STR_P(CRT_CONSTANT(opline->op2)));
906 	if (!const_info) {
907 		return NULL;
908 	}
909 	if ((ZEND_CLASS_CONST_FLAGS(const_info) & ZEND_ACC_DEPRECATED)
910 		|| ((ZEND_CLASS_CONST_FLAGS(const_info) & ZEND_ACC_PPP_MASK) != ZEND_ACC_PUBLIC && const_info->ce != op_array->scope)) {
911 		return NULL;
912 	}
913 	*is_prototype = is_static_reference
914 		&& !(const_info->ce->ce_flags & ZEND_ACC_FINAL) && !(ZEND_CLASS_CONST_FLAGS(const_info) & ZEND_ACC_FINAL);
915 
916 	return const_info;
917 }
918 
zend_optimizer_get_called_func(zend_script * script,zend_op_array * op_array,zend_op * opline,bool * is_prototype)919 zend_function *zend_optimizer_get_called_func(
920 		zend_script *script, zend_op_array *op_array, zend_op *opline, bool *is_prototype)
921 {
922 	*is_prototype = 0;
923 	switch (opline->opcode) {
924 		case ZEND_INIT_FCALL:
925 		{
926 			zend_string *function_name = Z_STR_P(CRT_CONSTANT(opline->op2));
927 			zend_function *func;
928 			zval *func_zv;
929 			if (script && (func = zend_hash_find_ptr(&script->function_table, function_name)) != NULL) {
930 				return func;
931 			} else if ((func_zv = zend_hash_find(EG(function_table), function_name)) != NULL) {
932 				if (!zend_optimizer_ignore_function(func_zv, op_array->filename)) {
933 					return Z_PTR_P(func_zv);
934 				}
935 			}
936 			break;
937 		}
938 		case ZEND_INIT_FCALL_BY_NAME:
939 		case ZEND_INIT_NS_FCALL_BY_NAME:
940 			if (opline->op2_type == IS_CONST && Z_TYPE_P(CRT_CONSTANT(opline->op2)) == IS_STRING) {
941 				zval *function_name = CRT_CONSTANT(opline->op2) + 1;
942 				zend_function *func;
943 				zval *func_zv;
944 				if (script && (func = zend_hash_find_ptr(&script->function_table, Z_STR_P(function_name)))) {
945 					return func;
946 				} else if ((func_zv = zend_hash_find(EG(function_table), Z_STR_P(function_name))) != NULL) {
947 					if (!zend_optimizer_ignore_function(func_zv, op_array->filename)) {
948 						return Z_PTR_P(func_zv);
949 					}
950 				}
951 			}
952 			break;
953 		case ZEND_INIT_STATIC_METHOD_CALL:
954 			if (opline->op2_type == IS_CONST && Z_TYPE_P(CRT_CONSTANT(opline->op2)) == IS_STRING) {
955 				zend_class_entry *ce = zend_optimizer_get_class_entry_from_op1(
956 					script, op_array, opline);
957 				if (ce) {
958 					zend_string *func_name = Z_STR_P(CRT_CONSTANT(opline->op2) + 1);
959 					zend_function *fbc = zend_hash_find_ptr(&ce->function_table, func_name);
960 					if (fbc) {
961 						bool is_public = (fbc->common.fn_flags & ZEND_ACC_PUBLIC) != 0;
962 						bool same_scope = fbc->common.scope == op_array->scope;
963 						if (is_public || same_scope) {
964 							return fbc;
965 						}
966 					}
967 				}
968 			}
969 			break;
970 		case ZEND_INIT_METHOD_CALL:
971 			if (opline->op1_type == IS_UNUSED
972 					&& opline->op2_type == IS_CONST && Z_TYPE_P(CRT_CONSTANT(opline->op2)) == IS_STRING
973 					&& op_array->scope
974 					&& !(op_array->fn_flags & ZEND_ACC_TRAIT_CLONE)
975 					&& !(op_array->scope->ce_flags & ZEND_ACC_TRAIT)) {
976 				zend_string *method_name = Z_STR_P(CRT_CONSTANT(opline->op2) + 1);
977 				zend_function *fbc = zend_hash_find_ptr(
978 					&op_array->scope->function_table, method_name);
979 				if (fbc) {
980 					bool is_private = (fbc->common.fn_flags & ZEND_ACC_PRIVATE) != 0;
981 					if (is_private) {
982 						/* Only use private method if in the same scope. We can't even use it
983 						 * as a prototype, as it may be overridden with changed signature. */
984 						bool same_scope = fbc->common.scope == op_array->scope;
985 						return same_scope ? fbc : NULL;
986 					}
987 					/* Prototype methods are potentially overridden. fbc still contains useful type information.
988 					 * Some optimizations may not be applied, like inlining or inferring the send-mode of superfluous args.
989 					 * A method cannot be overridden if the class or method is final. */
990 					if ((fbc->common.fn_flags & ZEND_ACC_FINAL) == 0 &&
991 						(fbc->common.scope->ce_flags & ZEND_ACC_FINAL) == 0) {
992 						*is_prototype = true;
993 					}
994 					return fbc;
995 				}
996 			}
997 			break;
998 		case ZEND_INIT_PARENT_PROPERTY_HOOK_CALL: {
999 			zend_class_entry *scope = op_array->scope;
1000 			ZEND_ASSERT(scope != NULL);
1001 			if ((scope->ce_flags & ZEND_ACC_LINKED) && scope->parent) {
1002 				zend_class_entry *parent_scope = scope->parent;
1003 				zend_string *prop_name = Z_STR_P(CRT_CONSTANT(opline->op1));
1004 				zend_property_hook_kind hook_kind = opline->op2.num;
1005 				zend_property_info *prop_info = zend_get_property_info(parent_scope, prop_name, /* silent */ true);
1006 
1007 				if (prop_info
1008 					&& prop_info != ZEND_WRONG_PROPERTY_INFO
1009 					&& !(prop_info->flags & ZEND_ACC_PRIVATE)
1010 					&& prop_info->hooks) {
1011 					zend_function *fbc = prop_info->hooks[hook_kind];
1012 					if (fbc) {
1013 						*is_prototype = false;
1014 						return fbc;
1015 					}
1016 				}
1017 			}
1018 			break;
1019 		}
1020 		case ZEND_NEW:
1021 		{
1022 			zend_class_entry *ce = zend_optimizer_get_class_entry_from_op1(
1023 				script, op_array, opline);
1024 			if (ce && ce->type == ZEND_USER_CLASS) {
1025 				return ce->constructor;
1026 			}
1027 			break;
1028 		}
1029 	}
1030 	return NULL;
1031 }
1032 
zend_optimizer_classify_function(zend_string * name,uint32_t num_args)1033 uint32_t zend_optimizer_classify_function(zend_string *name, uint32_t num_args) {
1034 	if (zend_string_equals_literal(name, "extract")) {
1035 		return ZEND_FUNC_INDIRECT_VAR_ACCESS;
1036 	} else if (zend_string_equals_literal(name, "compact")) {
1037 		return ZEND_FUNC_INDIRECT_VAR_ACCESS;
1038 	} else if (zend_string_equals_literal(name, "get_defined_vars")) {
1039 		return ZEND_FUNC_INDIRECT_VAR_ACCESS;
1040 	} else if (zend_string_equals_literal(name, "db2_execute")) {
1041 		return ZEND_FUNC_INDIRECT_VAR_ACCESS;
1042 	} else if (zend_string_equals_literal(name, "func_num_args")) {
1043 		return ZEND_FUNC_VARARG;
1044 	} else if (zend_string_equals_literal(name, "func_get_arg")) {
1045 		return ZEND_FUNC_VARARG;
1046 	} else if (zend_string_equals_literal(name, "func_get_args")) {
1047 		return ZEND_FUNC_VARARG;
1048 	} else {
1049 		return 0;
1050 	}
1051 }
1052 
zend_optimizer_get_loop_var_def(const zend_op_array * op_array,zend_op * free_opline)1053 zend_op *zend_optimizer_get_loop_var_def(const zend_op_array *op_array, zend_op *free_opline) {
1054 	uint32_t var = free_opline->op1.var;
1055 	ZEND_ASSERT(zend_optimizer_is_loop_var_free(free_opline));
1056 
1057 	while (--free_opline >= op_array->opcodes) {
1058 		if ((free_opline->result_type & (IS_TMP_VAR|IS_VAR)) && free_opline->result.var == var) {
1059 			return free_opline;
1060 		}
1061 	}
1062 	return NULL;
1063 }
1064 
zend_optimize(zend_op_array * op_array,zend_optimizer_ctx * ctx)1065 static void zend_optimize(zend_op_array      *op_array,
1066                           zend_optimizer_ctx *ctx)
1067 {
1068 	if (op_array->type == ZEND_EVAL_CODE) {
1069 		return;
1070 	}
1071 
1072 	if (ctx->debug_level & ZEND_DUMP_BEFORE_OPTIMIZER) {
1073 		zend_dump_op_array(op_array, ZEND_DUMP_LIVE_RANGES, "before optimizer", NULL);
1074 	}
1075 
1076 	/* pass 1 (Simple local optimizations)
1077 	 * - persistent constant substitution (true, false, null, etc)
1078 	 * - constant casting (ADD expects numbers, CONCAT strings, etc)
1079 	 * - constant expression evaluation
1080 	 * - optimize constant conditional JMPs
1081 	 * - pre-evaluate constant function calls
1082 	 * - eliminate FETCH $GLOBALS followed by FETCH_DIM/UNSET_DIM/ISSET_ISEMPTY_DIM
1083 	 */
1084 	if (ZEND_OPTIMIZER_PASS_1 & ctx->optimization_level) {
1085 		zend_optimizer_pass1(op_array, ctx);
1086 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_1) {
1087 			zend_dump_op_array(op_array, 0, "after pass 1", NULL);
1088 		}
1089 	}
1090 
1091 	/* pass 3: (Jump optimization)
1092 	 * - optimize series of JMPs
1093 	 */
1094 	if (ZEND_OPTIMIZER_PASS_3 & ctx->optimization_level) {
1095 		zend_optimizer_pass3(op_array, ctx);
1096 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_3) {
1097 			zend_dump_op_array(op_array, 0, "after pass 3", NULL);
1098 		}
1099 	}
1100 
1101 	/* pass 4:
1102 	 * - INIT_FCALL_BY_NAME -> DO_FCALL
1103 	 */
1104 	if (ZEND_OPTIMIZER_PASS_4 & ctx->optimization_level) {
1105 		zend_optimize_func_calls(op_array, ctx);
1106 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_4) {
1107 			zend_dump_op_array(op_array, 0, "after pass 4", NULL);
1108 		}
1109 	}
1110 
1111 	/* pass 5:
1112 	 * - CFG optimization
1113 	 */
1114 	if (ZEND_OPTIMIZER_PASS_5 & ctx->optimization_level) {
1115 		zend_optimize_cfg(op_array, ctx);
1116 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_5) {
1117 			zend_dump_op_array(op_array, 0, "after pass 5", NULL);
1118 		}
1119 	}
1120 
1121 	/* pass 6:
1122 	 * - DFA optimization
1123 	 */
1124 	if ((ZEND_OPTIMIZER_PASS_6 & ctx->optimization_level) &&
1125 	    !(ZEND_OPTIMIZER_PASS_7 & ctx->optimization_level)) {
1126 		zend_optimize_dfa(op_array, ctx);
1127 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_6) {
1128 			zend_dump_op_array(op_array, 0, "after pass 6", NULL);
1129 		}
1130 	}
1131 
1132 	/* pass 9:
1133 	 * - Optimize temp variables usage
1134 	 */
1135 	if ((ZEND_OPTIMIZER_PASS_9 & ctx->optimization_level) &&
1136 	    !(ZEND_OPTIMIZER_PASS_7 & ctx->optimization_level)) {
1137 		zend_optimize_temporary_variables(op_array, ctx);
1138 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_9) {
1139 			zend_dump_op_array(op_array, 0, "after pass 9", NULL);
1140 		}
1141 	}
1142 
1143 	/* pass 10:
1144 	 * - remove NOPs
1145 	 */
1146 	if (((ZEND_OPTIMIZER_PASS_10|ZEND_OPTIMIZER_PASS_5) & ctx->optimization_level) == ZEND_OPTIMIZER_PASS_10) {
1147 		zend_optimizer_nop_removal(op_array, ctx);
1148 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_10) {
1149 			zend_dump_op_array(op_array, 0, "after pass 10", NULL);
1150 		}
1151 	}
1152 
1153 	/* pass 11:
1154 	 * - Compact literals table
1155 	 */
1156 	if ((ZEND_OPTIMIZER_PASS_11 & ctx->optimization_level) &&
1157 	    (!(ZEND_OPTIMIZER_PASS_6 & ctx->optimization_level) ||
1158 	     !(ZEND_OPTIMIZER_PASS_7 & ctx->optimization_level))) {
1159 		zend_optimizer_compact_literals(op_array, ctx);
1160 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_11) {
1161 			zend_dump_op_array(op_array, 0, "after pass 11", NULL);
1162 		}
1163 	}
1164 
1165 	if ((ZEND_OPTIMIZER_PASS_13 & ctx->optimization_level) &&
1166 	    (!(ZEND_OPTIMIZER_PASS_6 & ctx->optimization_level) ||
1167 	     !(ZEND_OPTIMIZER_PASS_7 & ctx->optimization_level))) {
1168 		zend_optimizer_compact_vars(op_array);
1169 		if (ctx->debug_level & ZEND_DUMP_AFTER_PASS_13) {
1170 			zend_dump_op_array(op_array, 0, "after pass 13", NULL);
1171 		}
1172 	}
1173 
1174 	if (ZEND_OPTIMIZER_PASS_7 & ctx->optimization_level) {
1175 		return;
1176 	}
1177 
1178 	if (ctx->debug_level & ZEND_DUMP_AFTER_OPTIMIZER) {
1179 		zend_dump_op_array(op_array, 0, "after optimizer", NULL);
1180 	}
1181 }
1182 
zend_revert_pass_two(zend_op_array * op_array)1183 static void zend_revert_pass_two(zend_op_array *op_array)
1184 {
1185 	zend_op *opline, *end;
1186 
1187 	ZEND_ASSERT((op_array->fn_flags & ZEND_ACC_DONE_PASS_TWO) != 0);
1188 
1189 	opline = op_array->opcodes;
1190 	end = opline + op_array->last;
1191 	while (opline < end) {
1192 		if (opline->op1_type == IS_CONST) {
1193 			ZEND_PASS_TWO_UNDO_CONSTANT(op_array, opline, opline->op1);
1194 		}
1195 		if (opline->op2_type == IS_CONST) {
1196 			ZEND_PASS_TWO_UNDO_CONSTANT(op_array, opline, opline->op2);
1197 		}
1198 		/* reset smart branch flags IS_SMART_BRANCH_JMP[N]Z */
1199 		opline->result_type &= (IS_TMP_VAR|IS_VAR|IS_CV|IS_CONST);
1200 		opline++;
1201 	}
1202 #if !ZEND_USE_ABS_CONST_ADDR
1203 	if (op_array->literals) {
1204 		zval *literals = emalloc(sizeof(zval) * op_array->last_literal);
1205 		memcpy(literals, op_array->literals, sizeof(zval) * op_array->last_literal);
1206 		op_array->literals = literals;
1207 	}
1208 #endif
1209 
1210 	op_array->fn_flags &= ~ZEND_ACC_DONE_PASS_TWO;
1211 }
1212 
zend_redo_pass_two(zend_op_array * op_array)1213 static void zend_redo_pass_two(zend_op_array *op_array)
1214 {
1215 	zend_op *opline, *end;
1216 #if ZEND_USE_ABS_JMP_ADDR && !ZEND_USE_ABS_CONST_ADDR
1217 	zend_op *old_opcodes = op_array->opcodes;
1218 #endif
1219 
1220 	ZEND_ASSERT((op_array->fn_flags & ZEND_ACC_DONE_PASS_TWO) == 0);
1221 
1222 #if !ZEND_USE_ABS_CONST_ADDR
1223 	if (op_array->last_literal) {
1224 		op_array->opcodes = (zend_op *) erealloc(op_array->opcodes,
1225 			ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op) * op_array->last, 16) +
1226 			sizeof(zval) * op_array->last_literal);
1227 		memcpy(((char*)op_array->opcodes) + ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op) * op_array->last, 16),
1228 			op_array->literals, sizeof(zval) * op_array->last_literal);
1229 		efree(op_array->literals);
1230 		op_array->literals = (zval*)(((char*)op_array->opcodes) + ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op) * op_array->last, 16));
1231 	} else {
1232 		if (op_array->literals) {
1233 			efree(op_array->literals);
1234 		}
1235 		op_array->literals = NULL;
1236 	}
1237 #endif
1238 
1239 	opline = op_array->opcodes;
1240 	end = opline + op_array->last;
1241 	while (opline < end) {
1242 		if (opline->op1_type == IS_CONST) {
1243 			ZEND_PASS_TWO_UPDATE_CONSTANT(op_array, opline, opline->op1);
1244 		}
1245 		if (opline->op2_type == IS_CONST) {
1246 			ZEND_PASS_TWO_UPDATE_CONSTANT(op_array, opline, opline->op2);
1247 		}
1248 		/* fix jumps to point to new array */
1249 		switch (opline->opcode) {
1250 #if ZEND_USE_ABS_JMP_ADDR && !ZEND_USE_ABS_CONST_ADDR
1251 			case ZEND_JMP:
1252 			case ZEND_FAST_CALL:
1253 				opline->op1.jmp_addr = &op_array->opcodes[opline->op1.jmp_addr - old_opcodes];
1254 				break;
1255 			case ZEND_JMPZ:
1256 			case ZEND_JMPNZ:
1257 			case ZEND_JMPZ_EX:
1258 			case ZEND_JMPNZ_EX:
1259 			case ZEND_JMP_SET:
1260 			case ZEND_COALESCE:
1261 			case ZEND_FE_RESET_R:
1262 			case ZEND_FE_RESET_RW:
1263 			case ZEND_ASSERT_CHECK:
1264 			case ZEND_JMP_NULL:
1265 			case ZEND_BIND_INIT_STATIC_OR_JMP:
1266 			case ZEND_JMP_FRAMELESS:
1267 				opline->op2.jmp_addr = &op_array->opcodes[opline->op2.jmp_addr - old_opcodes];
1268 				break;
1269 			case ZEND_CATCH:
1270 				if (!(opline->extended_value & ZEND_LAST_CATCH)) {
1271 					opline->op2.jmp_addr = &op_array->opcodes[opline->op2.jmp_addr - old_opcodes];
1272 				}
1273 				break;
1274 			case ZEND_FE_FETCH_R:
1275 			case ZEND_FE_FETCH_RW:
1276 			case ZEND_SWITCH_LONG:
1277 			case ZEND_SWITCH_STRING:
1278 			case ZEND_MATCH:
1279 				/* relative extended_value don't have to be changed */
1280 				break;
1281 #endif
1282 			case ZEND_IS_IDENTICAL:
1283 			case ZEND_IS_NOT_IDENTICAL:
1284 			case ZEND_IS_EQUAL:
1285 			case ZEND_IS_NOT_EQUAL:
1286 			case ZEND_IS_SMALLER:
1287 			case ZEND_IS_SMALLER_OR_EQUAL:
1288 			case ZEND_CASE:
1289 			case ZEND_CASE_STRICT:
1290 			case ZEND_ISSET_ISEMPTY_CV:
1291 			case ZEND_ISSET_ISEMPTY_VAR:
1292 			case ZEND_ISSET_ISEMPTY_DIM_OBJ:
1293 			case ZEND_ISSET_ISEMPTY_PROP_OBJ:
1294 			case ZEND_ISSET_ISEMPTY_STATIC_PROP:
1295 			case ZEND_INSTANCEOF:
1296 			case ZEND_TYPE_CHECK:
1297 			case ZEND_DEFINED:
1298 			case ZEND_IN_ARRAY:
1299 			case ZEND_ARRAY_KEY_EXISTS:
1300 				if (opline->result_type & IS_TMP_VAR) {
1301 					/* reinitialize result_type of smart branch instructions */
1302 					if (opline + 1 < end) {
1303 						if ((opline+1)->opcode == ZEND_JMPZ
1304 						 && (opline+1)->op1_type == IS_TMP_VAR
1305 						 && (opline+1)->op1.var == opline->result.var) {
1306 							opline->result_type = IS_SMART_BRANCH_JMPZ | IS_TMP_VAR;
1307 						} else if ((opline+1)->opcode == ZEND_JMPNZ
1308 						 && (opline+1)->op1_type == IS_TMP_VAR
1309 						 && (opline+1)->op1.var == opline->result.var) {
1310 							opline->result_type = IS_SMART_BRANCH_JMPNZ | IS_TMP_VAR;
1311 						}
1312 					}
1313 				}
1314 				break;
1315 		}
1316 		ZEND_VM_SET_OPCODE_HANDLER(opline);
1317 		opline++;
1318 	}
1319 
1320 	op_array->fn_flags |= ZEND_ACC_DONE_PASS_TWO;
1321 }
1322 
zend_redo_pass_two_ex(zend_op_array * op_array,zend_ssa * ssa)1323 static void zend_redo_pass_two_ex(zend_op_array *op_array, zend_ssa *ssa)
1324 {
1325 	zend_op *opline, *end;
1326 #if ZEND_USE_ABS_JMP_ADDR && !ZEND_USE_ABS_CONST_ADDR
1327 	zend_op *old_opcodes = op_array->opcodes;
1328 #endif
1329 
1330 	ZEND_ASSERT((op_array->fn_flags & ZEND_ACC_DONE_PASS_TWO) == 0);
1331 
1332 #if !ZEND_USE_ABS_CONST_ADDR
1333 	if (op_array->last_literal) {
1334 		op_array->opcodes = (zend_op *) erealloc(op_array->opcodes,
1335 			ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op) * op_array->last, 16) +
1336 			sizeof(zval) * op_array->last_literal);
1337 		memcpy(((char*)op_array->opcodes) + ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op) * op_array->last, 16),
1338 			op_array->literals, sizeof(zval) * op_array->last_literal);
1339 		efree(op_array->literals);
1340 		op_array->literals = (zval*)(((char*)op_array->opcodes) + ZEND_MM_ALIGNED_SIZE_EX(sizeof(zend_op) * op_array->last, 16));
1341 	} else {
1342 		if (op_array->literals) {
1343 			efree(op_array->literals);
1344 		}
1345 		op_array->literals = NULL;
1346 	}
1347 #endif
1348 
1349 	opline = op_array->opcodes;
1350 	end = opline + op_array->last;
1351 	while (opline < end) {
1352 		zend_ssa_op *ssa_op = &ssa->ops[opline - op_array->opcodes];
1353 		uint32_t op1_info = opline->op1_type == IS_UNUSED ? 0 : (OP1_INFO() & (MAY_BE_UNDEF|MAY_BE_ANY|MAY_BE_REF|MAY_BE_ARRAY_OF_ANY|MAY_BE_ARRAY_KEY_ANY));
1354 		uint32_t op2_info = opline->op1_type == IS_UNUSED ? 0 : (OP2_INFO() & (MAY_BE_UNDEF|MAY_BE_ANY|MAY_BE_REF|MAY_BE_ARRAY_OF_ANY|MAY_BE_ARRAY_KEY_ANY));
1355 		uint32_t res_info =
1356 			(opline->opcode == ZEND_PRE_INC ||
1357 			 opline->opcode == ZEND_PRE_DEC ||
1358 			 opline->opcode == ZEND_POST_INC ||
1359 			 opline->opcode == ZEND_POST_DEC) ?
1360 				((ssa->ops[opline - op_array->opcodes].op1_def >= 0) ? (OP1_DEF_INFO() & (MAY_BE_UNDEF|MAY_BE_ANY|MAY_BE_REF|MAY_BE_ARRAY_OF_ANY|MAY_BE_ARRAY_KEY_ANY)) : MAY_BE_ANY) :
1361 				(opline->result_type == IS_UNUSED ? 0 : (RES_INFO() & (MAY_BE_UNDEF|MAY_BE_ANY|MAY_BE_REF|MAY_BE_ARRAY_OF_ANY|MAY_BE_ARRAY_KEY_ANY)));
1362 
1363 		if (opline->op1_type == IS_CONST) {
1364 			ZEND_PASS_TWO_UPDATE_CONSTANT(op_array, opline, opline->op1);
1365 		}
1366 		if (opline->op2_type == IS_CONST) {
1367 			ZEND_PASS_TWO_UPDATE_CONSTANT(op_array, opline, opline->op2);
1368 		}
1369 
1370 		/* fix jumps to point to new array */
1371 		switch (opline->opcode) {
1372 #if ZEND_USE_ABS_JMP_ADDR && !ZEND_USE_ABS_CONST_ADDR
1373 			case ZEND_JMP:
1374 			case ZEND_FAST_CALL:
1375 				opline->op1.jmp_addr = &op_array->opcodes[opline->op1.jmp_addr - old_opcodes];
1376 				break;
1377 			case ZEND_JMPZ:
1378 			case ZEND_JMPNZ:
1379 			case ZEND_JMPZ_EX:
1380 			case ZEND_JMPNZ_EX:
1381 			case ZEND_JMP_SET:
1382 			case ZEND_COALESCE:
1383 			case ZEND_FE_RESET_R:
1384 			case ZEND_FE_RESET_RW:
1385 			case ZEND_ASSERT_CHECK:
1386 			case ZEND_JMP_NULL:
1387 			case ZEND_BIND_INIT_STATIC_OR_JMP:
1388 			case ZEND_JMP_FRAMELESS:
1389 				opline->op2.jmp_addr = &op_array->opcodes[opline->op2.jmp_addr - old_opcodes];
1390 				break;
1391 			case ZEND_CATCH:
1392 				if (!(opline->extended_value & ZEND_LAST_CATCH)) {
1393 					opline->op2.jmp_addr = &op_array->opcodes[opline->op2.jmp_addr - old_opcodes];
1394 				}
1395 				break;
1396 			case ZEND_FE_FETCH_R:
1397 			case ZEND_FE_FETCH_RW:
1398 			case ZEND_SWITCH_LONG:
1399 			case ZEND_SWITCH_STRING:
1400 			case ZEND_MATCH:
1401 				/* relative extended_value don't have to be changed */
1402 				break;
1403 #endif
1404 			case ZEND_IS_IDENTICAL:
1405 			case ZEND_IS_NOT_IDENTICAL:
1406 			case ZEND_IS_EQUAL:
1407 			case ZEND_IS_NOT_EQUAL:
1408 			case ZEND_IS_SMALLER:
1409 			case ZEND_IS_SMALLER_OR_EQUAL:
1410 			case ZEND_CASE:
1411 			case ZEND_CASE_STRICT:
1412 			case ZEND_ISSET_ISEMPTY_CV:
1413 			case ZEND_ISSET_ISEMPTY_VAR:
1414 			case ZEND_ISSET_ISEMPTY_DIM_OBJ:
1415 			case ZEND_ISSET_ISEMPTY_PROP_OBJ:
1416 			case ZEND_ISSET_ISEMPTY_STATIC_PROP:
1417 			case ZEND_INSTANCEOF:
1418 			case ZEND_TYPE_CHECK:
1419 			case ZEND_DEFINED:
1420 			case ZEND_IN_ARRAY:
1421 			case ZEND_ARRAY_KEY_EXISTS:
1422 				if (opline->result_type & IS_TMP_VAR) {
1423 					/* reinitialize result_type of smart branch instructions */
1424 					if (opline + 1 < end) {
1425 						if ((opline+1)->opcode == ZEND_JMPZ
1426 						 && (opline+1)->op1_type == IS_TMP_VAR
1427 						 && (opline+1)->op1.var == opline->result.var) {
1428 							opline->result_type = IS_SMART_BRANCH_JMPZ | IS_TMP_VAR;
1429 						} else if ((opline+1)->opcode == ZEND_JMPNZ
1430 						 && (opline+1)->op1_type == IS_TMP_VAR
1431 						 && (opline+1)->op1.var == opline->result.var) {
1432 							opline->result_type = IS_SMART_BRANCH_JMPNZ | IS_TMP_VAR;
1433 						}
1434 					}
1435 				}
1436 				break;
1437 		}
1438 #ifdef ZEND_VERIFY_TYPE_INFERENCE
1439 		if (ssa_op->op1_use >= 0) {
1440 			opline->op1_use_type = ssa->var_info[ssa_op->op1_use].type;
1441 		}
1442 		if (ssa_op->op2_use >= 0) {
1443 			opline->op2_use_type = ssa->var_info[ssa_op->op2_use].type;
1444 		}
1445 		if (ssa_op->result_use >= 0) {
1446 			opline->result_use_type = ssa->var_info[ssa_op->result_use].type;
1447 		}
1448 		if (ssa_op->op1_def >= 0) {
1449 			opline->op1_def_type = ssa->var_info[ssa_op->op1_def].type;
1450 		}
1451 		if (ssa_op->op2_def >= 0) {
1452 			opline->op2_def_type = ssa->var_info[ssa_op->op2_def].type;
1453 		}
1454 		if (ssa_op->result_def >= 0) {
1455 			opline->result_def_type = ssa->var_info[ssa_op->result_def].type;
1456 		}
1457 #endif
1458 		zend_vm_set_opcode_handler_ex(opline, op1_info, op2_info, res_info);
1459 		opline++;
1460 	}
1461 
1462 	op_array->fn_flags |= ZEND_ACC_DONE_PASS_TWO;
1463 }
1464 
zend_optimize_op_array(zend_op_array * op_array,zend_optimizer_ctx * ctx)1465 static void zend_optimize_op_array(zend_op_array      *op_array,
1466                                    zend_optimizer_ctx *ctx)
1467 {
1468 	/* Revert pass_two() */
1469 	zend_revert_pass_two(op_array);
1470 
1471 	/* Do actual optimizations */
1472 	zend_optimize(op_array, ctx);
1473 
1474 	/* Redo pass_two() */
1475 	zend_redo_pass_two(op_array);
1476 
1477 	if (op_array->live_range) {
1478 		zend_recalc_live_ranges(op_array, NULL);
1479 	}
1480 }
1481 
zend_adjust_fcall_stack_size(zend_op_array * op_array,zend_optimizer_ctx * ctx)1482 static void zend_adjust_fcall_stack_size(zend_op_array *op_array, zend_optimizer_ctx *ctx)
1483 {
1484 	zend_function *func;
1485 	zend_op *opline, *end;
1486 
1487 	opline = op_array->opcodes;
1488 	end = opline + op_array->last;
1489 	while (opline < end) {
1490 		if (opline->opcode == ZEND_INIT_FCALL) {
1491 			func = zend_hash_find_ptr(
1492 				&ctx->script->function_table,
1493 				Z_STR_P(RT_CONSTANT(opline, opline->op2)));
1494 			if (func) {
1495 				opline->op1.num = zend_vm_calc_used_stack(opline->extended_value, func);
1496 			}
1497 		}
1498 		opline++;
1499 	}
1500 }
1501 
zend_adjust_fcall_stack_size_graph(zend_op_array * op_array)1502 static void zend_adjust_fcall_stack_size_graph(zend_op_array *op_array)
1503 {
1504 	zend_func_info *func_info = ZEND_FUNC_INFO(op_array);
1505 
1506 	if (func_info) {
1507 		zend_call_info *call_info =func_info->callee_info;
1508 
1509 		while (call_info) {
1510 			zend_op *opline = call_info->caller_init_opline;
1511 
1512 			if (opline && call_info->callee_func && opline->opcode == ZEND_INIT_FCALL) {
1513 				ZEND_ASSERT(!call_info->is_prototype);
1514 				opline->op1.num = zend_vm_calc_used_stack(opline->extended_value, call_info->callee_func);
1515 			}
1516 			call_info = call_info->next_callee;
1517 		}
1518 	}
1519 }
1520 
needs_live_range(zend_op_array * op_array,zend_op * def_opline)1521 static bool needs_live_range(zend_op_array *op_array, zend_op *def_opline) {
1522 	zend_func_info *func_info = ZEND_FUNC_INFO(op_array);
1523 	zend_ssa_op *ssa_op = &func_info->ssa.ops[def_opline - op_array->opcodes];
1524 	int ssa_var = ssa_op->result_def;
1525 	if (ssa_var < 0) {
1526 		/* Be conservative. */
1527 		return 1;
1528 	}
1529 
1530 	/* If the variable is used by a PHI, this may be the assignment of the final branch of a
1531 	 * ternary/etc structure. While this is where the live range starts, the value from the other
1532 	 * branch may also be used. As such, use the type of the PHI node for the following check. */
1533 	if (func_info->ssa.vars[ssa_var].phi_use_chain) {
1534 		ssa_var = func_info->ssa.vars[ssa_var].phi_use_chain->ssa_var;
1535 	}
1536 
1537 	uint32_t type = func_info->ssa.var_info[ssa_var].type;
1538 	return (type & (MAY_BE_STRING|MAY_BE_ARRAY|MAY_BE_OBJECT|MAY_BE_RESOURCE|MAY_BE_REF)) != 0;
1539 }
1540 
zend_foreach_op_array_helper(zend_op_array * op_array,zend_op_array_func_t func,void * context)1541 static void zend_foreach_op_array_helper(
1542 		zend_op_array *op_array, zend_op_array_func_t func, void *context) {
1543 	func(op_array, context);
1544 	for (uint32_t i = 0; i < op_array->num_dynamic_func_defs; i++) {
1545 		zend_foreach_op_array_helper(op_array->dynamic_func_defs[i], func, context);
1546 	}
1547 }
1548 
zend_foreach_op_array(zend_script * script,zend_op_array_func_t func,void * context)1549 void zend_foreach_op_array(zend_script *script, zend_op_array_func_t func, void *context)
1550 {
1551 	zval *zv;
1552 	zend_op_array *op_array;
1553 
1554 	zend_foreach_op_array_helper(&script->main_op_array, func, context);
1555 
1556 	ZEND_HASH_MAP_FOREACH_PTR(&script->function_table, op_array) {
1557 		zend_foreach_op_array_helper(op_array, func, context);
1558 	} ZEND_HASH_FOREACH_END();
1559 
1560 	ZEND_HASH_MAP_FOREACH_VAL(&script->class_table, zv) {
1561 		if (Z_TYPE_P(zv) == IS_ALIAS_PTR) {
1562 			continue;
1563 		}
1564 		zend_class_entry *ce = Z_CE_P(zv);
1565 		ZEND_HASH_MAP_FOREACH_PTR(&ce->function_table, op_array) {
1566 			if (op_array->scope == ce
1567 					&& op_array->type == ZEND_USER_FUNCTION
1568 					&& !(op_array->fn_flags & ZEND_ACC_ABSTRACT)
1569 					&& !(op_array->fn_flags & ZEND_ACC_TRAIT_CLONE)) {
1570 				zend_foreach_op_array_helper(op_array, func, context);
1571 			}
1572 		} ZEND_HASH_FOREACH_END();
1573 
1574 		zend_property_info *property;
1575 		ZEND_HASH_MAP_FOREACH_PTR(&ce->properties_info, property) {
1576 			zend_function **hooks = property->hooks;
1577 			if (property->ce == ce && property->hooks) {
1578 				for (uint32_t i = 0; i < ZEND_PROPERTY_HOOK_COUNT; i++) {
1579 					zend_function *hook = hooks[i];
1580 					if (hook && hook->common.scope == ce) {
1581 						zend_foreach_op_array_helper(&hooks[i]->op_array, func, context);
1582 					}
1583 				}
1584 			}
1585 		} ZEND_HASH_FOREACH_END();
1586 	} ZEND_HASH_FOREACH_END();
1587 }
1588 
step_optimize_op_array(zend_op_array * op_array,void * context)1589 static void step_optimize_op_array(zend_op_array *op_array, void *context) {
1590 	zend_optimize_op_array(op_array, (zend_optimizer_ctx *) context);
1591 }
1592 
step_adjust_fcall_stack_size(zend_op_array * op_array,void * context)1593 static void step_adjust_fcall_stack_size(zend_op_array *op_array, void *context) {
1594 	zend_adjust_fcall_stack_size(op_array, (zend_optimizer_ctx *) context);
1595 }
1596 
step_dump_after_optimizer(zend_op_array * op_array,void * context)1597 static void step_dump_after_optimizer(zend_op_array *op_array, void *context) {
1598 	zend_dump_op_array(op_array, ZEND_DUMP_LIVE_RANGES, "after optimizer", NULL);
1599 }
1600 
zend_optimizer_call_registered_passes(zend_script * script,void * ctx)1601 static void zend_optimizer_call_registered_passes(zend_script *script, void *ctx) {
1602 	for (int i = 0; i < zend_optimizer_registered_passes.last; i++) {
1603 		if (!zend_optimizer_registered_passes.pass[i]) {
1604 			continue;
1605 		}
1606 
1607 		zend_optimizer_registered_passes.pass[i](script, ctx);
1608 	}
1609 }
1610 
zend_optimize_script(zend_script * script,zend_long optimization_level,zend_long debug_level)1611 ZEND_API void zend_optimize_script(zend_script *script, zend_long optimization_level, zend_long debug_level)
1612 {
1613 	zend_op_array *op_array;
1614 	zend_string *name;
1615 	zend_optimizer_ctx ctx;
1616 	zval *zv;
1617 
1618 	ctx.arena = zend_arena_create(64 * 1024);
1619 	ctx.script = script;
1620 	ctx.constants = NULL;
1621 	ctx.optimization_level = optimization_level;
1622 	ctx.debug_level = debug_level;
1623 
1624 	if ((ZEND_OPTIMIZER_PASS_6 & optimization_level) &&
1625 	    (ZEND_OPTIMIZER_PASS_7 & optimization_level)) {
1626 		/* Optimize using call-graph */
1627 		zend_call_graph call_graph;
1628 		zend_build_call_graph(&ctx.arena, script, &call_graph);
1629 
1630 		int i;
1631 		zend_func_info *func_info;
1632 
1633 		for (i = 0; i < call_graph.op_arrays_count; i++) {
1634 			zend_revert_pass_two(call_graph.op_arrays[i]);
1635 			zend_optimize(call_graph.op_arrays[i], &ctx);
1636 		}
1637 
1638 	    zend_analyze_call_graph(&ctx.arena, script, &call_graph);
1639 
1640 		for (i = 0; i < call_graph.op_arrays_count; i++) {
1641 			func_info = ZEND_FUNC_INFO(call_graph.op_arrays[i]);
1642 			if (func_info) {
1643 				func_info->call_map = zend_build_call_map(&ctx.arena, func_info, call_graph.op_arrays[i]);
1644 				if (call_graph.op_arrays[i]->fn_flags & ZEND_ACC_HAS_RETURN_TYPE) {
1645 					zend_init_func_return_info(call_graph.op_arrays[i], script, &func_info->return_info);
1646 				}
1647 			}
1648 		}
1649 
1650 		for (i = 0; i < call_graph.op_arrays_count; i++) {
1651 			func_info = ZEND_FUNC_INFO(call_graph.op_arrays[i]);
1652 			if (func_info) {
1653 				if (zend_dfa_analyze_op_array(call_graph.op_arrays[i], &ctx, &func_info->ssa) == SUCCESS) {
1654 					func_info->flags = func_info->ssa.cfg.flags;
1655 				} else {
1656 					ZEND_SET_FUNC_INFO(call_graph.op_arrays[i], NULL);
1657 				}
1658 			}
1659 		}
1660 
1661 		//TODO: perform inner-script inference???
1662 		for (i = 0; i < call_graph.op_arrays_count; i++) {
1663 			func_info = ZEND_FUNC_INFO(call_graph.op_arrays[i]);
1664 			if (func_info) {
1665 				zend_dfa_optimize_op_array(call_graph.op_arrays[i], &ctx, &func_info->ssa, func_info->call_map);
1666 			}
1667 		}
1668 
1669 		if (debug_level & ZEND_DUMP_AFTER_PASS_7) {
1670 			for (i = 0; i < call_graph.op_arrays_count; i++) {
1671 				zend_dump_op_array(call_graph.op_arrays[i], 0, "after pass 7", NULL);
1672 			}
1673 		}
1674 
1675 		if (ZEND_OPTIMIZER_PASS_9 & optimization_level) {
1676 			for (i = 0; i < call_graph.op_arrays_count; i++) {
1677 				zend_optimize_temporary_variables(call_graph.op_arrays[i], &ctx);
1678 				if (debug_level & ZEND_DUMP_AFTER_PASS_9) {
1679 					zend_dump_op_array(call_graph.op_arrays[i], 0, "after pass 9", NULL);
1680 				}
1681 			}
1682 		}
1683 
1684 		if (ZEND_OPTIMIZER_PASS_11 & optimization_level) {
1685 			for (i = 0; i < call_graph.op_arrays_count; i++) {
1686 				zend_optimizer_compact_literals(call_graph.op_arrays[i], &ctx);
1687 				if (debug_level & ZEND_DUMP_AFTER_PASS_11) {
1688 					zend_dump_op_array(call_graph.op_arrays[i], 0, "after pass 11", NULL);
1689 				}
1690 			}
1691 		}
1692 
1693 		if (ZEND_OPTIMIZER_PASS_13 & optimization_level) {
1694 			for (i = 0; i < call_graph.op_arrays_count; i++) {
1695 				zend_optimizer_compact_vars(call_graph.op_arrays[i]);
1696 				if (debug_level & ZEND_DUMP_AFTER_PASS_13) {
1697 					zend_dump_op_array(call_graph.op_arrays[i], 0, "after pass 13", NULL);
1698 				}
1699 			}
1700 		}
1701 
1702 		if (ZEND_OPTIMIZER_PASS_12 & optimization_level) {
1703 			for (i = 0; i < call_graph.op_arrays_count; i++) {
1704 				zend_adjust_fcall_stack_size_graph(call_graph.op_arrays[i]);
1705 			}
1706 		}
1707 
1708 		for (i = 0; i < call_graph.op_arrays_count; i++) {
1709 			op_array = call_graph.op_arrays[i];
1710 			func_info = ZEND_FUNC_INFO(op_array);
1711 			if (func_info && func_info->ssa.var_info) {
1712 				zend_redo_pass_two_ex(op_array, &func_info->ssa);
1713 				if (op_array->live_range) {
1714 					zend_recalc_live_ranges(op_array, needs_live_range);
1715 				}
1716 			} else {
1717 				zend_redo_pass_two(op_array);
1718 				if (op_array->live_range) {
1719 					zend_recalc_live_ranges(op_array, NULL);
1720 				}
1721 			}
1722 		}
1723 
1724 		for (i = 0; i < call_graph.op_arrays_count; i++) {
1725 			ZEND_SET_FUNC_INFO(call_graph.op_arrays[i], NULL);
1726 		}
1727 	} else {
1728 		zend_foreach_op_array(script, step_optimize_op_array, &ctx);
1729 
1730 		if (ZEND_OPTIMIZER_PASS_12 & optimization_level) {
1731 			zend_foreach_op_array(script, step_adjust_fcall_stack_size, &ctx);
1732 		}
1733 	}
1734 
1735 	ZEND_HASH_MAP_FOREACH_VAL(&script->class_table, zv) {
1736 		if (Z_TYPE_P(zv) == IS_ALIAS_PTR) {
1737 			continue;
1738 		}
1739 		zend_class_entry *ce = Z_CE_P(zv);
1740 		ZEND_HASH_MAP_FOREACH_STR_KEY_PTR(&ce->function_table, name, op_array) {
1741 			if (op_array->scope != ce && op_array->type == ZEND_USER_FUNCTION) {
1742 				zend_op_array *orig_op_array =
1743 					zend_hash_find_ptr(&op_array->scope->function_table, name);
1744 
1745 				ZEND_ASSERT(orig_op_array != NULL);
1746 				if (orig_op_array != op_array) {
1747 					uint32_t fn_flags = op_array->fn_flags;
1748 					zend_function *prototype = op_array->prototype;
1749 					HashTable *ht = op_array->static_variables;
1750 
1751 					*op_array = *orig_op_array;
1752 					op_array->fn_flags = fn_flags;
1753 					op_array->prototype = prototype;
1754 					op_array->static_variables = ht;
1755 				}
1756 			}
1757 		} ZEND_HASH_FOREACH_END();
1758 	} ZEND_HASH_FOREACH_END();
1759 
1760 	zend_optimizer_call_registered_passes(script, &ctx);
1761 
1762 	if ((debug_level & ZEND_DUMP_AFTER_OPTIMIZER) &&
1763 			(ZEND_OPTIMIZER_PASS_7 & optimization_level)) {
1764 		zend_foreach_op_array(script, step_dump_after_optimizer, NULL);
1765 	}
1766 
1767 	if (ctx.constants) {
1768 		zend_hash_destroy(ctx.constants);
1769 	}
1770 	zend_arena_destroy(ctx.arena);
1771 }
1772 
zend_optimizer_register_pass(zend_optimizer_pass_t pass)1773 ZEND_API int zend_optimizer_register_pass(zend_optimizer_pass_t pass)
1774 {
1775 	if (!pass) {
1776 		return -1;
1777 	}
1778 
1779 	if (zend_optimizer_registered_passes.last == ZEND_OPTIMIZER_MAX_REGISTERED_PASSES) {
1780 		return -1;
1781 	}
1782 
1783 	zend_optimizer_registered_passes.pass[
1784 		zend_optimizer_registered_passes.last++] = pass;
1785 
1786 	return zend_optimizer_registered_passes.last;
1787 }
1788 
zend_optimizer_unregister_pass(int idx)1789 ZEND_API void zend_optimizer_unregister_pass(int idx)
1790 {
1791 	zend_optimizer_registered_passes.pass[idx-1] = NULL;
1792 }
1793 
zend_optimizer_startup(void)1794 zend_result zend_optimizer_startup(void)
1795 {
1796 	return zend_func_info_startup();
1797 }
1798 
zend_optimizer_shutdown(void)1799 zend_result zend_optimizer_shutdown(void)
1800 {
1801 	return zend_func_info_shutdown();
1802 }
1803