analyze_brprob.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. #!/usr/bin/env python3
  2. #
  3. # Script to analyze results of our branch prediction heuristics
  4. #
  5. # This file is part of GCC.
  6. #
  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.
  11. #
  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.
  16. #
  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/>. */
  20. #
  21. #
  22. #
  23. # This script is used to calculate two basic properties of the branch prediction
  24. # heuristics - coverage and hitrate. Coverage is number of executions
  25. # of a given branch matched by the heuristics and hitrate is probability
  26. # that once branch is predicted as taken it is really taken.
  27. #
  28. # These values are useful to determine the quality of given heuristics.
  29. # Hitrate may be directly used in predict.def.
  30. #
  31. # Usage:
  32. # Step 1: Compile and profile your program. You need to use -fprofile-generate
  33. # flag to get the profiles.
  34. # Step 2: Make a reference run of the intrumented application.
  35. # Step 3: Compile the program with collected profile and dump IPA profiles
  36. # (-fprofile-use -fdump-ipa-profile-details)
  37. # Step 4: Collect all generated dump files:
  38. # find . -name '*.profile' | xargs cat > dump_file
  39. # Step 5: Run the script:
  40. # ./analyze_brprob.py dump_file
  41. # and read results. Basically the following table is printed:
  42. #
  43. # HEURISTICS BRANCHES (REL) HITRATE COVERAGE (REL)
  44. # early return (on trees) 3 0.2% 35.83% / 93.64% 66360 0.0%
  45. # guess loop iv compare 8 0.6% 53.35% / 53.73% 11183344 0.0%
  46. # call 18 1.4% 31.95% / 69.95% 51880179 0.2%
  47. # loop guard 23 1.8% 84.13% / 84.85% 13749065956 42.2%
  48. # opcode values positive (on trees) 42 3.3% 15.71% / 84.81% 6771097902 20.8%
  49. # opcode values nonequal (on trees) 226 17.6% 72.48% / 72.84% 844753864 2.6%
  50. # loop exit 231 18.0% 86.97% / 86.98% 8952666897 27.5%
  51. # loop iterations 239 18.6% 91.10% / 91.10% 3062707264 9.4%
  52. # DS theory 281 21.9% 82.08% / 83.39% 7787264075 23.9%
  53. # no prediction 293 22.9% 46.92% / 70.70% 2293267840 7.0%
  54. # guessed loop iterations 313 24.4% 76.41% / 76.41% 10782750177 33.1%
  55. # first match 708 55.2% 82.30% / 82.31% 22489588691 69.0%
  56. # combined 1282 100.0% 79.76% / 81.75% 32570120606 100.0%
  57. #
  58. #
  59. # The heuristics called "first match" is a heuristics used by GCC branch
  60. # prediction pass and it predicts 55.2% branches correctly. As you can,
  61. # the heuristics has very good covertage (69.05%). On the other hand,
  62. # "opcode values nonequal (on trees)" heuristics has good hirate, but poor
  63. # coverage.
  64. import sys
  65. import os
  66. import re
  67. import argparse
  68. from math import *
  69. counter_aggregates = set(['combined', 'first match', 'DS theory',
  70. 'no prediction'])
  71. hot_threshold = 10
  72. def percentage(a, b):
  73. return 100.0 * a / b
  74. def average(values):
  75. return 1.0 * sum(values) / len(values)
  76. def average_cutoff(values, cut):
  77. l = len(values)
  78. skip = floor(l * cut / 2)
  79. if skip > 0:
  80. values.sort()
  81. values = values[skip:-skip]
  82. return average(values)
  83. def median(values):
  84. values.sort()
  85. return values[int(len(values) / 2)]
  86. class PredictDefFile:
  87. def __init__(self, path):
  88. self.path = path
  89. self.predictors = {}
  90. def parse_and_modify(self, heuristics, write_def_file):
  91. lines = [x.rstrip() for x in open(self.path).readlines()]
  92. p = None
  93. modified_lines = []
  94. for i, l in enumerate(lines):
  95. if l.startswith('DEF_PREDICTOR'):
  96. next_line = lines[i + 1]
  97. if l.endswith(','):
  98. l += next_line
  99. m = re.match('.*"(.*)".*', l)
  100. p = m.group(1)
  101. elif l == '':
  102. p = None
  103. if p != None:
  104. heuristic = [x for x in heuristics if x.name == p]
  105. heuristic = heuristic[0] if len(heuristic) == 1 else None
  106. m = re.match('.*HITRATE \(([^)]*)\).*', l)
  107. if (m != None):
  108. self.predictors[p] = int(m.group(1))
  109. # modify the line
  110. if heuristic != None:
  111. new_line = (l[:m.start(1)]
  112. + str(round(heuristic.get_hitrate()))
  113. + l[m.end(1):])
  114. l = new_line
  115. p = None
  116. elif 'PROB_VERY_LIKELY' in l:
  117. self.predictors[p] = 100
  118. modified_lines.append(l)
  119. # save the file
  120. if write_def_file:
  121. with open(self.path, 'w+') as f:
  122. for l in modified_lines:
  123. f.write(l + '\n')
  124. class Heuristics:
  125. def __init__(self, count, hits, fits):
  126. self.count = count
  127. self.hits = hits
  128. self.fits = fits
  129. class Summary:
  130. def __init__(self, name):
  131. self.name = name
  132. self.edges= []
  133. def branches(self):
  134. return len(self.edges)
  135. def hits(self):
  136. return sum([x.hits for x in self.edges])
  137. def fits(self):
  138. return sum([x.fits for x in self.edges])
  139. def count(self):
  140. return sum([x.count for x in self.edges])
  141. def successfull_branches(self):
  142. return len([x for x in self.edges if 2 * x.hits >= x.count])
  143. def get_hitrate(self):
  144. return 100.0 * self.hits() / self.count()
  145. def get_branch_hitrate(self):
  146. return 100.0 * self.successfull_branches() / self.branches()
  147. def count_formatted(self):
  148. v = self.count()
  149. for unit in ['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']:
  150. if v < 1000:
  151. return "%3.2f%s" % (v, unit)
  152. v /= 1000.0
  153. return "%.1f%s" % (v, 'Y')
  154. def count(self):
  155. return sum([x.count for x in self.edges])
  156. def print(self, branches_max, count_max, predict_def):
  157. # filter out most hot edges (if requested)
  158. self.edges = sorted(self.edges, reverse = True, key = lambda x: x.count)
  159. if args.coverage_threshold != None:
  160. threshold = args.coverage_threshold * self.count() / 100
  161. edges = [x for x in self.edges if x.count < threshold]
  162. if len(edges) != 0:
  163. self.edges = edges
  164. predicted_as = None
  165. if predict_def != None and self.name in predict_def.predictors:
  166. predicted_as = predict_def.predictors[self.name]
  167. print('%-40s %8i %5.1f%% %11.2f%% %7.2f%% / %6.2f%% %14i %8s %5.1f%%' %
  168. (self.name, self.branches(),
  169. percentage(self.branches(), branches_max),
  170. self.get_branch_hitrate(),
  171. self.get_hitrate(),
  172. percentage(self.fits(), self.count()),
  173. self.count(), self.count_formatted(),
  174. percentage(self.count(), count_max)), end = '')
  175. if predicted_as != None:
  176. print('%12i%% %5.1f%%' % (predicted_as,
  177. self.get_hitrate() - predicted_as), end = '')
  178. else:
  179. print(' ' * 20, end = '')
  180. # print details about the most important edges
  181. if args.coverage_threshold == None:
  182. edges = [x for x in self.edges[:100] if x.count * hot_threshold > self.count()]
  183. if args.verbose:
  184. for c in edges:
  185. r = 100.0 * c.count / self.count()
  186. print(' %.0f%%:%d' % (r, c.count), end = '')
  187. elif len(edges) > 0:
  188. print(' %0.0f%%:%d' % (100.0 * sum([x.count for x in edges]) / self.count(), len(edges)), end = '')
  189. print()
  190. class Profile:
  191. def __init__(self, filename):
  192. self.filename = filename
  193. self.heuristics = {}
  194. self.niter_vector = []
  195. def add(self, name, prediction, count, hits):
  196. if not name in self.heuristics:
  197. self.heuristics[name] = Summary(name)
  198. s = self.heuristics[name]
  199. if prediction < 50:
  200. hits = count - hits
  201. remaining = count - hits
  202. fits = max(hits, remaining)
  203. s.edges.append(Heuristics(count, hits, fits))
  204. def add_loop_niter(self, niter):
  205. if niter > 0:
  206. self.niter_vector.append(niter)
  207. def branches_max(self):
  208. return max([v.branches() for k, v in self.heuristics.items()])
  209. def count_max(self):
  210. return max([v.count() for k, v in self.heuristics.items()])
  211. def print_group(self, sorting, group_name, heuristics, predict_def):
  212. count_max = self.count_max()
  213. branches_max = self.branches_max()
  214. sorter = lambda x: x.branches()
  215. if sorting == 'branch-hitrate':
  216. sorter = lambda x: x.get_branch_hitrate()
  217. elif sorting == 'hitrate':
  218. sorter = lambda x: x.get_hitrate()
  219. elif sorting == 'coverage':
  220. sorter = lambda x: x.count
  221. elif sorting == 'name':
  222. sorter = lambda x: x.name.lower()
  223. print('%-40s %8s %6s %12s %18s %14s %8s %6s %12s %6s %s' %
  224. ('HEURISTICS', 'BRANCHES', '(REL)',
  225. 'BR. HITRATE', 'HITRATE', 'COVERAGE', 'COVERAGE', '(REL)',
  226. 'predict.def', '(REL)', 'HOT branches (>%d%%)' % hot_threshold))
  227. for h in sorted(heuristics, key = sorter):
  228. h.print(branches_max, count_max, predict_def)
  229. def dump(self, sorting):
  230. heuristics = self.heuristics.values()
  231. if len(heuristics) == 0:
  232. print('No heuristics available')
  233. return
  234. predict_def = None
  235. if args.def_file != None:
  236. predict_def = PredictDefFile(args.def_file)
  237. predict_def.parse_and_modify(heuristics, args.write_def_file)
  238. special = list(filter(lambda x: x.name in counter_aggregates,
  239. heuristics))
  240. normal = list(filter(lambda x: x.name not in counter_aggregates,
  241. heuristics))
  242. self.print_group(sorting, 'HEURISTICS', normal, predict_def)
  243. print()
  244. self.print_group(sorting, 'HEURISTIC AGGREGATES', special, predict_def)
  245. if len(self.niter_vector) > 0:
  246. print ('\nLoop count: %d' % len(self.niter_vector)),
  247. print(' avg. # of iter: %.2f' % average(self.niter_vector))
  248. print(' median # of iter: %.2f' % median(self.niter_vector))
  249. for v in [1, 5, 10, 20, 30]:
  250. cut = 0.01 * v
  251. print(' avg. (%d%% cutoff) # of iter: %.2f'
  252. % (v, average_cutoff(self.niter_vector, cut)))
  253. parser = argparse.ArgumentParser()
  254. parser.add_argument('dump_file', metavar = 'dump_file',
  255. help = 'IPA profile dump file')
  256. parser.add_argument('-s', '--sorting', dest = 'sorting',
  257. choices = ['branches', 'branch-hitrate', 'hitrate', 'coverage', 'name'],
  258. default = 'branches')
  259. parser.add_argument('-d', '--def-file', help = 'path to predict.def')
  260. parser.add_argument('-w', '--write-def-file', action = 'store_true',
  261. help = 'Modify predict.def file in order to set new numbers')
  262. parser.add_argument('-c', '--coverage-threshold', type = int,
  263. help = 'Ignore edges that have percentage coverage >= coverage-threshold')
  264. parser.add_argument('-v', '--verbose', action = 'store_true', help = 'Print verbose informations')
  265. args = parser.parse_args()
  266. profile = Profile(args.dump_file)
  267. loop_niter_str = ';; profile-based iteration count: '
  268. for l in open(args.dump_file):
  269. if l.startswith(';;heuristics;'):
  270. parts = l.strip().split(';')
  271. assert len(parts) == 8
  272. name = parts[3]
  273. prediction = float(parts[6])
  274. count = int(parts[4])
  275. hits = int(parts[5])
  276. profile.add(name, prediction, count, hits)
  277. elif l.startswith(loop_niter_str):
  278. v = int(l[len(loop_niter_str):])
  279. profile.add_loop_niter(v)
  280. profile.dump(args.sorting)