dce.nim 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2021 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Dead code elimination (=DCE) for IC.
  10. import std/[intsets, tables]
  11. when defined(nimPreviewSlimSystem):
  12. import std/assertions
  13. import ".." / [ast, options, lineinfos, types]
  14. import packed_ast, ic, bitabs
  15. type
  16. AliveSyms* = seq[IntSet]
  17. AliveContext* = object ## Purpose is to fill the 'alive' field.
  18. stack: seq[(int, TOptions, NodePos)] ## A stack for marking symbols as alive.
  19. decoder: PackedDecoder ## We need a PackedDecoder for module ID address translations.
  20. thisModule: int ## The module we're currently analysing for DCE.
  21. alive: AliveSyms ## The final result of our computation.
  22. options: TOptions
  23. compilerProcs: Table[string, (int, int32)]
  24. proc isExportedToC(c: var AliveContext; g: PackedModuleGraph; symId: int32): bool =
  25. ## "Exported to C" procs are special (these are marked with '.exportc') because these
  26. ## must not be optimized away!
  27. let symPtr = unsafeAddr g[c.thisModule].fromDisk.syms[symId]
  28. let flags = symPtr.flags
  29. # due to a bug/limitation in the lambda lifting, unused inner procs
  30. # are not transformed correctly; issue (#411). However, the whole purpose here
  31. # is to eliminate unused procs. So there is no special logic required for this case.
  32. if sfCompileTime notin flags:
  33. if ({sfExportc, sfCompilerProc} * flags != {}) or
  34. (symPtr.kind == skMethod):
  35. result = true
  36. # XXX: This used to be a condition to:
  37. # (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or
  38. if sfCompilerProc in flags:
  39. c.compilerProcs[g[c.thisModule].fromDisk.strings[symPtr.name]] = (c.thisModule, symId)
  40. template isNotGeneric(n: NodePos): bool = ithSon(tree, n, genericParamsPos).kind == nkEmpty
  41. proc followLater(c: var AliveContext; g: PackedModuleGraph; module: int; item: int32) =
  42. ## Marks a symbol 'item' as used and later in 'followNow' the symbol's body will
  43. ## be analysed.
  44. if not c.alive[module].containsOrIncl(item):
  45. var body = g[module].fromDisk.syms[item].ast
  46. if body != emptyNodeId:
  47. let opt = g[module].fromDisk.syms[item].options
  48. if g[module].fromDisk.syms[item].kind in routineKinds:
  49. body = NodeId ithSon(g[module].fromDisk.bodies, NodePos body, bodyPos)
  50. c.stack.add((module, opt, NodePos(body)))
  51. when false:
  52. let nid = g[module].fromDisk.syms[item].name
  53. if nid != LitId(0):
  54. let name = g[module].fromDisk.strings[nid]
  55. if name in ["nimFrame", "callDepthLimitReached"]:
  56. echo "I was called! ", name, " body exists: ", body != emptyNodeId, " ", module, " ", item
  57. proc requestCompilerProc(c: var AliveContext; g: PackedModuleGraph; name: string) =
  58. let (module, item) = c.compilerProcs[name]
  59. followLater(c, g, module, item)
  60. proc loadTypeKind(t: PackedItemId; c: AliveContext; g: PackedModuleGraph; toSkip: set[TTypeKind]): TTypeKind =
  61. template kind(t: ItemId): TTypeKind = g[t.module].fromDisk.types[t.item].kind
  62. var t2 = translateId(t, g, c.thisModule, c.decoder.config)
  63. result = t2.kind
  64. while result in toSkip:
  65. t2 = translateId(g[t2.module].fromDisk.types[t2.item].types[^1], g, t2.module, c.decoder.config)
  66. result = t2.kind
  67. proc rangeCheckAnalysis(c: var AliveContext; g: PackedModuleGraph; tree: PackedTree; n: NodePos) =
  68. ## Replicates the logic of `ccgexprs.genRangeChck`.
  69. ## XXX Refactor so that the duplicated logic is avoided. However, for now it's not clear
  70. ## the approach has enough merit.
  71. var dest = loadTypeKind(n.typ, c, g, abstractVar)
  72. if optRangeCheck notin c.options or dest in {tyUInt..tyUInt64}:
  73. discard "no need to generate a check because it was disabled"
  74. else:
  75. let n0t = loadTypeKind(n.firstSon.typ, c, g, {})
  76. if n0t in {tyUInt, tyUInt64}:
  77. c.requestCompilerProc(g, "raiseRangeErrorNoArgs")
  78. else:
  79. let raiser =
  80. case loadTypeKind(n.typ, c, g, abstractVarRange)
  81. of tyUInt..tyUInt64, tyChar: "raiseRangeErrorU"
  82. of tyFloat..tyFloat128: "raiseRangeErrorF"
  83. else: "raiseRangeErrorI"
  84. c.requestCompilerProc(g, raiser)
  85. proc aliveCode(c: var AliveContext; g: PackedModuleGraph; tree: PackedTree; n: NodePos) =
  86. ## Marks the symbols we encounter when we traverse the AST at `tree[n]` as alive, unless
  87. ## it is purely in a declarative context (type section etc.).
  88. case n.kind
  89. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit:
  90. discard "ignore non-sym atoms"
  91. of nkSym:
  92. # This symbol is alive and everything its body references.
  93. followLater(c, g, c.thisModule, n.operand)
  94. of nkModuleRef:
  95. let (n1, n2) = sons2(tree, n)
  96. assert n1.kind == nkInt32Lit
  97. assert n2.kind == nkInt32Lit
  98. let m = n1.litId
  99. let item = n2.operand
  100. let otherModule = toFileIndexCached(c.decoder, g, c.thisModule, m).int
  101. followLater(c, g, otherModule, item)
  102. of nkMacroDef, nkTemplateDef, nkTypeSection, nkTypeOfExpr,
  103. nkCommentStmt, nkIncludeStmt,
  104. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  105. nkFromStmt, nkStaticStmt:
  106. discard
  107. of nkVarSection, nkLetSection, nkConstSection:
  108. # XXX ignore the defining local variable name?
  109. for son in sonsReadonly(tree, n):
  110. aliveCode(c, g, tree, son)
  111. of nkChckRangeF, nkChckRange64, nkChckRange:
  112. rangeCheckAnalysis(c, g, tree, n)
  113. of nkProcDef, nkConverterDef, nkMethodDef, nkFuncDef, nkIteratorDef:
  114. if n.firstSon.kind == nkSym and isNotGeneric(n):
  115. let item = n.firstSon.operand
  116. if isExportedToC(c, g, item):
  117. # This symbol is alive and everything its body references.
  118. followLater(c, g, c.thisModule, item)
  119. else:
  120. for son in sonsReadonly(tree, n):
  121. aliveCode(c, g, tree, son)
  122. proc followNow(c: var AliveContext; g: PackedModuleGraph) =
  123. ## Mark all entries in the stack. Marking can add more entries
  124. ## to the stack but eventually we have looked at every alive symbol.
  125. while c.stack.len > 0:
  126. let (modId, opt, ast) = c.stack.pop()
  127. c.thisModule = modId
  128. c.options = opt
  129. aliveCode(c, g, g[modId].fromDisk.bodies, ast)
  130. proc computeAliveSyms*(g: PackedModuleGraph; conf: ConfigRef): AliveSyms =
  131. ## Entry point for our DCE algorithm.
  132. var c = AliveContext(stack: @[], decoder: PackedDecoder(config: conf),
  133. thisModule: -1, alive: newSeq[IntSet](g.len),
  134. options: conf.options)
  135. for i in countdown(high(g), 0):
  136. if g[i].status != undefined:
  137. c.thisModule = i
  138. for p in allNodes(g[i].fromDisk.topLevel):
  139. aliveCode(c, g, g[i].fromDisk.topLevel, p)
  140. followNow(c, g)
  141. result = move(c.alive)
  142. proc isAlive*(a: AliveSyms; module: int, item: int32): bool =
  143. ## Backends use this to query if a symbol is `alive` which means
  144. ## we need to produce (C/C++/etc) code for it.
  145. result = a[module].contains(item)