metric.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807
  1. # SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause)
  2. """Parse or generate representations of perf metrics."""
  3. import ast
  4. import decimal
  5. import json
  6. import os
  7. import re
  8. from enum import Enum
  9. from typing import Dict, List, Optional, Set, Tuple, Union
  10. all_pmus = set()
  11. all_events = set()
  12. experimental_events = set()
  13. all_events_all_models = set()
  14. def LoadEvents(directory: str) -> None:
  15. """Populate a global set of all known events for the purpose of validating Event names"""
  16. global all_pmus
  17. global all_events
  18. global experimental_events
  19. global all_events_all_models
  20. all_events = {
  21. "context\\-switches",
  22. "cpu\\-cycles",
  23. "cycles",
  24. "duration_time",
  25. "instructions",
  26. "l2_itlb_misses",
  27. }
  28. for file in os.listdir(os.fsencode(directory)):
  29. filename = os.fsdecode(file)
  30. if filename.endswith(".json"):
  31. try:
  32. for x in json.load(open(f"{directory}/{filename}")):
  33. if "Unit" in x:
  34. all_pmus.add(x["Unit"])
  35. if "EventName" in x:
  36. all_events.add(x["EventName"])
  37. if "Experimental" in x and x["Experimental"] == "1":
  38. experimental_events.add(x["EventName"])
  39. elif "ArchStdEvent" in x:
  40. all_events.add(x["ArchStdEvent"])
  41. except json.decoder.JSONDecodeError:
  42. # The generated directory may be the same as the input, which
  43. # causes partial json files. Ignore errors.
  44. pass
  45. all_events_all_models = all_events.copy()
  46. for root, dirs, files in os.walk(directory + ".."):
  47. for filename in files:
  48. if filename.endswith(".json"):
  49. try:
  50. for x in json.load(open(f"{root}/{filename}")):
  51. if "EventName" in x:
  52. all_events_all_models.add(x["EventName"])
  53. elif "ArchStdEvent" in x:
  54. all_events_all_models.add(x["ArchStdEvent"])
  55. except json.decoder.JSONDecodeError:
  56. # The generated directory may be the same as the input, which
  57. # causes partial json files. Ignore errors.
  58. pass
  59. def CheckPmu(name: str) -> bool:
  60. return name in all_pmus
  61. def CheckEvent(name: str) -> bool:
  62. """Check the event name exists in the set of all loaded events"""
  63. global all_events
  64. if len(all_events) == 0:
  65. # No events loaded so assume any event is good.
  66. return True
  67. if ':' in name:
  68. # Remove trailing modifier.
  69. name = name[:name.find(':')]
  70. elif '/' in name:
  71. # Name could begin with a PMU or an event, for now assume it is good.
  72. return True
  73. return name in all_events
  74. def CheckEveryEvent(*names: str) -> None:
  75. """Check all the events exist in at least one json file"""
  76. global all_events_all_models
  77. if len(all_events_all_models) == 0:
  78. assert len(names) == 1, f"Cannot determine valid events in {names}"
  79. # No events loaded so assume any event is good.
  80. return
  81. for name in names:
  82. # Remove trailing modifier.
  83. if ':' in name:
  84. name = name[:name.find(':')]
  85. elif '/' in name:
  86. name = name[:name.find('/')]
  87. if any([name.startswith(x) for x in ['amd', 'arm', 'cpu', 'msr', 'power']]):
  88. continue
  89. if name not in all_events_all_models:
  90. raise Exception(f"Is {name} a named json event?")
  91. def IsExperimentalEvent(name: str) -> bool:
  92. global experimental_events
  93. if ':' in name:
  94. # Remove trailing modifier.
  95. name = name[:name.find(':')]
  96. elif '/' in name:
  97. # Name could begin with a PMU or an event, for now assume it is not experimental.
  98. return False
  99. return name in experimental_events
  100. class MetricConstraint(Enum):
  101. GROUPED_EVENTS = 0
  102. NO_GROUP_EVENTS = 1
  103. NO_GROUP_EVENTS_NMI = 2
  104. NO_GROUP_EVENTS_SMT = 3
  105. class Expression:
  106. """Abstract base class of elements in a metric expression."""
  107. def ToPerfJson(self) -> str:
  108. """Returns a perf json file encoded representation."""
  109. raise NotImplementedError()
  110. def ToPython(self) -> str:
  111. """Returns a python expr parseable representation."""
  112. raise NotImplementedError()
  113. def Simplify(self):
  114. """Returns a simplified version of self."""
  115. raise NotImplementedError()
  116. def HasExperimentalEvents(self) -> bool:
  117. """Are experimental events used in the expression?"""
  118. raise NotImplementedError()
  119. def Equals(self, other) -> bool:
  120. """Returns true when two expressions are the same."""
  121. raise NotImplementedError()
  122. def Substitute(self, name: str, expression: 'Expression') -> 'Expression':
  123. raise NotImplementedError()
  124. def __str__(self) -> str:
  125. return self.ToPerfJson()
  126. def __or__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  127. return Operator('|', self, other)
  128. def __ror__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  129. return Operator('|', other, self)
  130. def __xor__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  131. return Operator('^', self, other)
  132. def __and__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  133. return Operator('&', self, other)
  134. def __rand__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  135. return Operator('&', other, self)
  136. def __lt__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  137. return Operator('<', self, other)
  138. def __gt__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  139. return Operator('>', self, other)
  140. def __add__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  141. return Operator('+', self, other)
  142. def __radd__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  143. return Operator('+', other, self)
  144. def __sub__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  145. return Operator('-', self, other)
  146. def __rsub__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  147. return Operator('-', other, self)
  148. def __mul__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  149. return Operator('*', self, other)
  150. def __rmul__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  151. return Operator('*', other, self)
  152. def __truediv__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  153. return Operator('/', self, other)
  154. def __rtruediv__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  155. return Operator('/', other, self)
  156. def __mod__(self, other: Union[int, float, 'Expression']) -> 'Operator':
  157. return Operator('%', self, other)
  158. def _Constify(val: Union[bool, int, float, Expression]) -> Expression:
  159. """Used to ensure that the nodes in the expression tree are all Expression."""
  160. if isinstance(val, bool):
  161. return Constant(1 if val else 0)
  162. if isinstance(val, (int, float)):
  163. return Constant(val)
  164. return val
  165. # Simple lookup for operator precedence, used to avoid unnecessary
  166. # brackets. Precedence matches that of the simple expression parser
  167. # but differs from python where comparisons are lower precedence than
  168. # the bitwise &, ^, | but not the logical versions that the expression
  169. # parser doesn't have.
  170. _PRECEDENCE = {
  171. '|': 0,
  172. '^': 1,
  173. '&': 2,
  174. '<': 3,
  175. '>': 3,
  176. '+': 4,
  177. '-': 4,
  178. '*': 5,
  179. '/': 5,
  180. '%': 5,
  181. }
  182. class Operator(Expression):
  183. """Represents a binary operator in the parse tree."""
  184. def __init__(self, operator: str, lhs: Union[int, float, Expression],
  185. rhs: Union[int, float, Expression]):
  186. self.operator = operator
  187. self.lhs = _Constify(lhs)
  188. self.rhs = _Constify(rhs)
  189. def Bracket(self,
  190. other: Expression,
  191. other_str: str,
  192. rhs: bool = False) -> str:
  193. """If necessary brackets the given other value.
  194. If ``other`` is an operator then a bracket is necessary when
  195. this/self operator has higher precedence. Consider: '(a + b) * c',
  196. ``other_str`` will be 'a + b'. A bracket is necessary as without
  197. the bracket 'a + b * c' will evaluate 'b * c' first. However, '(a
  198. * b) + c' doesn't need a bracket as 'a * b' will always be
  199. evaluated first. For 'a / (b * c)' (ie the same precedence level
  200. operations) then we add the bracket to best match the original
  201. input, but not for '(a / b) * c' where the bracket is unnecessary.
  202. Args:
  203. other (Expression): is a lhs or rhs operator
  204. other_str (str): ``other`` in the appropriate string form
  205. rhs (bool): is ``other`` on the RHS
  206. Returns:
  207. str: possibly bracketed other_str
  208. """
  209. if isinstance(other, Operator):
  210. if _PRECEDENCE.get(self.operator, -1) > _PRECEDENCE.get(
  211. other.operator, -1):
  212. return f'({other_str})'
  213. if rhs and _PRECEDENCE.get(self.operator, -1) == _PRECEDENCE.get(
  214. other.operator, -1):
  215. return f'({other_str})'
  216. return other_str
  217. def ToPerfJson(self):
  218. return (f'{self.Bracket(self.lhs, self.lhs.ToPerfJson())} {self.operator} '
  219. f'{self.Bracket(self.rhs, self.rhs.ToPerfJson(), True)}')
  220. def ToPython(self):
  221. return (f'{self.Bracket(self.lhs, self.lhs.ToPython())} {self.operator} '
  222. f'{self.Bracket(self.rhs, self.rhs.ToPython(), True)}')
  223. def Simplify(self) -> Expression:
  224. lhs = self.lhs.Simplify()
  225. rhs = self.rhs.Simplify()
  226. if isinstance(lhs, Constant) and isinstance(rhs, Constant):
  227. return Constant(ast.literal_eval(lhs + self.operator + rhs))
  228. if isinstance(self.lhs, Constant):
  229. if self.operator in ('+', '|') and lhs.value == '0':
  230. return rhs
  231. # Simplify multiplication by 0 except for the slot event which
  232. # is deliberately introduced using this pattern.
  233. if self.operator == '*' and lhs.value == '0' and (
  234. not isinstance(rhs, Event) or 'slots' not in rhs.name.lower()):
  235. return Constant(0)
  236. if self.operator == '*' and lhs.value == '1':
  237. return rhs
  238. if isinstance(rhs, Constant):
  239. if self.operator in ('+', '|') and rhs.value == '0':
  240. return lhs
  241. if self.operator == '*' and rhs.value == '0':
  242. return Constant(0)
  243. if self.operator == '*' and self.rhs.value == '1':
  244. return lhs
  245. return Operator(self.operator, lhs, rhs)
  246. def HasExperimentalEvents(self) -> bool:
  247. return self.lhs.HasExperimentalEvents() or self.rhs.HasExperimentalEvents()
  248. def Equals(self, other: Expression) -> bool:
  249. if isinstance(other, Operator):
  250. return self.operator == other.operator and self.lhs.Equals(
  251. other.lhs) and self.rhs.Equals(other.rhs)
  252. return False
  253. def Substitute(self, name: str, expression: Expression) -> Expression:
  254. if self.Equals(expression):
  255. return Event(name)
  256. lhs = self.lhs.Substitute(name, expression)
  257. rhs = None
  258. if self.rhs:
  259. rhs = self.rhs.Substitute(name, expression)
  260. return Operator(self.operator, lhs, rhs)
  261. class Select(Expression):
  262. """Represents a select ternary in the parse tree."""
  263. def __init__(self, true_val: Union[int, float, Expression],
  264. cond: Union[int, float, Expression],
  265. false_val: Union[int, float, Expression]):
  266. self.true_val = _Constify(true_val)
  267. self.cond = _Constify(cond)
  268. self.false_val = _Constify(false_val)
  269. def ToPerfJson(self):
  270. true_str = self.true_val.ToPerfJson()
  271. cond_str = self.cond.ToPerfJson()
  272. false_str = self.false_val.ToPerfJson()
  273. return f'({true_str} if {cond_str} else {false_str})'
  274. def ToPython(self):
  275. return (f'Select({self.true_val.ToPython()}, {self.cond.ToPython()}, '
  276. f'{self.false_val.ToPython()})')
  277. def Simplify(self) -> Expression:
  278. cond = self.cond.Simplify()
  279. true_val = self.true_val.Simplify()
  280. false_val = self.false_val.Simplify()
  281. if isinstance(cond, Constant):
  282. return false_val if cond.value == '0' else true_val
  283. if true_val.Equals(false_val):
  284. return true_val
  285. return Select(true_val, cond, false_val)
  286. def HasExperimentalEvents(self) -> bool:
  287. return (self.cond.HasExperimentalEvents() or self.true_val.HasExperimentalEvents() or
  288. self.false_val.HasExperimentalEvents())
  289. def Equals(self, other: Expression) -> bool:
  290. if isinstance(other, Select):
  291. return self.cond.Equals(other.cond) and self.false_val.Equals(
  292. other.false_val) and self.true_val.Equals(other.true_val)
  293. return False
  294. def Substitute(self, name: str, expression: Expression) -> Expression:
  295. if self.Equals(expression):
  296. return Event(name)
  297. true_val = self.true_val.Substitute(name, expression)
  298. cond = self.cond.Substitute(name, expression)
  299. false_val = self.false_val.Substitute(name, expression)
  300. return Select(true_val, cond, false_val)
  301. class Function(Expression):
  302. """A function in an expression like min, max, d_ratio."""
  303. def __init__(self,
  304. fn: str,
  305. lhs: Union[int, float, Expression],
  306. rhs: Optional[Union[int, float, Expression]] = None):
  307. self.fn = fn
  308. self.lhs = _Constify(lhs)
  309. self.rhs = _Constify(rhs)
  310. def ToPerfJson(self):
  311. if self.rhs:
  312. return f'{self.fn}({self.lhs.ToPerfJson()}, {self.rhs.ToPerfJson()})'
  313. return f'{self.fn}({self.lhs.ToPerfJson()})'
  314. def ToPython(self):
  315. if self.rhs:
  316. return f'{self.fn}({self.lhs.ToPython()}, {self.rhs.ToPython()})'
  317. return f'{self.fn}({self.lhs.ToPython()})'
  318. def Simplify(self) -> Expression:
  319. lhs = self.lhs.Simplify()
  320. rhs = self.rhs.Simplify() if self.rhs else None
  321. if isinstance(lhs, Constant) and isinstance(rhs, Constant):
  322. if self.fn == 'd_ratio':
  323. if rhs.value == '0':
  324. return Constant(0)
  325. Constant(ast.literal_eval(f'{lhs} / {rhs}'))
  326. return Constant(ast.literal_eval(f'{self.fn}({lhs}, {rhs})'))
  327. return Function(self.fn, lhs, rhs)
  328. def HasExperimentalEvents(self) -> bool:
  329. return self.lhs.HasExperimentalEvents() or (self.rhs and self.rhs.HasExperimentalEvents())
  330. def Equals(self, other: Expression) -> bool:
  331. if isinstance(other, Function):
  332. result = self.fn == other.fn and self.lhs.Equals(other.lhs)
  333. if self.rhs:
  334. result = result and self.rhs.Equals(other.rhs)
  335. return result
  336. return False
  337. def Substitute(self, name: str, expression: Expression) -> Expression:
  338. if self.Equals(expression):
  339. return Event(name)
  340. lhs = self.lhs.Substitute(name, expression)
  341. rhs = None
  342. if self.rhs:
  343. rhs = self.rhs.Substitute(name, expression)
  344. return Function(self.fn, lhs, rhs)
  345. def _FixEscapes(s: str) -> str:
  346. s = re.sub(r'([^\\]),', r'\1\\,', s)
  347. return re.sub(r'([^\\])=', r'\1\\=', s)
  348. class Event(Expression):
  349. """An event in an expression."""
  350. def __init__(self, *args: str):
  351. error = ""
  352. CheckEveryEvent(*args)
  353. for name in args:
  354. if CheckEvent(name):
  355. self.name = _FixEscapes(name)
  356. return
  357. if error:
  358. error += " or " + name
  359. else:
  360. error = name
  361. global all_events
  362. raise Exception(f"No event {error} in:\n{all_events}")
  363. def HasExperimentalEvents(self) -> bool:
  364. return IsExperimentalEvent(self.name)
  365. def ToPerfJson(self):
  366. result = re.sub('/', '@', self.name)
  367. return result
  368. def ToPython(self):
  369. return f'Event(r"{self.name}")'
  370. def Simplify(self) -> Expression:
  371. return self
  372. def Equals(self, other: Expression) -> bool:
  373. return isinstance(other, Event) and self.name == other.name
  374. def Substitute(self, name: str, expression: Expression) -> Expression:
  375. return self
  376. class MetricRef(Expression):
  377. """A metric reference in an expression."""
  378. def __init__(self, name: str):
  379. self.name = _FixEscapes(name)
  380. def ToPerfJson(self):
  381. return self.name
  382. def ToPython(self):
  383. return f'MetricRef(r"{self.name}")'
  384. def Simplify(self) -> Expression:
  385. return self
  386. def HasExperimentalEvents(self) -> bool:
  387. return False
  388. def Equals(self, other: Expression) -> bool:
  389. return isinstance(other, MetricRef) and self.name == other.name
  390. def Substitute(self, name: str, expression: Expression) -> Expression:
  391. return self
  392. class Constant(Expression):
  393. """A constant within the expression tree."""
  394. def __init__(self, value: Union[float, str]):
  395. ctx = decimal.Context()
  396. ctx.prec = 20
  397. dec = ctx.create_decimal(repr(value) if isinstance(value, float) else value)
  398. self.value = dec.normalize().to_eng_string()
  399. self.value = self.value.replace('+', '')
  400. self.value = self.value.replace('E', 'e')
  401. def ToPerfJson(self):
  402. return self.value
  403. def ToPython(self):
  404. return f'Constant({self.value})'
  405. def Simplify(self) -> Expression:
  406. return self
  407. def HasExperimentalEvents(self) -> bool:
  408. return False
  409. def Equals(self, other: Expression) -> bool:
  410. return isinstance(other, Constant) and self.value == other.value
  411. def Substitute(self, name: str, expression: Expression) -> Expression:
  412. return self
  413. class Literal(Expression):
  414. """A runtime literal within the expression tree."""
  415. def __init__(self, value: str):
  416. self.value = value
  417. def ToPerfJson(self):
  418. return self.value
  419. def ToPython(self):
  420. return f'Literal({self.value})'
  421. def Simplify(self) -> Expression:
  422. return self
  423. def HasExperimentalEvents(self) -> bool:
  424. return False
  425. def Equals(self, other: Expression) -> bool:
  426. return isinstance(other, Literal) and self.value == other.value
  427. def Substitute(self, name: str, expression: Expression) -> Expression:
  428. return self
  429. def min(lhs: Union[int, float, Expression], rhs: Union[int, float,
  430. Expression]) -> Function:
  431. # pylint: disable=redefined-builtin
  432. # pylint: disable=invalid-name
  433. return Function('min', lhs, rhs)
  434. def max(lhs: Union[int, float, Expression], rhs: Union[int, float,
  435. Expression]) -> Function:
  436. # pylint: disable=redefined-builtin
  437. # pylint: disable=invalid-name
  438. return Function('max', lhs, rhs)
  439. def d_ratio(lhs: Union[int, float, Expression],
  440. rhs: Union[int, float, Expression]) -> Function:
  441. # pylint: disable=redefined-builtin
  442. # pylint: disable=invalid-name
  443. return Function('d_ratio', lhs, rhs)
  444. def source_count(event: Event) -> Function:
  445. # pylint: disable=redefined-builtin
  446. # pylint: disable=invalid-name
  447. return Function('source_count', event)
  448. def has_event(event: Event) -> Function:
  449. # pylint: disable=redefined-builtin
  450. # pylint: disable=invalid-name
  451. return Function('has_event', event)
  452. def strcmp_cpuid_str(cpuid: Event) -> Function:
  453. # pylint: disable=redefined-builtin
  454. # pylint: disable=invalid-name
  455. return Function('strcmp_cpuid_str', cpuid)
  456. class Metric:
  457. """An individual metric that will specifiable on the perf command line."""
  458. groups: Set[str]
  459. expr: Expression
  460. scale_unit: str
  461. constraint: MetricConstraint
  462. threshold: Optional[Expression]
  463. def __init__(self,
  464. name: str,
  465. description: str,
  466. expr: Expression,
  467. scale_unit: str,
  468. constraint: MetricConstraint = MetricConstraint.GROUPED_EVENTS,
  469. threshold: Optional[Expression] = None):
  470. self.name = name
  471. self.description = description
  472. self.expr = expr.Simplify()
  473. if self.expr.HasExperimentalEvents():
  474. self.description += " (metric should be considered experimental as it contains experimental events)."
  475. # Workraound valid_only_metric hiding certain metrics based on unit.
  476. scale_unit = scale_unit.replace('/sec', ' per sec')
  477. if scale_unit[0].isdigit():
  478. self.scale_unit = scale_unit
  479. else:
  480. self.scale_unit = f'1{scale_unit}'
  481. self.constraint = constraint
  482. self.threshold = threshold
  483. self.groups = set()
  484. def __lt__(self, other):
  485. """Sort order."""
  486. return self.name < other.name
  487. def AddToMetricGroup(self, group):
  488. """Callback used when being added to a MetricGroup."""
  489. if group.name:
  490. self.groups.add(group.name)
  491. def Flatten(self) -> Set['Metric']:
  492. """Return a leaf metric."""
  493. return set([self])
  494. def ToPerfJson(self) -> Dict[str, str]:
  495. """Return as dictionary for Json generation."""
  496. result = {
  497. 'MetricName': self.name,
  498. 'MetricGroup': ';'.join(sorted(self.groups)),
  499. 'BriefDescription': self.description,
  500. 'MetricExpr': self.expr.ToPerfJson(),
  501. 'ScaleUnit': self.scale_unit
  502. }
  503. if self.constraint != MetricConstraint.GROUPED_EVENTS:
  504. result['MetricConstraint'] = self.constraint.name
  505. if self.threshold:
  506. result['MetricThreshold'] = self.threshold.ToPerfJson()
  507. return result
  508. def ToMetricGroupDescriptions(self, root: bool = True) -> Dict[str, str]:
  509. return {}
  510. class MetricGroup:
  511. """A group of metrics.
  512. Metric groups may be specificd on the perf command line, but within
  513. the json they aren't encoded. Metrics may be in multiple groups
  514. which can facilitate arrangements similar to trees.
  515. """
  516. def __init__(self, name: str,
  517. metric_list: List[Union[Optional[Metric], Optional['MetricGroup']]],
  518. description: Optional[str] = None):
  519. self.name = name
  520. self.metric_list = []
  521. self.description = description
  522. for metric in metric_list:
  523. if metric:
  524. self.metric_list.append(metric)
  525. metric.AddToMetricGroup(self)
  526. def AddToMetricGroup(self, group):
  527. """Callback used when a MetricGroup is added into another."""
  528. for metric in self.metric_list:
  529. metric.AddToMetricGroup(group)
  530. def Flatten(self) -> Set[Metric]:
  531. """Returns a set of all leaf metrics."""
  532. result = set()
  533. for x in self.metric_list:
  534. result = result.union(x.Flatten())
  535. return result
  536. def ToPerfJson(self) -> List[Dict[str, str]]:
  537. result = []
  538. for x in sorted(self.Flatten()):
  539. result.append(x.ToPerfJson())
  540. return result
  541. def ToMetricGroupDescriptions(self, root: bool = True) -> Dict[str, str]:
  542. result = {self.name: self.description} if self.description else {}
  543. for x in self.metric_list:
  544. result.update(x.ToMetricGroupDescriptions(False))
  545. return result
  546. def __str__(self) -> str:
  547. return str(self.ToPerfJson())
  548. def JsonEncodeMetric(x: MetricGroup):
  549. class MetricJsonEncoder(json.JSONEncoder):
  550. """Special handling for Metric objects."""
  551. def default(self, o):
  552. if isinstance(o, Metric) or isinstance(o, MetricGroup):
  553. return o.ToPerfJson()
  554. return json.JSONEncoder.default(self, o)
  555. return json.dumps(x, indent=2, cls=MetricJsonEncoder)
  556. def JsonEncodeMetricGroupDescriptions(x: MetricGroup):
  557. return json.dumps(x.ToMetricGroupDescriptions(), indent=2)
  558. class _RewriteIfExpToSelect(ast.NodeTransformer):
  559. """Transformer to convert if-else nodes to Select expressions."""
  560. def visit_IfExp(self, node):
  561. # pylint: disable=invalid-name
  562. self.generic_visit(node)
  563. call = ast.Call(
  564. func=ast.Name(id='Select', ctx=ast.Load()),
  565. args=[node.body, node.test, node.orelse],
  566. keywords=[])
  567. ast.copy_location(call, node.test)
  568. return call
  569. def ParsePerfJson(orig: str) -> Expression:
  570. """A simple json metric expression decoder.
  571. Converts a json encoded metric expression by way of python's ast and
  572. eval routine. First tokens are mapped to Event calls, then
  573. accidentally converted keywords or literals are mapped to their
  574. appropriate calls. Python's ast is used to match if-else that can't
  575. be handled via operator overloading. Finally the ast is evaluated.
  576. Args:
  577. orig (str): String to parse.
  578. Returns:
  579. Expression: The parsed string.
  580. """
  581. # pylint: disable=eval-used
  582. py = orig.strip()
  583. # First try to convert everything that looks like a string (event name) into Event(r"EVENT_NAME").
  584. # This isn't very selective so is followed up by converting some unwanted conversions back again
  585. py = re.sub(r'([a-zA-Z][^-+/\* \\\(\),]*(?:\\.[^-+/\* \\\(\),]*)*)',
  586. r'Event(r"\1")', py)
  587. # If it started with a # it should have been a literal, rather than an event name
  588. py = re.sub(r'#Event\(r"([^"]*)"\)', r'Literal("#\1")', py)
  589. # Fix events wrongly broken at a ','
  590. while True:
  591. prev_py = py
  592. py = re.sub(r'Event\(r"([^"]*)"\),Event\(r"([^"]*)"\)', r'Event(r"\1,\2")', py)
  593. if py == prev_py:
  594. break
  595. # Convert accidentally converted hex constants ("0Event(r"xDEADBEEF)"") back to a constant,
  596. # but keep it wrapped in Event(), otherwise Python drops the 0x prefix and it gets interpreted as
  597. # a double by the Bison parser
  598. py = re.sub(r'0Event\(r"[xX]([0-9a-fA-F]*)"\)', r'Event("0x\1")', py)
  599. # Convert accidentally converted scientific notation constants back
  600. py = re.sub(r'([0-9]+)Event\(r"(e[0-9]*)"\)', r'\1\2', py)
  601. # Convert all the known keywords back from events to just the keyword
  602. keywords = ['if', 'else', 'min', 'max', 'd_ratio', 'source_count', 'has_event', 'strcmp_cpuid_str']
  603. for kw in keywords:
  604. py = re.sub(rf'Event\(r"{kw}"\)', kw, py)
  605. try:
  606. parsed = ast.parse(py, mode='eval')
  607. except SyntaxError as e:
  608. raise SyntaxError(f'Parsing expression:\n{orig}') from e
  609. _RewriteIfExpToSelect().visit(parsed)
  610. parsed = ast.fix_missing_locations(parsed)
  611. return _Constify(eval(compile(parsed, orig, 'eval')))
  612. def RewriteMetricsInTermsOfOthers(metrics: List[Tuple[str, str, Expression]]
  613. )-> Dict[Tuple[str, str], Expression]:
  614. """Shorten metrics by rewriting in terms of others.
  615. Args:
  616. metrics (list): pmus, metric names and their expressions.
  617. Returns:
  618. Dict: mapping from a pmu, metric name pair to a shortened expression.
  619. """
  620. updates: Dict[Tuple[str, str], Expression] = dict()
  621. for outer_pmu, outer_name, outer_expression in metrics:
  622. if outer_pmu is None:
  623. outer_pmu = 'cpu'
  624. updated = outer_expression
  625. while True:
  626. for inner_pmu, inner_name, inner_expression in metrics:
  627. if inner_pmu is None:
  628. inner_pmu = 'cpu'
  629. if inner_pmu.lower() != outer_pmu.lower():
  630. continue
  631. if inner_name.lower() == outer_name.lower():
  632. continue
  633. if (inner_pmu, inner_name) in updates:
  634. inner_expression = updates[(inner_pmu, inner_name)]
  635. updated = updated.Substitute(inner_name, inner_expression)
  636. if updated.Equals(outer_expression):
  637. break
  638. if (outer_pmu, outer_name) in updates and updated.Equals(updates[(outer_pmu, outer_name)]):
  639. break
  640. updates[(outer_pmu, outer_name)] = updated
  641. return updates