|
| 1 | +package dotty.tools.dotc |
| 2 | +package transform |
| 3 | + |
| 4 | +import core._ |
| 5 | +import Contexts.Context |
| 6 | +import Symbols._ |
| 7 | +import Flags._ |
| 8 | +import SymDenotations._ |
| 9 | + |
| 10 | +import Decorators._ |
| 11 | +import ast.Trees._ |
| 12 | +import MegaPhase._ |
| 13 | +import StdNames.nme |
| 14 | +import Names.TermName |
| 15 | +import Constants.Constant |
| 16 | + |
| 17 | + |
| 18 | +/** The phase is enabled if a -Yinstrument-... option is set. |
| 19 | + * If enabled, it counts the number of closures or allocations for each source position. |
| 20 | + * It does this by generating a call to dotty.tools.dotc.util.Stats.doRecord. |
| 21 | + */ |
| 22 | +class Instrumentation extends MiniPhase { thisPhase => |
| 23 | + import ast.tpd._ |
| 24 | + |
| 25 | + override def phaseName: String = "instrumentation" |
| 26 | + |
| 27 | + override def isEnabled(implicit ctx: Context) = |
| 28 | + ctx.settings.YinstrumentClosures.value || |
| 29 | + ctx.settings.YinstrumentAllocations.value |
| 30 | + |
| 31 | + private var consName: TermName = _ |
| 32 | + private var consEqName: TermName = _ |
| 33 | + |
| 34 | + override def prepareForUnit(tree: Tree)(implicit ctx: Context): Context = { |
| 35 | + consName = "::".toTermName |
| 36 | + consEqName = "+=".toTermName |
| 37 | + ctx |
| 38 | + } |
| 39 | + |
| 40 | + private def record(category: String, tree: Tree)(implicit ctx: Context): Tree = { |
| 41 | + val key = Literal(Constant(s"$category${tree.sourcePos.show}")) |
| 42 | + ref(defn.Stats_doRecord).appliedTo(key, Literal(Constant(1))) |
| 43 | + } |
| 44 | + |
| 45 | + override def transformApply(tree: Apply)(implicit ctx: Context): Tree = tree.fun match { |
| 46 | + case Select(nu: New, _) => |
| 47 | + cpy.Block(tree)(record(i"alloc/${nu.tpe}@", tree) :: Nil, tree) |
| 48 | + case Select(_, name) if name == consName || name == consEqName => |
| 49 | + cpy.Block(tree)(record("alloc/::", tree) :: Nil, tree) |
| 50 | + case _ => |
| 51 | + tree |
| 52 | + } |
| 53 | + |
| 54 | + override def transformBlock(tree: Block)(implicit ctx: Context): Block = tree.expr match { |
| 55 | + case _: Closure => |
| 56 | + cpy.Block(tree)(record("closure/", tree) :: tree.stats, tree.expr) |
| 57 | + case _ => |
| 58 | + tree |
| 59 | + } |
| 60 | +} |
0 commit comments