cyclebreaker.nim 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2020 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. #[
  10. A Cycle breaker for Nim
  11. -----------------------
  12. Instead of "collecting" cycles with all of its pitfalls we will break cycles.
  13. We exploit that every 'ref' can be 'nil' for this and so get away without
  14. a distinction between weak and strong pointers. The required runtime
  15. mechanisms are the same though: We need to be able to traverse the graph.
  16. This design has the tremendous benefit that it doesn't require a dedicated
  17. 'rawDispose' operation and that it plays well with Nim's cost model.
  18. The cost of freeing a subgraph with cycles is 2 * N rather than N, that's all.
  19. Cycles do not have to be prepared via .acyclic, there are not multiple
  20. pointless traversals, only a single proc, `breakCycles` is exposed as a
  21. separate module.
  22. Algorithm
  23. ---------
  24. We traverse the graph and notice the nodes we've already traversed. If we
  25. marked the node already, we set the pointer that leads to this node to 'nil'
  26. and decrement the reference count of the cell we pointed at.
  27. We notice that multiple paths to the same object do not mean
  28. we found a cycle, it only means the node is shared.
  29. a -------> b <----- c
  30. | ^ ^
  31. +----------+ |
  32. | |
  33. +-------------------+
  34. If we simply remove all links to already processed nodes we end up with:
  35. a -------> b c
  36. | ^
  37. + |
  38. | |
  39. +-------------------+
  40. That seems acceptable, no leak is produced. This implies that the standard
  41. depth-first traversal suffices.
  42. ]#
  43. type PT = ptr pointer
  44. include cellseqs_v2
  45. const
  46. colGreen = 0b000
  47. colYellow = 0b001
  48. colRed = 0b010
  49. colorMask = 0b011
  50. type
  51. TraceProc = proc (p, env: pointer) {.nimcall, benign.}
  52. DisposeProc = proc (p: pointer) {.nimcall, benign.}
  53. template color(c): untyped = c.rc and colorMask
  54. template setColor(c, col) =
  55. c.rc = c.rc and not colorMask or col
  56. proc nimIncRefCyclic(p: pointer) {.compilerRtl, inl.} =
  57. let h = head(p)
  58. inc h.rc, rcIncrement
  59. type
  60. GcEnv = object
  61. traceStack: CellSeq
  62. proc trace(p: pointer; desc: PNimTypeV2; j: var GcEnv) {.inline.} =
  63. when false:
  64. cprintf("[Trace] desc: %p %p\n", desc, p)
  65. cprintf("[Trace] trace: %p\n", desc.traceImpl)
  66. if desc.traceImpl != nil:
  67. cast[TraceProc](desc.traceImpl)(p, addr(j))
  68. proc nimTraceRef(q: pointer; desc: PNimTypeV2; env: pointer) {.compilerRtl.} =
  69. let p = cast[ptr pointer](q)
  70. when traceCollector:
  71. cprintf("[Trace] raw: %p\n", p)
  72. cprintf("[Trace] deref: %p\n", p[])
  73. if p[] != nil:
  74. var j = cast[ptr GcEnv](env)
  75. j.traceStack.add(p, desc)
  76. proc nimTraceRefDyn(q: pointer; env: pointer) {.compilerRtl.} =
  77. let p = cast[ptr pointer](q)
  78. when traceCollector:
  79. cprintf("[TraceDyn] raw: %p\n", p)
  80. cprintf("[TraceDyn] deref: %p\n", p[])
  81. if p[] != nil:
  82. var j = cast[ptr GcEnv](env)
  83. j.traceStack.add(p, cast[ptr PNimTypeV2](p[])[])
  84. var markerGeneration: int
  85. proc breakCycles(s: Cell; desc: PNimTypeV2) =
  86. let markerColor = if (markerGeneration and 1) == 0: colRed
  87. else: colYellow
  88. atomicInc markerGeneration
  89. when traceCollector:
  90. cprintf("[BreakCycles] starting: %p %s RC %ld trace proc %p\n",
  91. s, desc.name, s.rc shr rcShift, desc.traceImpl)
  92. var j: GcEnv
  93. init j.traceStack
  94. s.setColor markerColor
  95. trace(s +! sizeof(RefHeader), desc, j)
  96. while j.traceStack.len > 0:
  97. let (u, desc) = j.traceStack.pop()
  98. let p = u[]
  99. let t = head(p)
  100. if t.color != markerColor:
  101. t.setColor markerColor
  102. trace(p, desc, j)
  103. when traceCollector:
  104. cprintf("[BreakCycles] followed: %p RC %ld\n", t, t.rc shr rcShift)
  105. else:
  106. if (t.rc shr rcShift) > 0:
  107. dec t.rc, rcIncrement
  108. # mark as a link that the produced destructor does not have to follow:
  109. u[] = nil
  110. when traceCollector:
  111. cprintf("[BreakCycles] niled out: %p RC %ld\n", t, t.rc shr rcShift)
  112. else:
  113. # anyhow as a link that the produced destructor does not have to follow:
  114. u[] = nil
  115. cprintf("[Bug] %p %s RC %ld\n", t, desc.name, t.rc shr rcShift)
  116. deinit j.traceStack
  117. proc thinout*[T](x: ref T) {.inline.} =
  118. ## turn the subgraph starting with `x` into its spanning tree by
  119. ## `nil`'ing out any pointers that would harm the spanning tree
  120. ## structure. Any back pointers that introduced cycles
  121. ## and thus would keep the graph from being freed are `nil`'ed.
  122. ## This is a form of cycle collection that works well with Nim's ARC
  123. ## and its associated cost model.
  124. proc getDynamicTypeInfo[T](x: T): PNimTypeV2 {.magic: "GetTypeInfoV2", noSideEffect, locks: 0.}
  125. breakCycles(head(cast[pointer](x)), getDynamicTypeInfo(x[]))
  126. proc thinout*[T: proc](x: T) {.inline.} =
  127. proc rawEnv[T: proc](x: T): pointer {.noSideEffect, inline.} =
  128. {.emit: """
  129. `result` = `x`.ClE_0;
  130. """.}
  131. let p = rawEnv(x)
  132. breakCycles(head(p), cast[ptr PNimTypeV2](p)[])
  133. proc nimDecRefIsLastCyclicDyn(p: pointer): bool {.compilerRtl, inl.} =
  134. if p != nil:
  135. var cell = head(p)
  136. if (cell.rc and not rcMask) == 0:
  137. result = true
  138. #cprintf("[DESTROY] %p\n", p)
  139. else:
  140. dec cell.rc, rcIncrement
  141. # According to Lins it's correct to do nothing else here.
  142. #cprintf("[DeCREF] %p\n", p)
  143. proc nimDecRefIsLastCyclicStatic(p: pointer; desc: PNimTypeV2): bool {.compilerRtl, inl.} =
  144. if p != nil:
  145. var cell = head(p)
  146. if (cell.rc and not rcMask) == 0:
  147. result = true
  148. #cprintf("[DESTROY] %p %s\n", p, desc.name)
  149. else:
  150. dec cell.rc, rcIncrement
  151. #cprintf("[DeCREF] %p %s %ld\n", p, desc.name, cell.rc)