2015-09-03 Richard Biener <rguenther@suse.de>
[official-gcc.git] / gcc / auto-profile.c
blobfa0cd07f573f3dc551bae421ce2a5174512614a9
1 /* Read and annotate call graph profile from the auto profile data file.
2 Copyright (C) 2014-2015 Free Software Foundation, Inc.
3 Contributed by Dehao Chen (dehao@google.com)
5 This file is part of GCC.
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 for more details.
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3. If not see
19 <http://www.gnu.org/licenses/>. */
21 #include "config.h"
22 #include "system.h"
24 #include <string.h>
25 #include <map>
26 #include <set>
28 #include "coretypes.h"
29 #include "alias.h"
30 #include "backend.h"
31 #include "predict.h"
32 #include "tree.h"
33 #include "gimple.h"
34 #include "hard-reg-set.h"
35 #include "ssa.h"
36 #include "options.h"
37 #include "fold-const.h"
38 #include "tree-pass.h"
39 #include "flags.h"
40 #include "diagnostic-core.h"
41 #include "gcov-io.h"
42 #include "profile.h"
43 #include "langhooks.h"
44 #include "opts.h"
45 #include "tree-pass.h"
46 #include "cfgloop.h"
47 #include "tree-cfg.h"
48 #include "tree-cfgcleanup.h"
49 #include "tree-into-ssa.h"
50 #include "internal-fn.h"
51 #include "gimple-iterator.h"
52 #include "cgraph.h"
53 #include "value-prof.h"
54 #include "coverage.h"
55 #include "params.h"
56 #include "alloc-pool.h"
57 #include "symbol-summary.h"
58 #include "ipa-prop.h"
59 #include "ipa-inline.h"
60 #include "tree-inline.h"
61 #include "auto-profile.h"
63 /* The following routines implements AutoFDO optimization.
65 This optimization uses sampling profiles to annotate basic block counts
66 and uses heuristics to estimate branch probabilities.
68 There are three phases in AutoFDO:
70 Phase 1: Read profile from the profile data file.
71 The following info is read from the profile datafile:
72 * string_table: a map between function name and its index.
73 * autofdo_source_profile: a map from function_instance name to
74 function_instance. This is represented as a forest of
75 function_instances.
76 * WorkingSet: a histogram of how many instructions are covered for a
77 given percentage of total cycles. This is describing the binary
78 level information (not source level). This info is used to help
79 decide if we want aggressive optimizations that could increase
80 code footprint (e.g. loop unroll etc.)
81 A function instance is an instance of function that could either be a
82 standalone symbol, or a clone of a function that is inlined into another
83 function.
85 Phase 2: Early inline + value profile transformation.
86 Early inline uses autofdo_source_profile to find if a callsite is:
87 * inlined in the profiled binary.
88 * callee body is hot in the profiling run.
89 If both condition satisfies, early inline will inline the callsite
90 regardless of the code growth.
91 Phase 2 is an iterative process. During each iteration, we also check
92 if an indirect callsite is promoted and inlined in the profiling run.
93 If yes, vpt will happen to force promote it and in the next iteration,
94 einline will inline the promoted callsite in the next iteration.
96 Phase 3: Annotate control flow graph.
97 AutoFDO uses a separate pass to:
98 * Annotate basic block count
99 * Estimate branch probability
101 After the above 3 phases, all profile is readily annotated on the GCC IR.
102 AutoFDO tries to reuse all FDO infrastructure as much as possible to make
103 use of the profile. E.g. it uses existing mechanism to calculate the basic
104 block/edge frequency, as well as the cgraph node/edge count.
107 #define DEFAULT_AUTO_PROFILE_FILE "fbdata.afdo"
108 #define AUTO_PROFILE_VERSION 1
110 namespace autofdo
113 /* Represent a source location: (function_decl, lineno). */
114 typedef std::pair<tree, unsigned> decl_lineno;
116 /* Represent an inline stack. vector[0] is the leaf node. */
117 typedef auto_vec<decl_lineno> inline_stack;
119 /* String array that stores function names. */
120 typedef auto_vec<char *> string_vector;
122 /* Map from function name's index in string_table to target's
123 execution count. */
124 typedef std::map<unsigned, gcov_type> icall_target_map;
126 /* Set of gimple stmts. Used to track if the stmt has already been promoted
127 to direct call. */
128 typedef std::set<gimple> stmt_set;
130 /* Represent count info of an inline stack. */
131 struct count_info
133 /* Sampled count of the inline stack. */
134 gcov_type count;
136 /* Map from indirect call target to its sample count. */
137 icall_target_map targets;
139 /* Whether this inline stack is already used in annotation.
141 Each inline stack should only be used to annotate IR once.
142 This will be enforced when instruction-level discriminator
143 is supported. */
144 bool annotated;
147 /* operator< for "const char *". */
148 struct string_compare
150 bool operator()(const char *a, const char *b) const
152 return strcmp (a, b) < 0;
156 /* Store a string array, indexed by string position in the array. */
157 class string_table
159 public:
160 string_table ()
163 ~string_table ();
165 /* For a given string, returns its index. */
166 int get_index (const char *name) const;
168 /* For a given decl, returns the index of the decl name. */
169 int get_index_by_decl (tree decl) const;
171 /* For a given index, returns the string. */
172 const char *get_name (int index) const;
174 /* Read profile, return TRUE on success. */
175 bool read ();
177 private:
178 typedef std::map<const char *, unsigned, string_compare> string_index_map;
179 string_vector vector_;
180 string_index_map map_;
183 /* Profile of a function instance:
184 1. total_count of the function.
185 2. head_count (entry basic block count) of the function (only valid when
186 function is a top-level function_instance, i.e. it is the original copy
187 instead of the inlined copy).
188 3. map from source location (decl_lineno) to profile (count_info).
189 4. map from callsite to callee function_instance. */
190 class function_instance
192 public:
193 typedef auto_vec<function_instance *> function_instance_stack;
195 /* Read the profile and return a function_instance with head count as
196 HEAD_COUNT. Recursively read callsites to create nested function_instances
197 too. STACK is used to track the recursive creation process. */
198 static function_instance *
199 read_function_instance (function_instance_stack *stack,
200 gcov_type head_count);
202 /* Recursively deallocate all callsites (nested function_instances). */
203 ~function_instance ();
205 /* Accessors. */
207 name () const
209 return name_;
211 gcov_type
212 total_count () const
214 return total_count_;
216 gcov_type
217 head_count () const
219 return head_count_;
222 /* Traverse callsites of the current function_instance to find one at the
223 location of LINENO and callee name represented in DECL. */
224 function_instance *get_function_instance_by_decl (unsigned lineno,
225 tree decl) const;
227 /* Store the profile info for LOC in INFO. Return TRUE if profile info
228 is found. */
229 bool get_count_info (location_t loc, count_info *info) const;
231 /* Read the inlined indirect call target profile for STMT and store it in
232 MAP, return the total count for all inlined indirect calls. */
233 gcov_type find_icall_target_map (gcall *stmt, icall_target_map *map) const;
235 /* Sum of counts that is used during annotation. */
236 gcov_type total_annotated_count () const;
238 /* Mark LOC as annotated. */
239 void mark_annotated (location_t loc);
241 private:
242 /* Callsite, represented as (decl_lineno, callee_function_name_index). */
243 typedef std::pair<unsigned, unsigned> callsite;
245 /* Map from callsite to callee function_instance. */
246 typedef std::map<callsite, function_instance *> callsite_map;
248 function_instance (unsigned name, gcov_type head_count)
249 : name_ (name), total_count_ (0), head_count_ (head_count)
253 /* Map from source location (decl_lineno) to profile (count_info). */
254 typedef std::map<unsigned, count_info> position_count_map;
256 /* function_instance name index in the string_table. */
257 unsigned name_;
259 /* Total sample count. */
260 gcov_type total_count_;
262 /* Entry BB's sample count. */
263 gcov_type head_count_;
265 /* Map from callsite location to callee function_instance. */
266 callsite_map callsites;
268 /* Map from source location to count_info. */
269 position_count_map pos_counts;
272 /* Profile for all functions. */
273 class autofdo_source_profile
275 public:
276 static autofdo_source_profile *
277 create ()
279 autofdo_source_profile *map = new autofdo_source_profile ();
281 if (map->read ())
282 return map;
283 delete map;
284 return NULL;
287 ~autofdo_source_profile ();
289 /* For a given DECL, returns the top-level function_instance. */
290 function_instance *get_function_instance_by_decl (tree decl) const;
292 /* Find count_info for a given gimple STMT. If found, store the count_info
293 in INFO and return true; otherwise return false. */
294 bool get_count_info (gimple stmt, count_info *info) const;
296 /* Find total count of the callee of EDGE. */
297 gcov_type get_callsite_total_count (struct cgraph_edge *edge) const;
299 /* Update value profile INFO for STMT from the inlined indirect callsite.
300 Return true if INFO is updated. */
301 bool update_inlined_ind_target (gcall *stmt, count_info *info);
303 /* Mark LOC as annotated. */
304 void mark_annotated (location_t loc);
306 private:
307 /* Map from function_instance name index (in string_table) to
308 function_instance. */
309 typedef std::map<unsigned, function_instance *> name_function_instance_map;
311 autofdo_source_profile () {}
313 /* Read AutoFDO profile and returns TRUE on success. */
314 bool read ();
316 /* Return the function_instance in the profile that correspond to the
317 inline STACK. */
318 function_instance *
319 get_function_instance_by_inline_stack (const inline_stack &stack) const;
321 name_function_instance_map map_;
324 /* Store the strings read from the profile data file. */
325 static string_table *afdo_string_table;
327 /* Store the AutoFDO source profile. */
328 static autofdo_source_profile *afdo_source_profile;
330 /* gcov_ctr_summary structure to store the profile_info. */
331 static struct gcov_ctr_summary *afdo_profile_info;
333 /* Helper functions. */
335 /* Return the original name of NAME: strip the suffix that starts
336 with '.' Caller is responsible for freeing RET. */
338 static char *
339 get_original_name (const char *name)
341 char *ret = xstrdup (name);
342 char *find = strchr (ret, '.');
343 if (find != NULL)
344 *find = 0;
345 return ret;
348 /* Return the combined location, which is a 32bit integer in which
349 higher 16 bits stores the line offset of LOC to the start lineno
350 of DECL, The lower 16 bits stores the discriminator. */
352 static unsigned
353 get_combined_location (location_t loc, tree decl)
355 /* TODO: allow more bits for line and less bits for discriminator. */
356 if (LOCATION_LINE (loc) - DECL_SOURCE_LINE (decl) >= (1<<16))
357 warning_at (loc, OPT_Woverflow, "Offset exceeds 16 bytes.");
358 return ((LOCATION_LINE (loc) - DECL_SOURCE_LINE (decl)) << 16);
361 /* Return the function decl of a given lexical BLOCK. */
363 static tree
364 get_function_decl_from_block (tree block)
366 tree decl;
368 if (LOCATION_LOCUS (BLOCK_SOURCE_LOCATION (block) == UNKNOWN_LOCATION))
369 return NULL_TREE;
371 for (decl = BLOCK_ABSTRACT_ORIGIN (block);
372 decl && (TREE_CODE (decl) == BLOCK);
373 decl = BLOCK_ABSTRACT_ORIGIN (decl))
374 if (TREE_CODE (decl) == FUNCTION_DECL)
375 break;
376 return decl;
379 /* Store inline stack for STMT in STACK. */
381 static void
382 get_inline_stack (location_t locus, inline_stack *stack)
384 if (LOCATION_LOCUS (locus) == UNKNOWN_LOCATION)
385 return;
387 tree block = LOCATION_BLOCK (locus);
388 if (block && TREE_CODE (block) == BLOCK)
390 int level = 0;
391 for (block = BLOCK_SUPERCONTEXT (block);
392 block && (TREE_CODE (block) == BLOCK);
393 block = BLOCK_SUPERCONTEXT (block))
395 location_t tmp_locus = BLOCK_SOURCE_LOCATION (block);
396 if (LOCATION_LOCUS (tmp_locus) == UNKNOWN_LOCATION)
397 continue;
399 tree decl = get_function_decl_from_block (block);
400 stack->safe_push (
401 std::make_pair (decl, get_combined_location (locus, decl)));
402 locus = tmp_locus;
403 level++;
406 stack->safe_push (
407 std::make_pair (current_function_decl,
408 get_combined_location (locus, current_function_decl)));
411 /* Return STMT's combined location, which is a 32bit integer in which
412 higher 16 bits stores the line offset of LOC to the start lineno
413 of DECL, The lower 16 bits stores the discriminator. */
415 static unsigned
416 get_relative_location_for_stmt (gimple stmt)
418 location_t locus = gimple_location (stmt);
419 if (LOCATION_LOCUS (locus) == UNKNOWN_LOCATION)
420 return UNKNOWN_LOCATION;
422 for (tree block = gimple_block (stmt); block && (TREE_CODE (block) == BLOCK);
423 block = BLOCK_SUPERCONTEXT (block))
424 if (LOCATION_LOCUS (BLOCK_SOURCE_LOCATION (block)) != UNKNOWN_LOCATION)
425 return get_combined_location (locus,
426 get_function_decl_from_block (block));
427 return get_combined_location (locus, current_function_decl);
430 /* Return true if BB contains indirect call. */
432 static bool
433 has_indirect_call (basic_block bb)
435 gimple_stmt_iterator gsi;
437 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
439 gimple stmt = gsi_stmt (gsi);
440 if (gimple_code (stmt) == GIMPLE_CALL && !gimple_call_internal_p (stmt)
441 && (gimple_call_fn (stmt) == NULL
442 || TREE_CODE (gimple_call_fn (stmt)) != FUNCTION_DECL))
443 return true;
445 return false;
448 /* Member functions for string_table. */
450 /* Deconstructor. */
452 string_table::~string_table ()
454 for (unsigned i = 0; i < vector_.length (); i++)
455 free (vector_[i]);
459 /* Return the index of a given function NAME. Return -1 if NAME is not
460 found in string table. */
463 string_table::get_index (const char *name) const
465 if (name == NULL)
466 return -1;
467 string_index_map::const_iterator iter = map_.find (name);
468 if (iter == map_.end ())
469 return -1;
471 return iter->second;
474 /* Return the index of a given function DECL. Return -1 if DECL is not
475 found in string table. */
478 string_table::get_index_by_decl (tree decl) const
480 char *name
481 = get_original_name (IDENTIFIER_POINTER (DECL_ASSEMBLER_NAME (decl)));
482 int ret = get_index (name);
483 free (name);
484 if (ret != -1)
485 return ret;
486 ret = get_index (lang_hooks.dwarf_name (decl, 0));
487 if (ret != -1)
488 return ret;
489 if (DECL_ABSTRACT_ORIGIN (decl))
490 return get_index_by_decl (DECL_ABSTRACT_ORIGIN (decl));
492 return -1;
495 /* Return the function name of a given INDEX. */
497 const char *
498 string_table::get_name (int index) const
500 gcc_assert (index > 0 && index < (int)vector_.length ());
501 return vector_[index];
504 /* Read the string table. Return TRUE if reading is successful. */
506 bool
507 string_table::read ()
509 if (gcov_read_unsigned () != GCOV_TAG_AFDO_FILE_NAMES)
510 return false;
511 /* Skip the length of the section. */
512 gcov_read_unsigned ();
513 /* Read in the file name table. */
514 unsigned string_num = gcov_read_unsigned ();
515 for (unsigned i = 0; i < string_num; i++)
517 vector_.safe_push (get_original_name (gcov_read_string ()));
518 map_[vector_.last ()] = i;
520 return true;
523 /* Member functions for function_instance. */
525 function_instance::~function_instance ()
527 for (callsite_map::iterator iter = callsites.begin ();
528 iter != callsites.end (); ++iter)
529 delete iter->second;
532 /* Traverse callsites of the current function_instance to find one at the
533 location of LINENO and callee name represented in DECL. */
535 function_instance *
536 function_instance::get_function_instance_by_decl (unsigned lineno,
537 tree decl) const
539 int func_name_idx = afdo_string_table->get_index_by_decl (decl);
540 if (func_name_idx != -1)
542 callsite_map::const_iterator ret
543 = callsites.find (std::make_pair (lineno, func_name_idx));
544 if (ret != callsites.end ())
545 return ret->second;
547 func_name_idx
548 = afdo_string_table->get_index (lang_hooks.dwarf_name (decl, 0));
549 if (func_name_idx != -1)
551 callsite_map::const_iterator ret
552 = callsites.find (std::make_pair (lineno, func_name_idx));
553 if (ret != callsites.end ())
554 return ret->second;
556 if (DECL_ABSTRACT_ORIGIN (decl))
557 return get_function_instance_by_decl (lineno, DECL_ABSTRACT_ORIGIN (decl));
559 return NULL;
562 /* Store the profile info for LOC in INFO. Return TRUE if profile info
563 is found. */
565 bool
566 function_instance::get_count_info (location_t loc, count_info *info) const
568 position_count_map::const_iterator iter = pos_counts.find (loc);
569 if (iter == pos_counts.end ())
570 return false;
571 *info = iter->second;
572 return true;
575 /* Mark LOC as annotated. */
577 void
578 function_instance::mark_annotated (location_t loc)
580 position_count_map::iterator iter = pos_counts.find (loc);
581 if (iter == pos_counts.end ())
582 return;
583 iter->second.annotated = true;
586 /* Read the inlined indirect call target profile for STMT and store it in
587 MAP, return the total count for all inlined indirect calls. */
589 gcov_type
590 function_instance::find_icall_target_map (gcall *stmt,
591 icall_target_map *map) const
593 gcov_type ret = 0;
594 unsigned stmt_offset = get_relative_location_for_stmt (stmt);
596 for (callsite_map::const_iterator iter = callsites.begin ();
597 iter != callsites.end (); ++iter)
599 unsigned callee = iter->second->name ();
600 /* Check if callsite location match the stmt. */
601 if (iter->first.first != stmt_offset)
602 continue;
603 struct cgraph_node *node = cgraph_node::get_for_asmname (
604 get_identifier (afdo_string_table->get_name (callee)));
605 if (node == NULL)
606 continue;
607 if (!check_ic_target (stmt, node))
608 continue;
609 (*map)[callee] = iter->second->total_count ();
610 ret += iter->second->total_count ();
612 return ret;
615 /* Read the profile and create a function_instance with head count as
616 HEAD_COUNT. Recursively read callsites to create nested function_instances
617 too. STACK is used to track the recursive creation process. */
619 /* function instance profile format:
621 ENTRY_COUNT: 8 bytes
622 NAME_INDEX: 4 bytes
623 NUM_POS_COUNTS: 4 bytes
624 NUM_CALLSITES: 4 byte
625 POS_COUNT_1:
626 POS_1_OFFSET: 4 bytes
627 NUM_TARGETS: 4 bytes
628 COUNT: 8 bytes
629 TARGET_1:
630 VALUE_PROFILE_TYPE: 4 bytes
631 TARGET_IDX: 8 bytes
632 COUNT: 8 bytes
633 TARGET_2
635 TARGET_n
636 POS_COUNT_2
638 POS_COUNT_N
639 CALLSITE_1:
640 CALLSITE_1_OFFSET: 4 bytes
641 FUNCTION_INSTANCE_PROFILE (nested)
642 CALLSITE_2
644 CALLSITE_n. */
646 function_instance *
647 function_instance::read_function_instance (function_instance_stack *stack,
648 gcov_type head_count)
650 unsigned name = gcov_read_unsigned ();
651 unsigned num_pos_counts = gcov_read_unsigned ();
652 unsigned num_callsites = gcov_read_unsigned ();
653 function_instance *s = new function_instance (name, head_count);
654 stack->safe_push (s);
656 for (unsigned i = 0; i < num_pos_counts; i++)
658 unsigned offset = gcov_read_unsigned () & 0xffff0000;
659 unsigned num_targets = gcov_read_unsigned ();
660 gcov_type count = gcov_read_counter ();
661 s->pos_counts[offset].count = count;
662 for (unsigned j = 0; j < stack->length (); j++)
663 (*stack)[j]->total_count_ += count;
664 for (unsigned j = 0; j < num_targets; j++)
666 /* Only indirect call target histogram is supported now. */
667 gcov_read_unsigned ();
668 gcov_type target_idx = gcov_read_counter ();
669 s->pos_counts[offset].targets[target_idx] = gcov_read_counter ();
672 for (unsigned i = 0; i < num_callsites; i++)
674 unsigned offset = gcov_read_unsigned ();
675 function_instance *callee_function_instance
676 = read_function_instance (stack, 0);
677 s->callsites[std::make_pair (offset, callee_function_instance->name ())]
678 = callee_function_instance;
680 stack->pop ();
681 return s;
684 /* Sum of counts that is used during annotation. */
686 gcov_type
687 function_instance::total_annotated_count () const
689 gcov_type ret = 0;
690 for (callsite_map::const_iterator iter = callsites.begin ();
691 iter != callsites.end (); ++iter)
692 ret += iter->second->total_annotated_count ();
693 for (position_count_map::const_iterator iter = pos_counts.begin ();
694 iter != pos_counts.end (); ++iter)
695 if (iter->second.annotated)
696 ret += iter->second.count;
697 return ret;
700 /* Member functions for autofdo_source_profile. */
702 autofdo_source_profile::~autofdo_source_profile ()
704 for (name_function_instance_map::const_iterator iter = map_.begin ();
705 iter != map_.end (); ++iter)
706 delete iter->second;
709 /* For a given DECL, returns the top-level function_instance. */
711 function_instance *
712 autofdo_source_profile::get_function_instance_by_decl (tree decl) const
714 int index = afdo_string_table->get_index_by_decl (decl);
715 if (index == -1)
716 return NULL;
717 name_function_instance_map::const_iterator ret = map_.find (index);
718 return ret == map_.end () ? NULL : ret->second;
721 /* Find count_info for a given gimple STMT. If found, store the count_info
722 in INFO and return true; otherwise return false. */
724 bool
725 autofdo_source_profile::get_count_info (gimple stmt, count_info *info) const
727 if (LOCATION_LOCUS (gimple_location (stmt)) == cfun->function_end_locus)
728 return false;
730 inline_stack stack;
731 get_inline_stack (gimple_location (stmt), &stack);
732 if (stack.length () == 0)
733 return false;
734 function_instance *s = get_function_instance_by_inline_stack (stack);
735 if (s == NULL)
736 return false;
737 return s->get_count_info (stack[0].second, info);
740 /* Mark LOC as annotated. */
742 void
743 autofdo_source_profile::mark_annotated (location_t loc)
745 inline_stack stack;
746 get_inline_stack (loc, &stack);
747 if (stack.length () == 0)
748 return;
749 function_instance *s = get_function_instance_by_inline_stack (stack);
750 if (s == NULL)
751 return;
752 s->mark_annotated (stack[0].second);
755 /* Update value profile INFO for STMT from the inlined indirect callsite.
756 Return true if INFO is updated. */
758 bool
759 autofdo_source_profile::update_inlined_ind_target (gcall *stmt,
760 count_info *info)
762 if (LOCATION_LOCUS (gimple_location (stmt)) == cfun->function_end_locus)
763 return false;
765 count_info old_info;
766 get_count_info (stmt, &old_info);
767 gcov_type total = 0;
768 for (icall_target_map::const_iterator iter = old_info.targets.begin ();
769 iter != old_info.targets.end (); ++iter)
770 total += iter->second;
772 /* Program behavior changed, original promoted (and inlined) target is not
773 hot any more. Will avoid promote the original target.
775 To check if original promoted target is still hot, we check the total
776 count of the unpromoted targets (stored in old_info). If it is no less
777 than half of the callsite count (stored in INFO), the original promoted
778 target is considered not hot any more. */
779 if (total >= info->count / 2)
780 return false;
782 inline_stack stack;
783 get_inline_stack (gimple_location (stmt), &stack);
784 if (stack.length () == 0)
785 return false;
786 function_instance *s = get_function_instance_by_inline_stack (stack);
787 if (s == NULL)
788 return false;
789 icall_target_map map;
790 if (s->find_icall_target_map (stmt, &map) == 0)
791 return false;
792 for (icall_target_map::const_iterator iter = map.begin ();
793 iter != map.end (); ++iter)
794 info->targets[iter->first] = iter->second;
795 return true;
798 /* Find total count of the callee of EDGE. */
800 gcov_type
801 autofdo_source_profile::get_callsite_total_count (
802 struct cgraph_edge *edge) const
804 inline_stack stack;
805 stack.safe_push (std::make_pair (edge->callee->decl, 0));
806 get_inline_stack (gimple_location (edge->call_stmt), &stack);
808 function_instance *s = get_function_instance_by_inline_stack (stack);
809 if (s == NULL
810 || afdo_string_table->get_index (IDENTIFIER_POINTER (
811 DECL_ASSEMBLER_NAME (edge->callee->decl))) != s->name ())
812 return 0;
814 return s->total_count ();
817 /* Read AutoFDO profile and returns TRUE on success. */
819 /* source profile format:
821 GCOV_TAG_AFDO_FUNCTION: 4 bytes
822 LENGTH: 4 bytes
823 NUM_FUNCTIONS: 4 bytes
824 FUNCTION_INSTANCE_1
825 FUNCTION_INSTANCE_2
827 FUNCTION_INSTANCE_N. */
829 bool
830 autofdo_source_profile::read ()
832 if (gcov_read_unsigned () != GCOV_TAG_AFDO_FUNCTION)
834 inform (0, "Not expected TAG.");
835 return false;
838 /* Skip the length of the section. */
839 gcov_read_unsigned ();
841 /* Read in the function/callsite profile, and store it in local
842 data structure. */
843 unsigned function_num = gcov_read_unsigned ();
844 for (unsigned i = 0; i < function_num; i++)
846 function_instance::function_instance_stack stack;
847 function_instance *s = function_instance::read_function_instance (
848 &stack, gcov_read_counter ());
849 afdo_profile_info->sum_all += s->total_count ();
850 map_[s->name ()] = s;
852 return true;
855 /* Return the function_instance in the profile that correspond to the
856 inline STACK. */
858 function_instance *
859 autofdo_source_profile::get_function_instance_by_inline_stack (
860 const inline_stack &stack) const
862 name_function_instance_map::const_iterator iter = map_.find (
863 afdo_string_table->get_index_by_decl (stack[stack.length () - 1].first));
864 if (iter == map_.end())
865 return NULL;
866 function_instance *s = iter->second;
867 for (unsigned i = stack.length() - 1; i > 0; i--)
869 s = s->get_function_instance_by_decl (
870 stack[i].second, stack[i - 1].first);
871 if (s == NULL)
872 return NULL;
874 return s;
877 /* Module profile is only used by LIPO. Here we simply ignore it. */
879 static void
880 fake_read_autofdo_module_profile ()
882 /* Read in the module info. */
883 gcov_read_unsigned ();
885 /* Skip the length of the section. */
886 gcov_read_unsigned ();
888 /* Read in the file name table. */
889 unsigned total_module_num = gcov_read_unsigned ();
890 gcc_assert (total_module_num == 0);
893 /* Read data from profile data file. */
895 static void
896 read_profile (void)
898 if (gcov_open (auto_profile_file, 1) == 0)
899 error ("Cannot open profile file %s.", auto_profile_file);
901 if (gcov_read_unsigned () != GCOV_DATA_MAGIC)
902 error ("AutoFDO profile magic number does not mathch.");
904 /* Skip the version number. */
905 unsigned version = gcov_read_unsigned ();
906 if (version != AUTO_PROFILE_VERSION)
907 error ("AutoFDO profile version %u does match %u.",
908 version, AUTO_PROFILE_VERSION);
910 /* Skip the empty integer. */
911 gcov_read_unsigned ();
913 /* string_table. */
914 afdo_string_table = new string_table ();
915 if (!afdo_string_table->read())
916 error ("Cannot read string table from %s.", auto_profile_file);
918 /* autofdo_source_profile. */
919 afdo_source_profile = autofdo_source_profile::create ();
920 if (afdo_source_profile == NULL)
921 error ("Cannot read function profile from %s.", auto_profile_file);
923 /* autofdo_module_profile. */
924 fake_read_autofdo_module_profile ();
926 /* Read in the working set. */
927 if (gcov_read_unsigned () != GCOV_TAG_AFDO_WORKING_SET)
928 error ("Cannot read working set from %s.", auto_profile_file);
930 /* Skip the length of the section. */
931 gcov_read_unsigned ();
932 gcov_working_set_t set[128];
933 for (unsigned i = 0; i < 128; i++)
935 set[i].num_counters = gcov_read_unsigned ();
936 set[i].min_counter = gcov_read_counter ();
938 add_working_set (set);
941 /* From AutoFDO profiles, find values inside STMT for that we want to measure
942 histograms for indirect-call optimization.
944 This function is actually served for 2 purposes:
945 * before annotation, we need to mark histogram, promote and inline
946 * after annotation, we just need to mark, and let follow-up logic to
947 decide if it needs to promote and inline. */
949 static void
950 afdo_indirect_call (gimple_stmt_iterator *gsi, const icall_target_map &map,
951 bool transform)
953 gimple gs = gsi_stmt (*gsi);
954 tree callee;
956 if (map.size () == 0)
957 return;
958 gcall *stmt = dyn_cast <gcall *> (gs);
959 if ((!stmt) || gimple_call_fndecl (stmt) != NULL_TREE)
960 return;
962 callee = gimple_call_fn (stmt);
964 histogram_value hist = gimple_alloc_histogram_value (
965 cfun, HIST_TYPE_INDIR_CALL, stmt, callee);
966 hist->n_counters = 3;
967 hist->hvalue.counters = XNEWVEC (gcov_type, hist->n_counters);
968 gimple_add_histogram_value (cfun, stmt, hist);
970 gcov_type total = 0;
971 icall_target_map::const_iterator max_iter = map.end ();
973 for (icall_target_map::const_iterator iter = map.begin ();
974 iter != map.end (); ++iter)
976 total += iter->second;
977 if (max_iter == map.end () || max_iter->second < iter->second)
978 max_iter = iter;
981 hist->hvalue.counters[0]
982 = (unsigned long long)afdo_string_table->get_name (max_iter->first);
983 hist->hvalue.counters[1] = max_iter->second;
984 hist->hvalue.counters[2] = total;
986 if (!transform)
987 return;
989 struct cgraph_edge *indirect_edge
990 = cgraph_node::get (current_function_decl)->get_edge (stmt);
991 struct cgraph_node *direct_call = cgraph_node::get_for_asmname (
992 get_identifier ((const char *) hist->hvalue.counters[0]));
994 if (direct_call == NULL || !check_ic_target (stmt, direct_call))
995 return;
996 if (DECL_STRUCT_FUNCTION (direct_call->decl) == NULL)
997 return;
998 struct cgraph_edge *new_edge
999 = indirect_edge->make_speculative (direct_call, 0, 0);
1000 new_edge->redirect_call_stmt_to_callee ();
1001 gimple_remove_histogram_value (cfun, stmt, hist);
1002 inline_call (new_edge, true, NULL, NULL, false);
1005 /* From AutoFDO profiles, find values inside STMT for that we want to measure
1006 histograms and adds them to list VALUES. */
1008 static void
1009 afdo_vpt (gimple_stmt_iterator *gsi, const icall_target_map &map,
1010 bool transform)
1012 afdo_indirect_call (gsi, map, transform);
1015 typedef std::set<basic_block> bb_set;
1016 typedef std::set<edge> edge_set;
1018 static bool
1019 is_bb_annotated (const basic_block bb, const bb_set &annotated)
1021 return annotated.find (bb) != annotated.end ();
1024 static void
1025 set_bb_annotated (basic_block bb, bb_set *annotated)
1027 annotated->insert (bb);
1030 static bool
1031 is_edge_annotated (const edge e, const edge_set &annotated)
1033 return annotated.find (e) != annotated.end ();
1036 static void
1037 set_edge_annotated (edge e, edge_set *annotated)
1039 annotated->insert (e);
1042 /* For a given BB, set its execution count. Attach value profile if a stmt
1043 is not in PROMOTED, because we only want to promote an indirect call once.
1044 Return TRUE if BB is annotated. */
1046 static bool
1047 afdo_set_bb_count (basic_block bb, const stmt_set &promoted)
1049 gimple_stmt_iterator gsi;
1050 edge e;
1051 edge_iterator ei;
1052 gcov_type max_count = 0;
1053 bool has_annotated = false;
1055 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1057 count_info info;
1058 gimple stmt = gsi_stmt (gsi);
1059 if (gimple_clobber_p (stmt) || is_gimple_debug (stmt))
1060 continue;
1061 if (afdo_source_profile->get_count_info (stmt, &info))
1063 if (info.count > max_count)
1064 max_count = info.count;
1065 has_annotated = true;
1066 if (info.targets.size () > 0
1067 && promoted.find (stmt) == promoted.end ())
1068 afdo_vpt (&gsi, info.targets, false);
1072 if (!has_annotated)
1073 return false;
1075 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1076 afdo_source_profile->mark_annotated (gimple_location (gsi_stmt (gsi)));
1077 for (gphi_iterator gpi = gsi_start_phis (bb);
1078 !gsi_end_p (gpi);
1079 gsi_next (&gpi))
1081 gphi *phi = gpi.phi ();
1082 size_t i;
1083 for (i = 0; i < gimple_phi_num_args (phi); i++)
1084 afdo_source_profile->mark_annotated (gimple_phi_arg_location (phi, i));
1086 FOR_EACH_EDGE (e, ei, bb->succs)
1087 afdo_source_profile->mark_annotated (e->goto_locus);
1089 bb->count = max_count;
1090 return true;
1093 /* BB1 and BB2 are in an equivalent class iff:
1094 1. BB1 dominates BB2.
1095 2. BB2 post-dominates BB1.
1096 3. BB1 and BB2 are in the same loop nest.
1097 This function finds the equivalent class for each basic block, and
1098 stores a pointer to the first BB in its equivalent class. Meanwhile,
1099 set bb counts for the same equivalent class to be idenical. Update
1100 ANNOTATED_BB for the first BB in its equivalent class. */
1102 static void
1103 afdo_find_equiv_class (bb_set *annotated_bb)
1105 basic_block bb;
1107 FOR_ALL_BB_FN (bb, cfun)
1108 bb->aux = NULL;
1110 FOR_ALL_BB_FN (bb, cfun)
1112 vec<basic_block> dom_bbs;
1113 basic_block bb1;
1114 int i;
1116 if (bb->aux != NULL)
1117 continue;
1118 bb->aux = bb;
1119 dom_bbs = get_dominated_by (CDI_DOMINATORS, bb);
1120 FOR_EACH_VEC_ELT (dom_bbs, i, bb1)
1121 if (bb1->aux == NULL && dominated_by_p (CDI_POST_DOMINATORS, bb, bb1)
1122 && bb1->loop_father == bb->loop_father)
1124 bb1->aux = bb;
1125 if (bb1->count > bb->count && is_bb_annotated (bb1, *annotated_bb))
1127 bb->count = bb1->count;
1128 set_bb_annotated (bb, annotated_bb);
1131 dom_bbs = get_dominated_by (CDI_POST_DOMINATORS, bb);
1132 FOR_EACH_VEC_ELT (dom_bbs, i, bb1)
1133 if (bb1->aux == NULL && dominated_by_p (CDI_DOMINATORS, bb, bb1)
1134 && bb1->loop_father == bb->loop_father)
1136 bb1->aux = bb;
1137 if (bb1->count > bb->count && is_bb_annotated (bb1, *annotated_bb))
1139 bb->count = bb1->count;
1140 set_bb_annotated (bb, annotated_bb);
1146 /* If a basic block's count is known, and only one of its in/out edges' count
1147 is unknown, its count can be calculated. Meanwhile, if all of the in/out
1148 edges' counts are known, then the basic block's unknown count can also be
1149 calculated.
1150 IS_SUCC is true if out edges of a basic blocks are examined.
1151 Update ANNOTATED_BB and ANNOTATED_EDGE accordingly.
1152 Return TRUE if any basic block/edge count is changed. */
1154 static bool
1155 afdo_propagate_edge (bool is_succ, bb_set *annotated_bb,
1156 edge_set *annotated_edge)
1158 basic_block bb;
1159 bool changed = false;
1161 FOR_EACH_BB_FN (bb, cfun)
1163 edge e, unknown_edge = NULL;
1164 edge_iterator ei;
1165 int num_unknown_edge = 0;
1166 gcov_type total_known_count = 0;
1168 FOR_EACH_EDGE (e, ei, is_succ ? bb->succs : bb->preds)
1169 if (!is_edge_annotated (e, *annotated_edge))
1170 num_unknown_edge++, unknown_edge = e;
1171 else
1172 total_known_count += e->count;
1174 if (num_unknown_edge == 0)
1176 if (total_known_count > bb->count)
1178 bb->count = total_known_count;
1179 changed = true;
1181 if (!is_bb_annotated (bb, *annotated_bb))
1183 set_bb_annotated (bb, annotated_bb);
1184 changed = true;
1187 else if (num_unknown_edge == 1 && is_bb_annotated (bb, *annotated_bb))
1189 if (bb->count >= total_known_count)
1190 unknown_edge->count = bb->count - total_known_count;
1191 else
1192 unknown_edge->count = 0;
1193 set_edge_annotated (unknown_edge, annotated_edge);
1194 changed = true;
1197 return changed;
1200 /* Special propagation for circuit expressions. Because GCC translates
1201 control flow into data flow for circuit expressions. E.g.
1202 BB1:
1203 if (a && b)
1205 else
1208 will be translated into:
1210 BB1:
1211 if (a)
1212 goto BB.t1
1213 else
1214 goto BB.t3
1215 BB.t1:
1216 if (b)
1217 goto BB.t2
1218 else
1219 goto BB.t3
1220 BB.t2:
1221 goto BB.t3
1222 BB.t3:
1223 tmp = PHI (0 (BB1), 0 (BB.t1), 1 (BB.t2)
1224 if (tmp)
1225 goto BB2
1226 else
1227 goto BB3
1229 In this case, we need to propagate through PHI to determine the edge
1230 count of BB1->BB.t1, BB.t1->BB.t2.
1231 Update ANNOTATED_EDGE accordingly. */
1233 static void
1234 afdo_propagate_circuit (const bb_set &annotated_bb, edge_set *annotated_edge)
1236 basic_block bb;
1237 FOR_ALL_BB_FN (bb, cfun)
1239 gimple def_stmt;
1240 tree cmp_rhs, cmp_lhs;
1241 gimple cmp_stmt = last_stmt (bb);
1242 edge e;
1243 edge_iterator ei;
1245 if (!cmp_stmt || gimple_code (cmp_stmt) != GIMPLE_COND)
1246 continue;
1247 cmp_rhs = gimple_cond_rhs (cmp_stmt);
1248 cmp_lhs = gimple_cond_lhs (cmp_stmt);
1249 if (!TREE_CONSTANT (cmp_rhs)
1250 || !(integer_zerop (cmp_rhs) || integer_onep (cmp_rhs)))
1251 continue;
1252 if (TREE_CODE (cmp_lhs) != SSA_NAME)
1253 continue;
1254 if (!is_bb_annotated (bb, annotated_bb))
1255 continue;
1256 def_stmt = SSA_NAME_DEF_STMT (cmp_lhs);
1257 while (def_stmt && gimple_code (def_stmt) == GIMPLE_ASSIGN
1258 && gimple_assign_single_p (def_stmt)
1259 && TREE_CODE (gimple_assign_rhs1 (def_stmt)) == SSA_NAME)
1260 def_stmt = SSA_NAME_DEF_STMT (gimple_assign_rhs1 (def_stmt));
1261 if (!def_stmt)
1262 continue;
1263 gphi *phi_stmt = dyn_cast <gphi *> (def_stmt);
1264 if (!phi_stmt)
1265 continue;
1266 FOR_EACH_EDGE (e, ei, bb->succs)
1268 unsigned i, total = 0;
1269 edge only_one;
1270 bool check_value_one = (((integer_onep (cmp_rhs))
1271 ^ (gimple_cond_code (cmp_stmt) == EQ_EXPR))
1272 ^ ((e->flags & EDGE_TRUE_VALUE) != 0));
1273 if (!is_edge_annotated (e, *annotated_edge))
1274 continue;
1275 for (i = 0; i < gimple_phi_num_args (phi_stmt); i++)
1277 tree val = gimple_phi_arg_def (phi_stmt, i);
1278 edge ep = gimple_phi_arg_edge (phi_stmt, i);
1280 if (!TREE_CONSTANT (val)
1281 || !(integer_zerop (val) || integer_onep (val)))
1282 continue;
1283 if (check_value_one ^ integer_onep (val))
1284 continue;
1285 total++;
1286 only_one = ep;
1287 if (e->probability == 0 && !is_edge_annotated (ep, *annotated_edge))
1289 ep->probability = 0;
1290 ep->count = 0;
1291 set_edge_annotated (ep, annotated_edge);
1294 if (total == 1 && !is_edge_annotated (only_one, *annotated_edge))
1296 only_one->probability = e->probability;
1297 only_one->count = e->count;
1298 set_edge_annotated (only_one, annotated_edge);
1304 /* Propagate the basic block count and edge count on the control flow
1305 graph. We do the propagation iteratively until stablize. */
1307 static void
1308 afdo_propagate (bb_set *annotated_bb, edge_set *annotated_edge)
1310 basic_block bb;
1311 bool changed = true;
1312 int i = 0;
1314 FOR_ALL_BB_FN (bb, cfun)
1316 bb->count = ((basic_block)bb->aux)->count;
1317 if (is_bb_annotated ((const basic_block)bb->aux, *annotated_bb))
1318 set_bb_annotated (bb, annotated_bb);
1321 while (changed && i++ < 10)
1323 changed = false;
1325 if (afdo_propagate_edge (true, annotated_bb, annotated_edge))
1326 changed = true;
1327 if (afdo_propagate_edge (false, annotated_bb, annotated_edge))
1328 changed = true;
1329 afdo_propagate_circuit (*annotated_bb, annotated_edge);
1333 /* Propagate counts on control flow graph and calculate branch
1334 probabilities. */
1336 static void
1337 afdo_calculate_branch_prob (bb_set *annotated_bb, edge_set *annotated_edge)
1339 basic_block bb;
1340 bool has_sample = false;
1342 FOR_EACH_BB_FN (bb, cfun)
1344 if (bb->count > 0)
1346 has_sample = true;
1347 break;
1351 if (!has_sample)
1352 return;
1354 calculate_dominance_info (CDI_POST_DOMINATORS);
1355 calculate_dominance_info (CDI_DOMINATORS);
1356 loop_optimizer_init (0);
1358 afdo_find_equiv_class (annotated_bb);
1359 afdo_propagate (annotated_bb, annotated_edge);
1361 FOR_EACH_BB_FN (bb, cfun)
1363 edge e;
1364 edge_iterator ei;
1365 int num_unknown_succ = 0;
1366 gcov_type total_count = 0;
1368 FOR_EACH_EDGE (e, ei, bb->succs)
1370 if (!is_edge_annotated (e, *annotated_edge))
1371 num_unknown_succ++;
1372 else
1373 total_count += e->count;
1375 if (num_unknown_succ == 0 && total_count > 0)
1377 FOR_EACH_EDGE (e, ei, bb->succs)
1378 e->probability = (double)e->count * REG_BR_PROB_BASE / total_count;
1381 FOR_ALL_BB_FN (bb, cfun)
1383 edge e;
1384 edge_iterator ei;
1386 FOR_EACH_EDGE (e, ei, bb->succs)
1387 e->count = (double)bb->count * e->probability / REG_BR_PROB_BASE;
1388 bb->aux = NULL;
1391 loop_optimizer_finalize ();
1392 free_dominance_info (CDI_DOMINATORS);
1393 free_dominance_info (CDI_POST_DOMINATORS);
1396 /* Perform value profile transformation using AutoFDO profile. Add the
1397 promoted stmts to PROMOTED_STMTS. Return TRUE if there is any
1398 indirect call promoted. */
1400 static bool
1401 afdo_vpt_for_early_inline (stmt_set *promoted_stmts)
1403 basic_block bb;
1404 if (afdo_source_profile->get_function_instance_by_decl (
1405 current_function_decl) == NULL)
1406 return false;
1408 compute_inline_parameters (cgraph_node::get (current_function_decl), true);
1410 bool has_vpt = false;
1411 FOR_EACH_BB_FN (bb, cfun)
1413 if (!has_indirect_call (bb))
1414 continue;
1415 gimple_stmt_iterator gsi;
1417 gcov_type bb_count = 0;
1418 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1420 count_info info;
1421 gimple stmt = gsi_stmt (gsi);
1422 if (afdo_source_profile->get_count_info (stmt, &info))
1423 bb_count = MAX (bb_count, info.count);
1426 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1428 gcall *stmt = dyn_cast <gcall *> (gsi_stmt (gsi));
1429 /* IC_promotion and early_inline_2 is done in multiple iterations.
1430 No need to promoted the stmt if its in promoted_stmts (means
1431 it is already been promoted in the previous iterations). */
1432 if ((!stmt) || gimple_call_fn (stmt) == NULL
1433 || TREE_CODE (gimple_call_fn (stmt)) == FUNCTION_DECL
1434 || promoted_stmts->find (stmt) != promoted_stmts->end ())
1435 continue;
1437 count_info info;
1438 afdo_source_profile->get_count_info (stmt, &info);
1439 info.count = bb_count;
1440 if (afdo_source_profile->update_inlined_ind_target (stmt, &info))
1442 /* Promote the indirect call and update the promoted_stmts. */
1443 promoted_stmts->insert (stmt);
1444 afdo_vpt (&gsi, info.targets, true);
1445 has_vpt = true;
1450 if (has_vpt)
1452 optimize_inline_calls (current_function_decl);
1453 return true;
1456 return false;
1459 /* Annotate auto profile to the control flow graph. Do not annotate value
1460 profile for stmts in PROMOTED_STMTS. */
1462 static void
1463 afdo_annotate_cfg (const stmt_set &promoted_stmts)
1465 basic_block bb;
1466 bb_set annotated_bb;
1467 edge_set annotated_edge;
1468 const function_instance *s
1469 = afdo_source_profile->get_function_instance_by_decl (
1470 current_function_decl);
1472 if (s == NULL)
1473 return;
1474 cgraph_node::get (current_function_decl)->count = s->head_count ();
1475 ENTRY_BLOCK_PTR_FOR_FN (cfun)->count = s->head_count ();
1476 gcov_type max_count = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count;
1478 FOR_EACH_BB_FN (bb, cfun)
1480 edge e;
1481 edge_iterator ei;
1483 bb->count = 0;
1484 FOR_EACH_EDGE (e, ei, bb->succs)
1485 e->count = 0;
1487 if (afdo_set_bb_count (bb, promoted_stmts))
1488 set_bb_annotated (bb, &annotated_bb);
1489 if (bb->count > max_count)
1490 max_count = bb->count;
1492 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count
1493 > ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb->count)
1495 ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb->count
1496 = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count;
1497 set_bb_annotated (ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb, &annotated_bb);
1499 if (ENTRY_BLOCK_PTR_FOR_FN (cfun)->count
1500 > EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb->count)
1502 EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb->count
1503 = ENTRY_BLOCK_PTR_FOR_FN (cfun)->count;
1504 set_bb_annotated (EXIT_BLOCK_PTR_FOR_FN (cfun)->prev_bb, &annotated_bb);
1506 afdo_source_profile->mark_annotated (
1507 DECL_SOURCE_LOCATION (current_function_decl));
1508 afdo_source_profile->mark_annotated (cfun->function_start_locus);
1509 afdo_source_profile->mark_annotated (cfun->function_end_locus);
1510 if (max_count > 0)
1512 afdo_calculate_branch_prob (&annotated_bb, &annotated_edge);
1513 counts_to_freqs ();
1514 profile_status_for_fn (cfun) = PROFILE_READ;
1516 if (flag_value_profile_transformations)
1518 gimple_value_profile_transformations ();
1519 free_dominance_info (CDI_DOMINATORS);
1520 free_dominance_info (CDI_POST_DOMINATORS);
1521 update_ssa (TODO_update_ssa);
1525 /* Wrapper function to invoke early inliner. */
1527 static void
1528 early_inline ()
1530 compute_inline_parameters (cgraph_node::get (current_function_decl), true);
1531 unsigned todo = early_inliner (cfun);
1532 if (todo & TODO_update_ssa_any)
1533 update_ssa (TODO_update_ssa);
1536 /* Use AutoFDO profile to annoate the control flow graph.
1537 Return the todo flag. */
1539 static unsigned int
1540 auto_profile (void)
1542 struct cgraph_node *node;
1544 if (symtab->state == FINISHED)
1545 return 0;
1547 init_node_map (true);
1548 profile_info = autofdo::afdo_profile_info;
1550 FOR_EACH_FUNCTION (node)
1552 if (!gimple_has_body_p (node->decl))
1553 continue;
1555 /* Don't profile functions produced for builtin stuff. */
1556 if (DECL_SOURCE_LOCATION (node->decl) == BUILTINS_LOCATION)
1557 continue;
1559 push_cfun (DECL_STRUCT_FUNCTION (node->decl));
1561 /* First do indirect call promotion and early inline to make the
1562 IR match the profiled binary before actual annotation.
1564 This is needed because an indirect call might have been promoted
1565 and inlined in the profiled binary. If we do not promote and
1566 inline these indirect calls before annotation, the profile for
1567 these promoted functions will be lost.
1569 e.g. foo() --indirect_call--> bar()
1570 In profiled binary, the callsite is promoted and inlined, making
1571 the profile look like:
1573 foo: {
1574 loc_foo_1: count_1
1575 bar@loc_foo_2: {
1576 loc_bar_1: count_2
1577 loc_bar_2: count_3
1581 Before AutoFDO pass, loc_foo_2 is not promoted thus not inlined.
1582 If we perform annotation on it, the profile inside bar@loc_foo2
1583 will be wasted.
1585 To avoid this, we promote loc_foo_2 and inline the promoted bar
1586 function before annotation, so the profile inside bar@loc_foo2
1587 will be useful. */
1588 autofdo::stmt_set promoted_stmts;
1589 for (int i = 0; i < PARAM_VALUE (PARAM_EARLY_INLINER_MAX_ITERATIONS); i++)
1591 if (!flag_value_profile_transformations
1592 || !autofdo::afdo_vpt_for_early_inline (&promoted_stmts))
1593 break;
1594 early_inline ();
1597 early_inline ();
1598 autofdo::afdo_annotate_cfg (promoted_stmts);
1599 compute_function_frequency ();
1601 /* Local pure-const may imply need to fixup the cfg. */
1602 if (execute_fixup_cfg () & TODO_cleanup_cfg)
1603 cleanup_tree_cfg ();
1605 free_dominance_info (CDI_DOMINATORS);
1606 free_dominance_info (CDI_POST_DOMINATORS);
1607 cgraph_edge::rebuild_edges ();
1608 compute_inline_parameters (cgraph_node::get (current_function_decl), true);
1609 pop_cfun ();
1612 return TODO_rebuild_cgraph_edges;
1614 } /* namespace autofdo. */
1616 /* Read the profile from the profile data file. */
1618 void
1619 read_autofdo_file (void)
1621 if (auto_profile_file == NULL)
1622 auto_profile_file = DEFAULT_AUTO_PROFILE_FILE;
1624 autofdo::afdo_profile_info = (struct gcov_ctr_summary *)xcalloc (
1625 1, sizeof (struct gcov_ctr_summary));
1626 autofdo::afdo_profile_info->runs = 1;
1627 autofdo::afdo_profile_info->sum_max = 0;
1628 autofdo::afdo_profile_info->sum_all = 0;
1630 /* Read the profile from the profile file. */
1631 autofdo::read_profile ();
1634 /* Free the resources. */
1636 void
1637 end_auto_profile (void)
1639 delete autofdo::afdo_source_profile;
1640 delete autofdo::afdo_string_table;
1641 profile_info = NULL;
1644 /* Returns TRUE if EDGE is hot enough to be inlined early. */
1646 bool
1647 afdo_callsite_hot_enough_for_early_inline (struct cgraph_edge *edge)
1649 gcov_type count
1650 = autofdo::afdo_source_profile->get_callsite_total_count (edge);
1652 if (count > 0)
1654 bool is_hot;
1655 const struct gcov_ctr_summary *saved_profile_info = profile_info;
1656 /* At early inline stage, profile_info is not set yet. We need to
1657 temporarily set it to afdo_profile_info to calculate hotness. */
1658 profile_info = autofdo::afdo_profile_info;
1659 is_hot = maybe_hot_count_p (NULL, count);
1660 profile_info = saved_profile_info;
1661 return is_hot;
1664 return false;
1667 namespace
1670 const pass_data pass_data_ipa_auto_profile = {
1671 SIMPLE_IPA_PASS, "afdo", /* name */
1672 OPTGROUP_NONE, /* optinfo_flags */
1673 TV_IPA_AUTOFDO, /* tv_id */
1674 0, /* properties_required */
1675 0, /* properties_provided */
1676 0, /* properties_destroyed */
1677 0, /* todo_flags_start */
1678 0, /* todo_flags_finish */
1681 class pass_ipa_auto_profile : public simple_ipa_opt_pass
1683 public:
1684 pass_ipa_auto_profile (gcc::context *ctxt)
1685 : simple_ipa_opt_pass (pass_data_ipa_auto_profile, ctxt)
1689 /* opt_pass methods: */
1690 virtual bool
1691 gate (function *)
1693 return flag_auto_profile;
1695 virtual unsigned int
1696 execute (function *)
1698 return autofdo::auto_profile ();
1700 }; // class pass_ipa_auto_profile
1702 } // anon namespace
1704 simple_ipa_opt_pass *
1705 make_pass_ipa_auto_profile (gcc::context *ctxt)
1707 return new pass_ipa_auto_profile (ctxt);