2 * Copyright (C) 1995-2008 University of Karlsruhe. All right reserved.
4 * This file is part of libFirm.
6 * This file may be distributed and/or modified under the terms of the
7 * GNU General Public License version 2 as published by the Free Software
8 * Foundation and appearing in the file LICENSE.GPL included in the
9 * packaging of this file.
11 * Licensees holding valid libFirm Professional Edition licenses may use
12 * this file in accordance with the libFirm Commercial License.
13 * Agreement provided with the Software.
15 * This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
16 * WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22 * @brief Code instrumentation and execution count profiling.
23 * @author Adam M. Szalkowski
52 #include "irprofile.h"
54 /** An entry in the id-to-location map */
55 typedef struct loc_entry {
56 ir_entity *fname; /**< the entity holding the file name */
57 unsigned int lineno; /**< line number */
60 typedef struct _block_id_walker_data_t {
61 tarval **array; /**< the entity the holds the block counts */
62 unsigned int id; /**< current block id number */
63 ir_node *symconst; /**< the SymConst representing array */
64 pmap *fname_map; /**< set containing all found filenames */
65 loc_entry *locs; /**< locations */
66 ir_type *tp_char; /**< the character type */
67 unsigned flags; /**< profile flags */
68 } block_id_walker_data_t;
70 typedef struct _execcount_t {
76 * Compare two execcount_t entries.
78 static int cmp_execcount(const void *a, const void *b, size_t size) {
79 const execcount_t *ea = a;
80 const execcount_t *eb = b;
82 return ea->block != eb->block;
86 * Block walker, count number of blocks.
88 static void block_counter(ir_node * bb, void * data) {
89 unsigned int *count = data;
95 * Return the number of blocks the given graph.
97 static unsigned int count_blocks(ir_graph *irg) {
98 unsigned int count = 0;
100 irg_block_walk_graph(irg, block_counter, NULL, &count);
104 /* keep the execcounts here because they are only read once per compiler run */
105 static set * profile = NULL;
106 static hook_entry_t hook;
109 * Instrument a block with code needed for profiling
112 instrument_block(ir_node *bb, ir_node *address, unsigned int id)
114 ir_graph *irg = get_irn_irg(bb);
115 ir_node *start_block = get_irg_start_block(irg);
116 ir_node *load, *store, *offset, *add, *projm, *proji, *unknown;
120 * We can't instrument the end block as there are no real instructions there
122 if(bb == get_irg_end_block(irg))
125 unknown = new_r_Unknown(irg, mode_M);
126 cnst = new_r_Const_long(irg, start_block, mode_Iu, get_mode_size_bytes(mode_Iu) * id);
127 offset = new_r_Add(irg, bb, address, cnst, mode_P);
128 load = new_r_Load(irg, bb, unknown, offset, mode_Iu);
129 projm = new_r_Proj(irg, bb, load, mode_M, pn_Load_M);
130 proji = new_r_Proj(irg, bb, load, mode_Iu, pn_Load_res);
131 cnst = new_r_Const_long(irg, start_block, mode_Iu, 1);
132 add = new_r_Add(irg, bb, proji, cnst, mode_Iu);
133 store = new_r_Store(irg, bb, projm, offset, add);
134 projm = new_r_Proj(irg, bb, store, mode_M, pn_Store_M);
135 set_irn_link(bb, projm);
136 set_irn_link(projm, load);
139 typedef struct fix_env {
144 * SSA Construction for instrumentation code memory
147 fix_ssa(ir_node * bb, void * data)
151 int arity = get_Block_n_cfgpreds(bb);
153 /* start and end block are not instrumented, skip! */
154 if (bb == env->end_block)
157 if (bb == get_irg_start_block(get_irn_irg(bb))) {
159 } else if (arity == 1) {
160 mem = get_irn_link(get_Block_cfgpred_block(bb, 0));
164 ir_graph *irg = current_ir_graph;
166 NEW_ARR_A(ir_node*, ins, arity);
167 for (n = arity - 1; n >= 0; --n) {
168 ins[n] = get_irn_link(get_Block_cfgpred_block(bb, n));
170 mem = new_r_Phi(irg, bb, arity, ins, mode_M);
172 set_Load_mem(get_irn_link(get_irn_link(bb)), mem);
175 static void add_constructor(ir_entity *method)
177 ir_type *method_type = get_entity_type(method);
178 ident *id = id_unique("constructor_ptrt.%u");
179 ir_type *ptr_type = new_type_pointer(id, method_type, mode_P_code);
181 ir_type *constructors = get_segment_type(IR_SEGMENT_CONSTRUCTORS);
182 ident *ide = id_unique("constructor_ptr.%u");
183 ir_entity *ptr = new_entity(constructors, ide, ptr_type);
184 ir_graph *irg = get_const_code_irg();
185 ir_node *val = new_rd_SymConst_addr_ent(NULL, irg, mode_P_code,
188 set_entity_compiler_generated(ptr, 1);
189 set_entity_variability(ptr, variability_constant);
190 set_atomic_ent_value(ptr, val);
194 * Generates a new irg which calls the initializer
197 * void __firmprof_initializer(void) { __init_firmprof(ent_filename, bblock_id, bblock_counts, n_blocks); }
200 gen_initializer_irg(ir_entity * ent_filename, ir_entity * bblock_id, ir_entity * bblock_counts, int n_blocks)
202 ir_node *start_block;
205 ident *name = new_id_from_str("__firmprof_initializer");
206 ir_entity *ent = new_entity(get_glob_type(), name, new_type_method(name, 0, 0));
207 ir_node *ret, *call, *symconst;
210 ident *init_name = new_id_from_str("__init_firmprof");
211 ir_type *init_type = new_type_method(init_name, 4, 0);
212 ir_type *uint, *uintptr, *string;
216 ir_type *empty_frame_type;
218 set_entity_ld_ident(ent, name);
220 uint = new_type_primitive(new_id_from_str("__uint"), mode_Iu);
221 uintptr = new_type_pointer(new_id_from_str("__uintptr"), uint, mode_P);
222 string = new_type_pointer(new_id_from_str("__charptr"), new_type_primitive(new_id_from_str("__char"), mode_Bs), mode_P);
224 set_method_param_type(init_type, 0, string);
225 set_method_param_type(init_type, 1, uintptr);
226 set_method_param_type(init_type, 2, uintptr);
227 set_method_param_type(init_type, 3, uint);
228 init_ent = new_entity(get_glob_type(), init_name, init_type);
229 set_entity_ld_ident(init_ent, init_name);
231 irg = new_ir_graph(ent, 0);
232 empty_frame_type = get_irg_frame_type(irg);
233 set_type_size_bytes(empty_frame_type, 0);
235 bb = get_cur_block();
237 start_block = get_irg_start_block(irg);
239 sym.entity_p = init_ent;
240 symconst = new_r_SymConst(irg, start_block, mode_P_data, sym, symconst_addr_ent);
242 sym.entity_p = ent_filename;
243 ins[0] = new_r_SymConst(irg, start_block, mode_P_data, sym, symconst_addr_ent);
244 sym.entity_p = bblock_id;
245 ins[1] = new_r_SymConst(irg, start_block, mode_P_data, sym, symconst_addr_ent);
246 sym.entity_p = bblock_counts;
247 ins[2] = new_r_SymConst(irg, start_block, mode_P_data, sym, symconst_addr_ent);
248 ins[3] = new_r_Const_long(irg, start_block, mode_Iu, n_blocks);
250 call = new_r_Call(irg, bb, get_irg_initial_mem(irg), symconst, 4, ins, init_type);
251 ret = new_r_Return(irg, bb, new_r_Proj(irg, bb, call, mode_M, pn_Call_M_regular), 0, NULL);
254 add_immBlock_pred(get_irg_end_block(irg), ret);
255 mature_immBlock(get_irg_end_block(irg));
257 irg_finalize_cons(irg);
259 add_constructor(ent);
265 * Create the location data for the given debug info.
267 static void create_location_data(dbg_info *dbg, block_id_walker_data_t *wd)
270 const char *fname = ir_retrieve_dbg_info(dbg, &lineno);
273 pmap_entry *entry = pmap_find(wd->fname_map, (void *)fname);
277 static unsigned nr = 0;
281 int i, len = strlen(fname) + 1;
282 tarval **tarval_string;
284 snprintf(buf, sizeof(buf), "firm_name_arr.%d", nr);
285 arr = new_type_array(new_id_from_str(buf), 1, wd->tp_char);
286 set_array_bounds_int(arr, 0, 0, len);
288 snprintf(buf, sizeof(buf), "__firm_name.%d", nr++);
289 id = new_id_from_str(buf);
290 ent = new_entity(get_glob_type(), id, arr);
291 set_entity_ld_ident(ent, id);
293 pmap_insert(wd->fname_map, (void *)fname, ent);
295 /* initialize file name string constant */
296 tarval_string = alloca(sizeof(*tarval_string) * (len));
297 for (i = 0; i < len; ++i) {
298 tarval_string[i] = new_tarval_from_long(fname[i], mode_Bs);
300 set_entity_variability(ent, variability_constant);
301 set_array_entity_values(ent, tarval_string, len);
305 wd->locs[wd->id].fname = ent;
306 wd->locs[wd->id].lineno = lineno;
308 wd->locs[wd->id].fname = NULL;
309 wd->locs[wd->id].lineno = 0;
314 * Walker: assigns an ID to every block.
315 * Builds the string table
318 block_id_walker(ir_node * bb, void * data)
320 block_id_walker_data_t *wd = data;
322 wd->array[wd->id] = new_tarval_from_long(get_irn_node_nr(bb), mode_Iu);
323 instrument_block(bb, wd->symconst, wd->id);
325 if (wd->flags & profile_with_locations) {
326 dbg_info *dbg = get_irn_dbg_info(bb);
327 create_location_data(dbg, wd);
332 #define IDENT(x) new_id_from_chars(x, sizeof(x) - 1)
335 ir_profile_instrument(const char *filename, unsigned flags)
339 ir_entity *bblock_id;
340 ir_entity *bblock_counts;
341 ir_entity *ent_filename;
342 ir_entity *ent_locations = NULL;
343 ir_entity *loc_lineno = NULL;
344 ir_entity *loc_name = NULL;
348 ir_type *string_type;
349 ir_type *character_type;
350 ir_type *loc_type = NULL;
351 ir_type *charptr_type;
353 ir_node *start_block;
354 tarval **tarval_array;
355 tarval **tarval_string;
357 int filename_len = strlen(filename)+1;
359 unsigned align_l, align_n, size;
361 block_id_walker_data_t wd;
364 /* count the number of block first */
365 for (n = get_irp_n_irgs() - 1; n >= 0; --n) {
366 ir_graph *irg = get_irp_irg(n);
368 n_blocks += count_blocks(irg);
371 /* create all the necessary types and entities. Note that the
372 types must have a fixed layout, because we already running in the
374 uint_type = new_type_primitive(IDENT("__uint"), mode_Iu);
375 set_type_alignment_bytes(uint_type, get_type_size_bytes(uint_type));
377 array_type = new_type_array(IDENT("__block_info_array"), 1, uint_type);
378 set_array_bounds_int(array_type, 0, 0, n_blocks);
379 set_type_size_bytes(array_type, n_blocks * get_mode_size_bytes(mode_Iu));
380 set_type_alignment_bytes(array_type, get_mode_size_bytes(mode_Iu));
381 set_type_state(array_type, layout_fixed);
383 character_type = new_type_primitive(IDENT("__char"), mode_Bs);
384 string_type = new_type_array(IDENT("__filename"), 1, character_type);
385 set_array_bounds_int(string_type, 0, 0, filename_len);
386 set_type_size_bytes(string_type, filename_len);
387 set_type_alignment_bytes(string_type, 1);
388 set_type_state(string_type, layout_fixed);
390 gtp = get_glob_type();
392 cur_ident = IDENT("__FIRMPROF__BLOCK_IDS");
393 bblock_id = new_entity(gtp, cur_ident, array_type);
394 set_entity_ld_ident(bblock_id, cur_ident);
395 set_entity_variability(bblock_id, variability_initialized);
397 cur_ident = IDENT("__FIRMPROF__BLOCK_COUNTS");
398 bblock_counts = new_entity(gtp, cur_ident, array_type);
399 set_entity_ld_ident(bblock_counts, cur_ident);
400 set_entity_variability(bblock_counts, variability_initialized);
402 cur_ident = IDENT("__FIRMPROF__FILE_NAME");
403 ent_filename = new_entity(gtp, cur_ident, string_type);
404 set_entity_ld_ident(ent_filename, cur_ident);
406 if (flags & profile_with_locations) {
407 loc_type = new_type_struct(IDENT("__location"));
408 loc_lineno = new_entity(loc_type, IDENT("lineno"), uint_type);
409 align_l = get_type_alignment_bytes(uint_type);
410 size = get_type_size_bytes(uint_type);
411 set_entity_offset(loc_lineno, 0);
413 charptr_type = new_type_pointer(IDENT("__charptr"), character_type, mode_P_data);
414 align_n = get_type_size_bytes(charptr_type);
415 set_type_alignment_bytes(charptr_type, align_n);
416 loc_name = new_entity(loc_type, IDENT("name"), charptr_type);
417 size = (size + align_n - 1) & ~(align_n - 1);
418 set_entity_offset(loc_name, size);
421 if (align_n > align_l)
423 size = (size + align_l - 1) & ~(align_l - 1);
424 set_type_size_bytes(loc_type, size);
425 set_type_state(loc_type, layout_fixed);
427 loc_type = new_type_array(IDENT("__locarray"), 1, loc_type);
428 set_array_bounds_int(string_type, 0, 0, n_blocks);
430 cur_ident = IDENT("__FIRMPROF__LOCATIONS");
431 ent_locations = new_entity(gtp, cur_ident, loc_type);
432 set_entity_ld_ident(ent_locations, cur_ident);
435 /* initialize count array */
436 NEW_ARR_A(tarval *, tarval_array, n_blocks);
437 tv = get_tarval_null(mode_Iu);
438 for (i = 0; i < n_blocks; ++i) {
439 tarval_array[i] = tv;
441 set_array_entity_values(bblock_counts, tarval_array, n_blocks);
443 /* initialize function name string constant */
444 tarval_string = alloca(sizeof(*tarval_string) * (filename_len));
445 for (i = 0; i < filename_len; ++i) {
446 tarval_string[i] = new_tarval_from_long(filename[i], mode_Bs);
448 set_entity_variability(ent_filename, variability_constant);
449 set_array_entity_values(ent_filename, tarval_string, filename_len);
451 /* initialize block id array and instrument blocks */
452 wd.array = tarval_array;
454 wd.tp_char = character_type;
456 if (flags & profile_with_locations) {
457 wd.fname_map = pmap_create();
458 NEW_ARR_A(loc_entry, wd.locs, n_blocks);
461 for (n = get_irp_n_irgs() - 1; n >= 0; --n) {
462 ir_graph *irg = get_irp_irg(n);
464 ir_node *endbb = get_irg_end_block(irg);
467 set_current_ir_graph(irg);
469 /* generate a symbolic constant pointing to the count array */
470 sym.entity_p = bblock_counts;
471 wd.symconst = new_r_SymConst(irg, get_irg_start_block(irg), mode_P_data, sym, symconst_addr_ent);
473 irg_block_walk_graph(irg, block_id_walker, NULL, &wd);
474 start_block = get_irg_start_block(irg);
475 env.end_block = get_irg_end_block(irg);
476 irg_block_walk_graph(irg, fix_ssa, NULL, &env);
477 for (i = get_Block_n_cfgpreds(endbb) - 1; i >= 0; --i) {
478 ir_node *node = skip_Proj(get_Block_cfgpred(endbb, i));
479 ir_node *bb = get_Block_cfgpred_block(endbb, i);
483 switch (get_irn_opcode(node)) {
485 ins[0] = get_irn_link(bb);
486 ins[1] = get_Return_mem(node);
487 sync = new_r_Sync(irg, bb, 2, ins);
488 set_Return_mem(node, sync);
491 ins[0] = get_irn_link(bb);
492 ins[1] = get_Raise_mem(node);
493 sync = new_r_Sync(irg, bb, 2, ins);
494 set_Raise_mem(node, sync);
497 /* a fragile's op exception. There should be another path to End,
499 assert(is_fragile_op(node) && "unexpected End control flow predecessor");
503 set_array_entity_values(bblock_id, tarval_array, n_blocks);
505 if (flags & profile_with_locations) {
506 /* build the initializer for the locations */
507 rem = current_ir_graph;
508 current_ir_graph = get_const_code_irg();
509 ent = get_array_element_entity(loc_type);
510 set_entity_variability(ent_locations, variability_constant);
511 for (i = 0; i < n_blocks; ++i) {
512 compound_graph_path *path;
517 path = new_compound_graph_path(loc_type, 2);
518 set_compound_graph_path_array_index(path, 0, i);
519 set_compound_graph_path_node(path, 0, ent);
520 set_compound_graph_path_node(path, 1, loc_lineno);
521 tv = new_tarval_from_long(wd.locs[i].lineno, mode_Iu);
522 add_compound_ent_value_w_path(ent_locations, new_Const(mode_Iu, tv), path);
525 path = new_compound_graph_path(loc_type, 2);
526 set_compound_graph_path_array_index(path, 0, i);
527 set_compound_graph_path_node(path, 0, ent);
528 set_compound_graph_path_node(path, 1, loc_name);
529 if (wd.locs[i].fname) {
530 sym.entity_p = wd.locs[i].fname;
531 n = new_SymConst(mode_P_data, sym, symconst_addr_ent);
533 n = new_Const(mode_P_data, get_mode_null(mode_P_data));
535 add_compound_ent_value_w_path(ent_locations, n, path);
537 pmap_destroy(wd.fname_map);
539 return gen_initializer_irg(ent_filename, bblock_id, bblock_counts, n_blocks);
543 profile_node_info(void *ctx, FILE *f, const ir_node *irn)
547 fprintf(f, "profiled execution count: %u\n", ir_profile_get_block_execcount(irn));
552 register_vcg_hook(void)
554 memset(&hook, 0, sizeof(hook));
555 hook.hook._hook_node_info = profile_node_info;
556 register_hook(hook_node_info, &hook);
560 unregister_vcg_hook(void)
562 unregister_hook(hook_node_info, &hook);
566 * Reads the corresponding profile info file if it exists and returns a
567 * profile info struct
570 ir_profile_read(const char *filename)
576 f = fopen(filename, "r");
580 printf("found profile data '%s'.\n", filename);
583 ret = fread(buf, 8, 1, f);
584 if(ret == 0 || strncmp(buf, "firmprof", 8) != 0) {
588 if(profile) ir_profile_free();
589 profile = new_set(cmp_execcount, 16);
593 ret = fread(&query, sizeof(unsigned int), 2, f);
597 set_insert(profile, &query, sizeof(query), query.block);
605 * Frees the profile info
608 ir_profile_free(void)
611 unregister_vcg_hook();
617 * Tells whether profile module has acquired data
620 ir_profile_has_data(void)
622 return (profile != NULL);
626 * Get block execution count as determined be profiling
629 ir_profile_get_block_execcount(const ir_node *block)
631 execcount_t *ec, query;
636 query.block = get_irn_node_nr(block);
637 ec = set_find(profile, &query, sizeof(query), get_irn_node_nr(block));
642 ir_fprintf(stderr, "Warning: Profile contains no data for %+F\n",
648 typedef struct _intialize_execfreq_env_t {
650 ir_exec_freq *execfreqs;
652 } initialize_execfreq_env_t;
654 // minimal execution frequency (an execfreq of 0 confuses algos)
655 static const double MIN_EXECFREQ = 0.00001;
657 static void initialize_execfreq(ir_node *block, void *data) {
658 initialize_execfreq_env_t *env = data;
661 if(block == get_irg_start_block(env->irg)
662 || block == get_irg_end_block(env->irg)) {
665 freq = ir_profile_get_block_execcount(block);
666 freq *= env->freq_factor;
667 if(freq < MIN_EXECFREQ)
671 set_execfreq(env->execfreqs, block, freq);
674 ir_exec_freq *ir_create_execfreqs_from_profile(ir_graph *irg)
676 ir_node *start_block;
677 initialize_execfreq_env_t env;
681 env.execfreqs = create_execfreq(irg);
682 start_block = get_irg_start_block(irg);
684 count = ir_profile_get_block_execcount(start_block);
686 // the function was never executed, so fallback to estimated freqs
687 free_execfreq(env.execfreqs);
689 return compute_execfreq(irg, 10);
692 env.freq_factor = 1.0 / count;
693 irg_block_walk_graph(irg, initialize_execfreq, NULL, &env);
695 return env.execfreqs;