optimizer.nim 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. #
  2. #
  3. # The Nim Compiler
  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. ## Optimizer:
  10. ## - elide 'wasMoved(x); destroy(x)' pairs
  11. ## - recognize "all paths lead to 'wasMoved(x)'"
  12. import
  13. ast, renderer, idents, intsets
  14. from trees import exprStructuralEquivalent
  15. const
  16. nfMarkForDeletion = nfNone # faster than a lookup table
  17. type
  18. BasicBlock = object
  19. wasMovedLocs: seq[PNode]
  20. kind: TNodeKind
  21. hasReturn, hasBreak: bool
  22. label: PSym # can be nil
  23. parent: ptr BasicBlock
  24. Con = object
  25. somethingTodo: bool
  26. inFinally: int
  27. proc nestedBlock(parent: var BasicBlock; kind: TNodeKind): BasicBlock =
  28. BasicBlock(wasMovedLocs: @[], kind: kind, hasReturn: false, hasBreak: false,
  29. label: nil, parent: addr(parent))
  30. proc breakStmt(b: var BasicBlock; n: PNode) =
  31. var it = addr(b)
  32. while it != nil:
  33. it.wasMovedLocs.setLen 0
  34. it.hasBreak = true
  35. if n.kind == nkSym:
  36. if it.label == n.sym: break
  37. else:
  38. # unnamed break leaves the block is nkWhileStmt or the like:
  39. if it.kind in {nkWhileStmt, nkBlockStmt, nkBlockExpr}: break
  40. it = it.parent
  41. proc returnStmt(b: var BasicBlock) =
  42. b.hasReturn = true
  43. var it = addr(b)
  44. while it != nil:
  45. it.wasMovedLocs.setLen 0
  46. it = it.parent
  47. proc mergeBasicBlockInfo(parent: var BasicBlock; this: BasicBlock) {.inline.} =
  48. if this.hasReturn:
  49. parent.wasMovedLocs.setLen 0
  50. parent.hasReturn = true
  51. proc wasMovedTarget(matches: var IntSet; branch: seq[PNode]; moveTarget: PNode): bool =
  52. result = false
  53. for i in 0..<branch.len:
  54. if exprStructuralEquivalent(branch[i][1].skipAddr, moveTarget,
  55. strictSymEquality = true):
  56. result = true
  57. matches.incl i
  58. proc intersect(summary: var seq[PNode]; branch: seq[PNode]) =
  59. # keep all 'wasMoved(x)' calls in summary that are also in 'branch':
  60. var i = 0
  61. var matches = initIntSet()
  62. while i < summary.len:
  63. if wasMovedTarget(matches, branch, summary[i][1].skipAddr):
  64. inc i
  65. else:
  66. summary.del i
  67. for m in matches:
  68. summary.add branch[m]
  69. proc invalidateWasMoved(c: var BasicBlock; x: PNode) =
  70. var i = 0
  71. while i < c.wasMovedLocs.len:
  72. if exprStructuralEquivalent(c.wasMovedLocs[i][1].skipAddr, x,
  73. strictSymEquality = true):
  74. c.wasMovedLocs.del i
  75. else:
  76. inc i
  77. proc wasMovedDestroyPair(c: var Con; b: var BasicBlock; d: PNode) =
  78. var i = 0
  79. while i < b.wasMovedLocs.len:
  80. if exprStructuralEquivalent(b.wasMovedLocs[i][1].skipAddr, d[1].skipAddr,
  81. strictSymEquality = true):
  82. b.wasMovedLocs[i].flags.incl nfMarkForDeletion
  83. c.somethingTodo = true
  84. d.flags.incl nfMarkForDeletion
  85. b.wasMovedLocs.del i
  86. else:
  87. inc i
  88. proc analyse(c: var Con; b: var BasicBlock; n: PNode) =
  89. case n.kind
  90. of nkCallKinds:
  91. var special = false
  92. var reverse = false
  93. if n[0].kind == nkSym:
  94. let s = n[0].sym
  95. if s.magic == mWasMoved:
  96. b.wasMovedLocs.add n
  97. special = true
  98. elif s.name.s == "=destroy":
  99. if c.inFinally > 0 and (b.hasReturn or b.hasBreak):
  100. discard "cannot optimize away the destructor"
  101. else:
  102. c.wasMovedDestroyPair b, n
  103. special = true
  104. elif s.name.s == "=sink":
  105. reverse = true
  106. if not special:
  107. if not reverse:
  108. for i in 0 ..< n.len:
  109. analyse(c, b, n[i])
  110. else:
  111. #[ Test destructor/tmatrix.test3:
  112. Prevent this from being elided. We should probably
  113. find a better solution...
  114. `=sink`(b, -
  115. let blitTmp = b;
  116. wasMoved(b);
  117. blitTmp + a)
  118. `=destroy`(b)
  119. ]#
  120. for i in countdown(n.len-1, 0):
  121. analyse(c, b, n[i])
  122. if canRaise(n[0]): returnStmt(b)
  123. of nkSym:
  124. # any usage of the location before destruction implies we
  125. # cannot elide the 'wasMoved(x)':
  126. b.invalidateWasMoved n
  127. of nkNone..pred(nkSym), succ(nkSym)..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  128. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  129. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  130. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
  131. nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  132. discard "do not follow the construct"
  133. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  134. # reverse order, see remark for `=sink`:
  135. analyse(c, b, n[1])
  136. analyse(c, b, n[0])
  137. of nkIfStmt, nkIfExpr:
  138. let isExhaustive = n[^1].kind in {nkElse, nkElseExpr}
  139. var wasMovedSet: seq[PNode] = @[]
  140. for i in 0 ..< n.len:
  141. var branch = nestedBlock(b, n[i].kind)
  142. analyse(c, branch, n[i])
  143. mergeBasicBlockInfo(b, branch)
  144. if isExhaustive:
  145. if i == 0:
  146. wasMovedSet = move(branch.wasMovedLocs)
  147. else:
  148. wasMovedSet.intersect(branch.wasMovedLocs)
  149. for i in 0..<wasMovedSet.len:
  150. b.wasMovedLocs.add wasMovedSet[i]
  151. of nkCaseStmt:
  152. let isExhaustive = skipTypes(n[0].typ,
  153. abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString, tyCstring} or
  154. n[^1].kind == nkElse
  155. analyse(c, b, n[0])
  156. var wasMovedSet: seq[PNode] = @[]
  157. for i in 1 ..< n.len:
  158. var branch = nestedBlock(b, n[i].kind)
  159. analyse(c, branch, n[i])
  160. mergeBasicBlockInfo(b, branch)
  161. if isExhaustive:
  162. if i == 1:
  163. wasMovedSet = move(branch.wasMovedLocs)
  164. else:
  165. wasMovedSet.intersect(branch.wasMovedLocs)
  166. for i in 0..<wasMovedSet.len:
  167. b.wasMovedLocs.add wasMovedSet[i]
  168. of nkTryStmt:
  169. for i in 0 ..< n.len:
  170. var tryBody = nestedBlock(b, nkTryStmt)
  171. analyse(c, tryBody, n[i])
  172. mergeBasicBlockInfo(b, tryBody)
  173. of nkWhileStmt:
  174. analyse(c, b, n[0])
  175. var loopBody = nestedBlock(b, nkWhileStmt)
  176. analyse(c, loopBody, n[1])
  177. mergeBasicBlockInfo(b, loopBody)
  178. of nkBlockStmt, nkBlockExpr:
  179. var blockBody = nestedBlock(b, n.kind)
  180. if n[0].kind == nkSym:
  181. blockBody.label = n[0].sym
  182. analyse(c, blockBody, n[1])
  183. mergeBasicBlockInfo(b, blockBody)
  184. of nkBreakStmt:
  185. breakStmt(b, n[0])
  186. of nkReturnStmt, nkRaiseStmt:
  187. for child in n: analyse(c, b, child)
  188. returnStmt(b)
  189. of nkFinally:
  190. inc c.inFinally
  191. for child in n: analyse(c, b, child)
  192. dec c.inFinally
  193. else:
  194. for child in n: analyse(c, b, child)
  195. proc opt(c: Con; n, parent: PNode; parentPos: int) =
  196. template recurse() =
  197. let x = shallowCopy(n)
  198. for i in 0 ..< n.len:
  199. opt(c, n[i], x, i)
  200. parent[parentPos] = x
  201. case n.kind
  202. of nkCallKinds:
  203. if nfMarkForDeletion in n.flags:
  204. parent[parentPos] = newNodeI(nkEmpty, n.info)
  205. else:
  206. recurse()
  207. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  208. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  209. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  210. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState, nkTypeOfExpr,
  211. nkMixinStmt, nkBindStmt:
  212. parent[parentPos] = n
  213. else:
  214. recurse()
  215. proc optimize*(n: PNode): PNode =
  216. # optimize away simple 'wasMoved(x); destroy(x)' pairs.
  217. #[ Unfortunately this optimization is only really safe when no exceptions
  218. are possible, see for example:
  219. proc main(inp: string; cond: bool) =
  220. if cond:
  221. try:
  222. var s = ["hi", inp & "more"]
  223. for i in 0..4:
  224. use s
  225. consume(s)
  226. wasMoved(s)
  227. finally:
  228. destroy(s)
  229. Now assume 'use' raises, then we shouldn't do the 'wasMoved(s)'
  230. ]#
  231. var c: Con
  232. var b: BasicBlock
  233. analyse(c, b, n)
  234. if c.somethingTodo:
  235. result = shallowCopy(n)
  236. for i in 0 ..< n.safeLen:
  237. opt(c, n[i], result, i)
  238. else:
  239. result = n