injectdestructors.nim 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2017 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Injects destructor calls into Nim code as well as
  10. ## an optimizer that optimizes copies to moves. This is implemented as an
  11. ## AST to AST transformation so that every backend benefits from it.
  12. ## See doc/destructors.rst for a spec of the implemented rewrite rules
  13. import
  14. intsets, strtabs, ast, astalgo, msgs, renderer, magicsys, types, idents,
  15. strutils, options, lowerings, tables, modulegraphs,
  16. lineinfos, parampatterns, sighashes, liftdestructors, optimizer,
  17. varpartitions, aliasanalysis, dfa
  18. when defined(nimPreviewSlimSystem):
  19. import std/assertions
  20. from trees import exprStructuralEquivalent, getRoot
  21. type
  22. Con = object
  23. owner: PSym
  24. when true:
  25. g: ControlFlowGraph
  26. graph: ModuleGraph
  27. inLoop, inSpawn, inLoopCond: int
  28. uninit: IntSet # set of uninit'ed vars
  29. idgen: IdGenerator
  30. body: PNode
  31. otherUsage: TLineInfo
  32. Scope = object # we do scope-based memory management.
  33. # a scope is comparable to an nkStmtListExpr like
  34. # (try: statements; dest = y(); finally: destructors(); dest)
  35. vars: seq[PSym]
  36. wasMoved: seq[PNode]
  37. final: seq[PNode] # finally section
  38. locals: seq[PSym]
  39. body: PNode
  40. needsTry: bool
  41. parent: ptr Scope
  42. ProcessMode = enum
  43. normal
  44. consumed
  45. sinkArg
  46. const toDebug {.strdefine.} = ""
  47. when toDebug.len > 0:
  48. var shouldDebug = false
  49. template dbg(body) =
  50. when toDebug.len > 0:
  51. if shouldDebug:
  52. body
  53. proc hasDestructor(c: Con; t: PType): bool {.inline.} =
  54. result = ast.hasDestructor(t)
  55. when toDebug.len > 0:
  56. # for more effective debugging
  57. if not result and c.graph.config.selectedGC in {gcArc, gcOrc}:
  58. assert(not containsGarbageCollectedRef(t))
  59. proc getTemp(c: var Con; s: var Scope; typ: PType; info: TLineInfo): PNode =
  60. let sym = newSym(skTemp, getIdent(c.graph.cache, ":tmpD"), nextSymId c.idgen, c.owner, info)
  61. sym.typ = typ
  62. s.vars.add(sym)
  63. result = newSymNode(sym)
  64. proc nestedScope(parent: var Scope; body: PNode): Scope =
  65. Scope(vars: @[], locals: @[], wasMoved: @[], final: @[], body: body, needsTry: false, parent: addr(parent))
  66. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}): PNode
  67. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope; isDecl = false): PNode
  68. when false:
  69. var
  70. perfCounters: array[InstrKind, int]
  71. proc showCounters*() =
  72. for i in low(InstrKind)..high(InstrKind):
  73. echo "INSTR ", i, " ", perfCounters[i]
  74. proc isLastReadImpl(n: PNode; c: var Con; scope: var Scope): bool =
  75. let root = parampatterns.exprRoot(n, allowCalls=false)
  76. if root == nil: return false
  77. var s = addr(scope)
  78. while s != nil:
  79. if s.locals.contains(root): break
  80. s = s.parent
  81. c.g = constructCfg(c.owner, if s != nil: s.body else: c.body, root)
  82. dbg:
  83. echo "\n### ", c.owner.name.s, ":\nCFG:"
  84. echoCfg(c.g)
  85. #echo c.body
  86. var j = 0
  87. while j < c.g.len:
  88. if c.g[j].kind == use and c.g[j].n == n: break
  89. inc j
  90. c.otherUsage = unknownLineInfo
  91. if j < c.g.len:
  92. var pcs = @[j+1]
  93. var marked = initIntSet()
  94. result = true
  95. while pcs.len > 0:
  96. var pc = pcs.pop()
  97. if not marked.contains(pc):
  98. let oldPc = pc
  99. while pc < c.g.len:
  100. dbg:
  101. echo "EXEC ", c.g[pc].kind, " ", pc, " ", n
  102. when false:
  103. inc perfCounters[c.g[pc].kind]
  104. case c.g[pc].kind
  105. of loop:
  106. let back = pc + c.g[pc].dest
  107. if not marked.containsOrIncl(back):
  108. pc = back
  109. else:
  110. break
  111. of goto:
  112. pc = pc + c.g[pc].dest
  113. of fork:
  114. if not marked.contains(pc+1):
  115. pcs.add pc + 1
  116. pc = pc + c.g[pc].dest
  117. of use:
  118. if c.g[pc].n.aliases(n) != no or n.aliases(c.g[pc].n) != no:
  119. c.otherUsage = c.g[pc].n.info
  120. return false
  121. inc pc
  122. of def:
  123. if c.g[pc].n.aliases(n) == yes:
  124. # the path leads to a redefinition of 's' --> sink 's'.
  125. break
  126. elif n.aliases(c.g[pc].n) != no:
  127. # only partially writes to 's' --> can't sink 's', so this def reads 's'
  128. # or maybe writes to 's' --> can't sink 's'
  129. c.otherUsage = c.g[pc].n.info
  130. return false
  131. inc pc
  132. marked.incl oldPc
  133. else:
  134. result = false
  135. proc isLastRead(n: PNode; c: var Con; s: var Scope): bool =
  136. if not hasDestructor(c, n.typ): return true
  137. let m = skipConvDfa(n)
  138. result = (m.kind == nkSym and sfSingleUsedTemp in m.sym.flags) or
  139. isLastReadImpl(n, c, s)
  140. proc isFirstWrite(n: PNode; c: var Con): bool =
  141. let m = skipConvDfa(n)
  142. result = nfFirstWrite in m.flags
  143. proc isCursor(n: PNode): bool =
  144. case n.kind
  145. of nkSym:
  146. sfCursor in n.sym.flags
  147. of nkDotExpr:
  148. isCursor(n[1])
  149. of nkCheckedFieldExpr:
  150. isCursor(n[0])
  151. else:
  152. false
  153. template isUnpackedTuple(n: PNode): bool =
  154. ## we move out all elements of unpacked tuples,
  155. ## hence unpacked tuples themselves don't need to be destroyed
  156. (n.kind == nkSym and n.sym.kind == skTemp and n.sym.typ.kind == tyTuple)
  157. proc checkForErrorPragma(c: Con; t: PType; ri: PNode; opname: string) =
  158. var m = "'" & opname & "' is not available for type <" & typeToString(t) & ">"
  159. if (opname == "=" or opname == "=copy") and ri != nil:
  160. m.add "; requires a copy because it's not the last read of '"
  161. m.add renderTree(ri)
  162. m.add '\''
  163. if c.otherUsage != unknownLineInfo:
  164. # ri.comment.startsWith('\n'):
  165. m.add "; another read is done here: "
  166. m.add c.graph.config $ c.otherUsage
  167. #m.add c.graph.config $ c.g[parseInt(ri.comment[1..^1])].n.info
  168. elif ri.kind == nkSym and ri.sym.kind == skParam and not isSinkType(ri.sym.typ):
  169. m.add "; try to make "
  170. m.add renderTree(ri)
  171. m.add " a 'sink' parameter"
  172. m.add "; routine: "
  173. m.add c.owner.name.s
  174. localError(c.graph.config, ri.info, errGenerated, m)
  175. proc makePtrType(c: var Con, baseType: PType): PType =
  176. result = newType(tyPtr, nextTypeId c.idgen, c.owner)
  177. addSonSkipIntLit(result, baseType, c.idgen)
  178. proc genOp(c: var Con; op: PSym; dest: PNode): PNode =
  179. let addrExp = newNodeIT(nkHiddenAddr, dest.info, makePtrType(c, dest.typ))
  180. addrExp.add(dest)
  181. result = newTree(nkCall, newSymNode(op), addrExp)
  182. proc genOp(c: var Con; t: PType; kind: TTypeAttachedOp; dest, ri: PNode): PNode =
  183. var op = getAttachedOp(c.graph, t, kind)
  184. if op == nil or op.ast.isGenericRoutine:
  185. # give up and find the canonical type instead:
  186. let h = sighashes.hashType(t, {CoType, CoConsiderOwned, CoDistinct})
  187. let canon = c.graph.canonTypes.getOrDefault(h)
  188. if canon != nil:
  189. op = getAttachedOp(c.graph, canon, kind)
  190. if op == nil:
  191. #echo dest.typ.id
  192. globalError(c.graph.config, dest.info, "internal error: '" & AttachedOpToStr[kind] &
  193. "' operator not found for type " & typeToString(t))
  194. elif op.ast.isGenericRoutine:
  195. globalError(c.graph.config, dest.info, "internal error: '" & AttachedOpToStr[kind] &
  196. "' operator is generic")
  197. dbg:
  198. if kind == attachedDestructor:
  199. echo "destructor is ", op.id, " ", op.ast
  200. if sfError in op.flags: checkForErrorPragma(c, t, ri, AttachedOpToStr[kind])
  201. c.genOp(op, dest)
  202. proc genDestroy(c: var Con; dest: PNode): PNode =
  203. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  204. result = c.genOp(t, attachedDestructor, dest, nil)
  205. proc canBeMoved(c: Con; t: PType): bool {.inline.} =
  206. let t = t.skipTypes({tyGenericInst, tyAlias, tySink})
  207. if optOwnedRefs in c.graph.config.globalOptions:
  208. result = t.kind != tyRef and getAttachedOp(c.graph, t, attachedSink) != nil
  209. else:
  210. result = getAttachedOp(c.graph, t, attachedSink) != nil
  211. proc isNoInit(dest: PNode): bool {.inline.} =
  212. result = dest.kind == nkSym and sfNoInit in dest.sym.flags
  213. proc genSink(c: var Con; dest, ri: PNode, isDecl = false): PNode =
  214. if (c.inLoopCond == 0 and (isUnpackedTuple(dest) or isDecl or
  215. (isAnalysableFieldAccess(dest, c.owner) and isFirstWrite(dest, c)))) or
  216. isNoInit(dest):
  217. # optimize sink call into a bitwise memcopy
  218. result = newTree(nkFastAsgn, dest, ri)
  219. else:
  220. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  221. if getAttachedOp(c.graph, t, attachedSink) != nil:
  222. result = c.genOp(t, attachedSink, dest, ri)
  223. result.add ri
  224. else:
  225. # the default is to use combination of `=destroy(dest)` and
  226. # and copyMem(dest, source). This is efficient.
  227. result = newTree(nkStmtList, c.genDestroy(dest), newTree(nkFastAsgn, dest, ri))
  228. proc isCriticalLink(dest: PNode): bool {.inline.} =
  229. #[
  230. Lins's idea that only "critical" links can introduce a cycle. This is
  231. critical for the performance gurantees that we strive for: If you
  232. traverse a data structure, no tracing will be performed at all.
  233. ORC is about this promise: The GC only touches the memory that the
  234. mutator touches too.
  235. These constructs cannot possibly create cycles::
  236. local = ...
  237. new(x)
  238. dest = ObjectConstructor(field: noalias(dest))
  239. But since 'ObjectConstructor' is already moved into 'dest' all we really have
  240. to look for is assignments to local variables.
  241. ]#
  242. result = dest.kind != nkSym
  243. proc finishCopy(c: var Con; result, dest: PNode; isFromSink: bool) =
  244. if c.graph.config.selectedGC == gcOrc:
  245. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct})
  246. if cyclicType(t):
  247. result.add boolLit(c.graph, result.info, isFromSink or isCriticalLink(dest))
  248. proc genMarkCyclic(c: var Con; result, dest: PNode) =
  249. if c.graph.config.selectedGC == gcOrc:
  250. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink, tyDistinct})
  251. if cyclicType(t):
  252. if t.kind == tyRef:
  253. result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, dest)
  254. else:
  255. let xenv = genBuiltin(c.graph, c.idgen, mAccessEnv, "accessEnv", dest)
  256. xenv.typ = getSysType(c.graph, dest.info, tyPointer)
  257. result.add callCodegenProc(c.graph, "nimMarkCyclic", dest.info, xenv)
  258. proc genCopyNoCheck(c: var Con; dest, ri: PNode): PNode =
  259. let t = dest.typ.skipTypes({tyGenericInst, tyAlias, tySink})
  260. result = c.genOp(t, attachedAsgn, dest, ri)
  261. assert ri.typ != nil
  262. proc genCopy(c: var Con; dest, ri: PNode): PNode =
  263. let t = dest.typ
  264. if tfHasOwned in t.flags and ri.kind != nkNilLit:
  265. # try to improve the error message here:
  266. c.checkForErrorPragma(t, ri, "=copy")
  267. result = c.genCopyNoCheck(dest, ri)
  268. assert ri.typ != nil
  269. proc genDiscriminantAsgn(c: var Con; s: var Scope; n: PNode): PNode =
  270. # discriminator is ordinal value that doesn't need sink destroy
  271. # but fields within active case branch might need destruction
  272. # tmp to support self assignments
  273. let tmp = c.getTemp(s, n[1].typ, n.info)
  274. result = newTree(nkStmtList)
  275. result.add newTree(nkFastAsgn, tmp, p(n[1], c, s, consumed))
  276. result.add p(n[0], c, s, normal)
  277. let le = p(n[0], c, s, normal)
  278. let leDotExpr = if le.kind == nkCheckedFieldExpr: le[0] else: le
  279. let objType = leDotExpr[0].typ
  280. if hasDestructor(c, objType):
  281. if getAttachedOp(c.graph, objType, attachedDestructor) != nil and
  282. sfOverriden in getAttachedOp(c.graph, objType, attachedDestructor).flags:
  283. localError(c.graph.config, n.info, errGenerated, """Assignment to discriminant for objects with user defined destructor is not supported, object must have default destructor.
  284. It is best to factor out piece of object that needs custom destructor into separate object or not use discriminator assignment""")
  285. result.add newTree(nkFastAsgn, le, tmp)
  286. return
  287. # generate: if le != tmp: `=destroy`(le)
  288. let branchDestructor = produceDestructorForDiscriminator(c.graph, objType, leDotExpr[1].sym, n.info, c.idgen)
  289. let cond = newNodeIT(nkInfix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  290. cond.add newSymNode(getMagicEqSymForType(c.graph, le.typ, n.info))
  291. cond.add le
  292. cond.add tmp
  293. let notExpr = newNodeIT(nkPrefix, n.info, getSysType(c.graph, unknownLineInfo, tyBool))
  294. notExpr.add newSymNode(createMagic(c.graph, c.idgen, "not", mNot))
  295. notExpr.add cond
  296. result.add newTree(nkIfStmt, newTree(nkElifBranch, notExpr, c.genOp(branchDestructor, le)))
  297. result.add newTree(nkFastAsgn, le, tmp)
  298. proc genWasMoved(c: var Con, n: PNode): PNode =
  299. result = newNodeI(nkCall, n.info)
  300. result.add(newSymNode(createMagic(c.graph, c.idgen, "wasMoved", mWasMoved)))
  301. result.add copyTree(n) #mWasMoved does not take the address
  302. #if n.kind != nkSym:
  303. # message(c.graph.config, n.info, warnUser, "wasMoved(" & $n & ")")
  304. proc genDefaultCall(t: PType; c: Con; info: TLineInfo): PNode =
  305. result = newNodeI(nkCall, info)
  306. result.add(newSymNode(createMagic(c.graph, c.idgen, "default", mDefault)))
  307. result.typ = t
  308. proc destructiveMoveVar(n: PNode; c: var Con; s: var Scope): PNode =
  309. # generate: (let tmp = v; reset(v); tmp)
  310. if not hasDestructor(c, n.typ):
  311. assert n.kind != nkSym or not hasDestructor(c, n.sym.typ)
  312. result = copyTree(n)
  313. else:
  314. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  315. var temp = newSym(skLet, getIdent(c.graph.cache, "blitTmp"), nextSymId c.idgen, c.owner, n.info)
  316. temp.typ = n.typ
  317. var v = newNodeI(nkLetSection, n.info)
  318. let tempAsNode = newSymNode(temp)
  319. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  320. vpart[0] = tempAsNode
  321. vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
  322. vpart[2] = n
  323. v.add(vpart)
  324. result.add v
  325. let nn = skipConv(n)
  326. c.genMarkCyclic(result, nn)
  327. let wasMovedCall = c.genWasMoved(nn)
  328. result.add wasMovedCall
  329. result.add tempAsNode
  330. proc isCapturedVar(n: PNode): bool =
  331. let root = getRoot(n)
  332. if root != nil: result = root.name.s[0] == ':'
  333. proc passCopyToSink(n: PNode; c: var Con; s: var Scope): PNode =
  334. result = newNodeIT(nkStmtListExpr, n.info, n.typ)
  335. let tmp = c.getTemp(s, n.typ, n.info)
  336. if hasDestructor(c, n.typ):
  337. result.add c.genWasMoved(tmp)
  338. var m = c.genCopy(tmp, n)
  339. m.add p(n, c, s, normal)
  340. c.finishCopy(m, n, isFromSink = true)
  341. result.add m
  342. if isLValue(n) and not isCapturedVar(n) and n.typ.skipTypes(abstractInst).kind != tyRef and c.inSpawn == 0:
  343. message(c.graph.config, n.info, hintPerformance,
  344. ("passing '$1' to a sink parameter introduces an implicit copy; " &
  345. "if possible, rearrange your program's control flow to prevent it") % $n)
  346. else:
  347. if c.graph.config.selectedGC in {gcArc, gcOrc}:
  348. assert(not containsManagedMemory(n.typ))
  349. if n.typ.skipTypes(abstractInst).kind in {tyOpenArray, tyVarargs}:
  350. localError(c.graph.config, n.info, "cannot create an implicit openArray copy to be passed to a sink parameter")
  351. result.add newTree(nkAsgn, tmp, p(n, c, s, normal))
  352. # Since we know somebody will take over the produced copy, there is
  353. # no need to destroy it.
  354. result.add tmp
  355. proc isDangerousSeq(t: PType): bool {.inline.} =
  356. let t = t.skipTypes(abstractInst)
  357. result = t.kind == tySequence and tfHasOwned notin t[0].flags
  358. proc containsConstSeq(n: PNode): bool =
  359. if n.kind == nkBracket and n.len > 0 and n.typ != nil and isDangerousSeq(n.typ):
  360. return true
  361. result = false
  362. case n.kind
  363. of nkExprEqExpr, nkExprColonExpr, nkHiddenStdConv, nkHiddenSubConv:
  364. result = containsConstSeq(n[1])
  365. of nkObjConstr, nkClosure:
  366. for i in 1..<n.len:
  367. if containsConstSeq(n[i]): return true
  368. of nkCurly, nkBracket, nkPar, nkTupleConstr:
  369. for son in n:
  370. if containsConstSeq(son): return true
  371. else: discard
  372. proc ensureDestruction(arg, orig: PNode; c: var Con; s: var Scope): PNode =
  373. # it can happen that we need to destroy expression contructors
  374. # like [], (), closures explicitly in order to not leak them.
  375. if arg.typ != nil and hasDestructor(c, arg.typ):
  376. # produce temp creation for (fn, env). But we need to move 'env'?
  377. # This was already done in the sink parameter handling logic.
  378. result = newNodeIT(nkStmtListExpr, arg.info, arg.typ)
  379. let tmp = c.getTemp(s, arg.typ, arg.info)
  380. result.add c.genSink(tmp, arg, isDecl = true)
  381. result.add tmp
  382. s.final.add c.genDestroy(tmp)
  383. else:
  384. result = arg
  385. proc cycleCheck(n: PNode; c: var Con) =
  386. if c.graph.config.selectedGC != gcArc: return
  387. var value = n[1]
  388. if value.kind == nkClosure:
  389. value = value[1]
  390. if value.kind == nkNilLit: return
  391. let destTyp = n[0].typ.skipTypes(abstractInst)
  392. if destTyp.kind != tyRef and not (destTyp.kind == tyProc and destTyp.callConv == ccClosure):
  393. return
  394. var x = n[0]
  395. var field: PNode = nil
  396. while true:
  397. if x.kind == nkDotExpr:
  398. field = x[1]
  399. if field.kind == nkSym and sfCursor in field.sym.flags: return
  400. x = x[0]
  401. elif x.kind in {nkBracketExpr, nkCheckedFieldExpr, nkDerefExpr, nkHiddenDeref}:
  402. x = x[0]
  403. else:
  404. break
  405. if exprStructuralEquivalent(x, value, strictSymEquality = true):
  406. let msg =
  407. if field != nil:
  408. "'$#' creates an uncollectable ref cycle; annotate '$#' with .cursor" % [$n, $field]
  409. else:
  410. "'$#' creates an uncollectable ref cycle" % [$n]
  411. message(c.graph.config, n.info, warnCycleCreated, msg)
  412. break
  413. proc pVarTopLevel(v: PNode; c: var Con; s: var Scope; res: PNode) =
  414. # move the variable declaration to the top of the frame:
  415. s.vars.add v.sym
  416. if isUnpackedTuple(v):
  417. if c.inLoop > 0:
  418. # unpacked tuple needs reset at every loop iteration
  419. res.add newTree(nkFastAsgn, v, genDefaultCall(v.typ, c, v.info))
  420. elif sfThread notin v.sym.flags and sfCursor notin v.sym.flags:
  421. # do not destroy thread vars for now at all for consistency.
  422. if sfGlobal in v.sym.flags and s.parent == nil: #XXX: Rethink this logic (see tarcmisc.test2)
  423. c.graph.globalDestructors.add c.genDestroy(v)
  424. else:
  425. s.final.add c.genDestroy(v)
  426. proc processScope(c: var Con; s: var Scope; ret: PNode): PNode =
  427. result = newNodeI(nkStmtList, ret.info)
  428. if s.vars.len > 0:
  429. let varSection = newNodeI(nkVarSection, ret.info)
  430. for tmp in s.vars:
  431. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  432. newNodeI(nkEmpty, ret.info))
  433. result.add varSection
  434. if s.wasMoved.len > 0 or s.final.len > 0:
  435. let finSection = newNodeI(nkStmtList, ret.info)
  436. for m in s.wasMoved: finSection.add m
  437. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  438. if s.needsTry:
  439. result.add newTryFinally(ret, finSection)
  440. else:
  441. result.add ret
  442. result.add finSection
  443. else:
  444. result.add ret
  445. if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
  446. template processScopeExpr(c: var Con; s: var Scope; ret: PNode, processCall: untyped, tmpFlags: TSymFlags): PNode =
  447. assert not ret.typ.isEmptyType
  448. var result = newNodeIT(nkStmtListExpr, ret.info, ret.typ)
  449. # There is a possibility to do this check: s.wasMoved.len > 0 or s.final.len > 0
  450. # later and use it to eliminate the temporary when theres no need for it, but its
  451. # tricky because you would have to intercept moveOrCopy at a certain point
  452. let tmp = c.getTemp(s.parent[], ret.typ, ret.info)
  453. tmp.sym.flags = tmpFlags
  454. let cpy = if hasDestructor(c, ret.typ):
  455. s.parent[].final.add c.genDestroy(tmp)
  456. moveOrCopy(tmp, ret, c, s, isDecl = true)
  457. else:
  458. newTree(nkFastAsgn, tmp, p(ret, c, s, normal))
  459. if s.vars.len > 0:
  460. let varSection = newNodeI(nkVarSection, ret.info)
  461. for tmp in s.vars:
  462. varSection.add newTree(nkIdentDefs, newSymNode(tmp), newNodeI(nkEmpty, ret.info),
  463. newNodeI(nkEmpty, ret.info))
  464. result.add varSection
  465. let finSection = newNodeI(nkStmtList, ret.info)
  466. for m in s.wasMoved: finSection.add m
  467. for i in countdown(s.final.high, 0): finSection.add s.final[i]
  468. if s.needsTry:
  469. result.add newTryFinally(newTree(nkStmtListExpr, cpy, processCall(tmp, s.parent[])), finSection)
  470. else:
  471. result.add cpy
  472. result.add finSection
  473. result.add processCall(tmp, s.parent[])
  474. if s.parent != nil: s.parent[].needsTry = s.parent[].needsTry or s.needsTry
  475. result
  476. template handleNestedTempl(n, processCall: untyped, willProduceStmt = false,
  477. tmpFlags = {sfSingleUsedTemp}) =
  478. template maybeVoid(child, s): untyped =
  479. if isEmptyType(child.typ): p(child, c, s, normal)
  480. else: processCall(child, s)
  481. case n.kind
  482. of nkStmtList, nkStmtListExpr:
  483. # a statement list does not open a new scope
  484. if n.len == 0: return n
  485. result = copyNode(n)
  486. for i in 0..<n.len-1:
  487. result.add p(n[i], c, s, normal)
  488. result.add maybeVoid(n[^1], s)
  489. of nkCaseStmt:
  490. result = copyNode(n)
  491. result.add p(n[0], c, s, normal)
  492. for i in 1..<n.len:
  493. let it = n[i]
  494. assert it.kind in {nkOfBranch, nkElse}
  495. var branch = shallowCopy(it)
  496. for j in 0 ..< it.len-1:
  497. branch[j] = copyTree(it[j])
  498. var ofScope = nestedScope(s, it.lastSon)
  499. branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt:
  500. processScope(c, ofScope, maybeVoid(it[^1], ofScope))
  501. else:
  502. processScopeExpr(c, ofScope, it[^1], processCall, tmpFlags)
  503. result.add branch
  504. of nkWhileStmt:
  505. inc c.inLoop
  506. inc c.inLoopCond
  507. result = copyNode(n)
  508. result.add p(n[0], c, s, normal)
  509. dec c.inLoopCond
  510. var bodyScope = nestedScope(s, n[1])
  511. let bodyResult = p(n[1], c, bodyScope, normal)
  512. result.add processScope(c, bodyScope, bodyResult)
  513. dec c.inLoop
  514. of nkParForStmt:
  515. inc c.inLoop
  516. result = shallowCopy(n)
  517. let last = n.len-1
  518. for i in 0..<last-1:
  519. result[i] = n[i]
  520. result[last-1] = p(n[last-1], c, s, normal)
  521. var bodyScope = nestedScope(s, n[1])
  522. let bodyResult = p(n[last], c, bodyScope, normal)
  523. result[last] = processScope(c, bodyScope, bodyResult)
  524. dec c.inLoop
  525. of nkBlockStmt, nkBlockExpr:
  526. result = copyNode(n)
  527. result.add n[0]
  528. var bodyScope = nestedScope(s, n[1])
  529. result.add if n[1].typ.isEmptyType or willProduceStmt:
  530. processScope(c, bodyScope, processCall(n[1], bodyScope))
  531. else:
  532. processScopeExpr(c, bodyScope, n[1], processCall, tmpFlags)
  533. of nkIfStmt, nkIfExpr:
  534. result = copyNode(n)
  535. for i in 0..<n.len:
  536. let it = n[i]
  537. var branch = shallowCopy(it)
  538. var branchScope = nestedScope(s, it.lastSon)
  539. if it.kind in {nkElifBranch, nkElifExpr}:
  540. #Condition needs to be destroyed outside of the condition/branch scope
  541. branch[0] = p(it[0], c, s, normal)
  542. branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt:
  543. processScope(c, branchScope, maybeVoid(it[^1], branchScope))
  544. else:
  545. processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
  546. result.add branch
  547. of nkTryStmt:
  548. result = copyNode(n)
  549. var tryScope = nestedScope(s, n[0])
  550. result.add if n[0].typ.isEmptyType or willProduceStmt:
  551. processScope(c, tryScope, maybeVoid(n[0], tryScope))
  552. else:
  553. processScopeExpr(c, tryScope, n[0], maybeVoid, tmpFlags)
  554. for i in 1..<n.len:
  555. let it = n[i]
  556. var branch = copyTree(it)
  557. var branchScope = nestedScope(s, it[^1])
  558. branch[^1] = if it[^1].typ.isEmptyType or willProduceStmt or it.kind == nkFinally:
  559. processScope(c, branchScope, if it.kind == nkFinally: p(it[^1], c, branchScope, normal)
  560. else: maybeVoid(it[^1], branchScope))
  561. else:
  562. processScopeExpr(c, branchScope, it[^1], processCall, tmpFlags)
  563. result.add branch
  564. of nkWhen: # This should be a "when nimvm" node.
  565. result = copyTree(n)
  566. result[1][0] = processCall(n[1][0], s)
  567. else: assert(false)
  568. proc pRaiseStmt(n: PNode, c: var Con; s: var Scope): PNode =
  569. if optOwnedRefs in c.graph.config.globalOptions and n[0].kind != nkEmpty:
  570. if n[0].kind in nkCallKinds:
  571. let call = p(n[0], c, s, normal)
  572. result = copyNode(n)
  573. result.add call
  574. else:
  575. let tmp = c.getTemp(s, n[0].typ, n.info)
  576. var m = c.genCopyNoCheck(tmp, n[0])
  577. m.add p(n[0], c, s, normal)
  578. c.finishCopy(m, n[0], isFromSink = false)
  579. result = newTree(nkStmtList, c.genWasMoved(tmp), m)
  580. var toDisarm = n[0]
  581. if toDisarm.kind == nkStmtListExpr: toDisarm = toDisarm.lastSon
  582. if toDisarm.kind == nkSym and toDisarm.sym.owner == c.owner:
  583. result.add c.genWasMoved(toDisarm)
  584. result.add newTree(nkRaiseStmt, tmp)
  585. else:
  586. result = copyNode(n)
  587. if n[0].kind != nkEmpty:
  588. result.add p(n[0], c, s, sinkArg)
  589. else:
  590. result.add copyNode(n[0])
  591. s.needsTry = true
  592. proc p(n: PNode; c: var Con; s: var Scope; mode: ProcessMode; tmpFlags = {sfSingleUsedTemp}): PNode =
  593. if n.kind in {nkStmtList, nkStmtListExpr, nkBlockStmt, nkBlockExpr, nkIfStmt,
  594. nkIfExpr, nkCaseStmt, nkWhen, nkWhileStmt, nkParForStmt, nkTryStmt}:
  595. template process(child, s): untyped = p(child, c, s, mode)
  596. handleNestedTempl(n, process, tmpFlags = tmpFlags)
  597. elif mode == sinkArg:
  598. if n.containsConstSeq:
  599. # const sequences are not mutable and so we need to pass a copy to the
  600. # sink parameter (bug #11524). Note that the string implementation is
  601. # different and can deal with 'const string sunk into var'.
  602. result = passCopyToSink(n, c, s)
  603. elif n.kind in {nkBracket, nkObjConstr, nkTupleConstr, nkClosure, nkNilLit} +
  604. nkCallKinds + nkLiterals:
  605. result = p(n, c, s, consumed)
  606. elif ((n.kind == nkSym and isSinkParam(n.sym)) or isAnalysableFieldAccess(n, c.owner)) and
  607. isLastRead(n, c, s) and not (n.kind == nkSym and isCursor(n)):
  608. # Sinked params can be consumed only once. We need to reset the memory
  609. # to disable the destructor which we have not elided
  610. result = destructiveMoveVar(n, c, s)
  611. elif n.kind in {nkHiddenSubConv, nkHiddenStdConv, nkConv}:
  612. result = copyTree(n)
  613. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  614. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  615. # allow conversions from owned to unowned via this little hack:
  616. let nTyp = n[1].typ
  617. n[1].typ = n.typ
  618. result[1] = p(n[1], c, s, sinkArg)
  619. result[1].typ = nTyp
  620. else:
  621. result[1] = p(n[1], c, s, sinkArg)
  622. elif n.kind in {nkObjDownConv, nkObjUpConv}:
  623. result = copyTree(n)
  624. result[0] = p(n[0], c, s, sinkArg)
  625. elif n.typ == nil:
  626. # 'raise X' can be part of a 'case' expression. Deal with it here:
  627. result = p(n, c, s, normal)
  628. else:
  629. # copy objects that are not temporary but passed to a 'sink' parameter
  630. result = passCopyToSink(n, c, s)
  631. else:
  632. case n.kind
  633. of nkBracket, nkTupleConstr, nkClosure, nkCurly:
  634. # Let C(x) be the construction, 'x' the vector of arguments.
  635. # C(x) either owns 'x' or it doesn't.
  636. # If C(x) owns its data, we must consume C(x).
  637. # If it doesn't own the data, it's harmful to destroy it (double frees etc).
  638. # We have the freedom to choose whether it owns it or not so we are smart about it
  639. # and we say, "if passed to a sink we demand C(x) to own its data"
  640. # otherwise we say "C(x) is just some temporary storage, it doesn't own anything,
  641. # don't destroy it"
  642. # but if C(x) is a ref it MUST own its data since we must destroy it
  643. # so then we have no choice but to use 'sinkArg'.
  644. let m = if mode == normal: normal
  645. else: sinkArg
  646. result = copyTree(n)
  647. for i in ord(n.kind == nkClosure)..<n.len:
  648. if n[i].kind == nkExprColonExpr:
  649. result[i][1] = p(n[i][1], c, s, m)
  650. elif n[i].kind == nkRange:
  651. result[i][0] = p(n[i][0], c, s, m)
  652. result[i][1] = p(n[i][1], c, s, m)
  653. else:
  654. result[i] = p(n[i], c, s, m)
  655. of nkObjConstr:
  656. # see also the remark about `nkTupleConstr`.
  657. let t = n.typ.skipTypes(abstractInst)
  658. let isRefConstr = t.kind == tyRef
  659. let m = if isRefConstr: sinkArg
  660. elif mode == normal: normal
  661. else: sinkArg
  662. result = copyTree(n)
  663. for i in 1..<n.len:
  664. if n[i].kind == nkExprColonExpr:
  665. let field = lookupFieldAgain(t, n[i][0].sym)
  666. if field != nil and sfCursor in field.flags:
  667. result[i][1] = p(n[i][1], c, s, normal)
  668. else:
  669. result[i][1] = p(n[i][1], c, s, m)
  670. else:
  671. result[i] = p(n[i], c, s, m)
  672. if mode == normal and isRefConstr:
  673. result = ensureDestruction(result, n, c, s)
  674. of nkCallKinds:
  675. let inSpawn = c.inSpawn
  676. if n[0].kind == nkSym and n[0].sym.magic == mSpawn:
  677. c.inSpawn.inc
  678. elif c.inSpawn > 0:
  679. c.inSpawn.dec
  680. let parameters = n[0].typ
  681. let L = if parameters != nil: parameters.len else: 0
  682. when false:
  683. var isDangerous = false
  684. if n[0].kind == nkSym and n[0].sym.magic in {mOr, mAnd}:
  685. inc c.inDangerousBranch
  686. isDangerous = true
  687. result = shallowCopy(n)
  688. for i in 1..<n.len:
  689. if i < L and isCompileTimeOnly(parameters[i]):
  690. result[i] = n[i]
  691. elif i < L and (isSinkTypeForParam(parameters[i]) or inSpawn > 0):
  692. result[i] = p(n[i], c, s, sinkArg)
  693. else:
  694. result[i] = p(n[i], c, s, normal)
  695. when false:
  696. if isDangerous:
  697. dec c.inDangerousBranch
  698. if n[0].kind == nkSym and n[0].sym.magic in {mNew, mNewFinalize}:
  699. result[0] = copyTree(n[0])
  700. if c.graph.config.selectedGC in {gcHooks, gcArc, gcOrc}:
  701. let destroyOld = c.genDestroy(result[1])
  702. result = newTree(nkStmtList, destroyOld, result)
  703. else:
  704. result[0] = p(n[0], c, s, normal)
  705. if canRaise(n[0]): s.needsTry = true
  706. if mode == normal:
  707. result = ensureDestruction(result, n, c, s)
  708. of nkDiscardStmt: # Small optimization
  709. result = shallowCopy(n)
  710. if n[0].kind != nkEmpty:
  711. result[0] = p(n[0], c, s, normal)
  712. else:
  713. result[0] = copyNode(n[0])
  714. of nkVarSection, nkLetSection:
  715. # transform; var x = y to var x; x op y where op is a move or copy
  716. result = newNodeI(nkStmtList, n.info)
  717. for it in n:
  718. var ri = it[^1]
  719. if it.kind == nkVarTuple and hasDestructor(c, ri.typ):
  720. for i in 0..<it.len-2:
  721. if it[i].kind == nkSym: s.locals.add it[i].sym
  722. let x = lowerTupleUnpacking(c.graph, it, c.idgen, c.owner)
  723. result.add p(x, c, s, consumed)
  724. elif it.kind == nkIdentDefs and hasDestructor(c, skipPragmaExpr(it[0]).typ):
  725. for j in 0..<it.len-2:
  726. let v = skipPragmaExpr(it[j])
  727. if v.kind == nkSym:
  728. if sfCompileTime in v.sym.flags: continue
  729. s.locals.add v.sym
  730. pVarTopLevel(v, c, s, result)
  731. if ri.kind != nkEmpty:
  732. result.add moveOrCopy(v, ri, c, s, isDecl = v.kind == nkSym)
  733. elif ri.kind == nkEmpty and c.inLoop > 0:
  734. result.add moveOrCopy(v, genDefaultCall(v.typ, c, v.info), c, s, isDecl = v.kind == nkSym)
  735. else: # keep the var but transform 'ri':
  736. var v = copyNode(n)
  737. var itCopy = copyNode(it)
  738. for j in 0..<it.len-1:
  739. itCopy.add it[j]
  740. var flags = {sfSingleUsedTemp}
  741. if it.kind == nkIdentDefs and it.len == 3 and it[0].kind == nkSym and
  742. sfGlobal in it[0].sym.flags:
  743. flags.incl sfGlobal
  744. itCopy.add p(it[^1], c, s, normal, tmpFlags = flags)
  745. v.add itCopy
  746. result.add v
  747. of nkAsgn, nkFastAsgn:
  748. if hasDestructor(c, n[0].typ) and n[1].kind notin {nkProcDef, nkDo, nkLambda}:
  749. if n[0].kind in {nkDotExpr, nkCheckedFieldExpr}:
  750. cycleCheck(n, c)
  751. assert n[1].kind notin {nkAsgn, nkFastAsgn}
  752. result = moveOrCopy(p(n[0], c, s, mode), n[1], c, s)
  753. elif isDiscriminantField(n[0]):
  754. result = c.genDiscriminantAsgn(s, n)
  755. else:
  756. result = copyNode(n)
  757. result.add p(n[0], c, s, mode)
  758. result.add p(n[1], c, s, consumed)
  759. of nkRaiseStmt:
  760. result = pRaiseStmt(n, c, s)
  761. of nkWhileStmt:
  762. internalError(c.graph.config, n.info, "nkWhileStmt should have been handled earlier")
  763. result = n
  764. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef,
  765. nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo,
  766. nkFuncDef, nkConstSection, nkConstDef, nkIncludeStmt, nkImportStmt,
  767. nkExportStmt, nkPragma, nkCommentStmt, nkBreakState,
  768. nkTypeOfExpr, nkMixinStmt, nkBindStmt:
  769. result = n
  770. of nkStringToCString, nkCStringToString, nkChckRangeF, nkChckRange64, nkChckRange, nkPragmaBlock:
  771. result = shallowCopy(n)
  772. for i in 0 ..< n.len:
  773. result[i] = p(n[i], c, s, normal)
  774. if n.typ != nil and hasDestructor(c, n.typ):
  775. if mode == normal:
  776. result = ensureDestruction(result, n, c, s)
  777. of nkHiddenSubConv, nkHiddenStdConv, nkConv:
  778. # we have an "ownership invariance" for all constructors C(x).
  779. # See the comment for nkBracket construction. If the caller wants
  780. # to own 'C(x)', it really wants to own 'x' too. If it doesn't,
  781. # we need to destroy 'x' but the function call handling ensures that
  782. # already.
  783. result = copyTree(n)
  784. if n.typ.skipTypes(abstractInst-{tyOwned}).kind != tyOwned and
  785. n[1].typ.skipTypes(abstractInst-{tyOwned}).kind == tyOwned:
  786. # allow conversions from owned to unowned via this little hack:
  787. let nTyp = n[1].typ
  788. n[1].typ = n.typ
  789. result[1] = p(n[1], c, s, mode)
  790. result[1].typ = nTyp
  791. else:
  792. result[1] = p(n[1], c, s, mode)
  793. of nkObjDownConv, nkObjUpConv:
  794. result = copyTree(n)
  795. result[0] = p(n[0], c, s, mode)
  796. of nkDotExpr:
  797. result = shallowCopy(n)
  798. result[0] = p(n[0], c, s, normal)
  799. for i in 1 ..< n.len:
  800. result[i] = n[i]
  801. if mode == sinkArg and hasDestructor(c, n.typ):
  802. if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
  803. s.wasMoved.add c.genWasMoved(n)
  804. else:
  805. result = passCopyToSink(result, c, s)
  806. of nkBracketExpr, nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref:
  807. result = shallowCopy(n)
  808. for i in 0 ..< n.len:
  809. result[i] = p(n[i], c, s, normal)
  810. if mode == sinkArg and hasDestructor(c, n.typ):
  811. if isAnalysableFieldAccess(n, c.owner) and isLastRead(n, c, s):
  812. # consider 'a[(g; destroy(g); 3)]', we want to say 'wasMoved(a[3])'
  813. # without the junk, hence 'c.genWasMoved(n)'
  814. # and not 'c.genWasMoved(result)':
  815. s.wasMoved.add c.genWasMoved(n)
  816. else:
  817. result = passCopyToSink(result, c, s)
  818. of nkDefer, nkRange:
  819. result = shallowCopy(n)
  820. for i in 0 ..< n.len:
  821. result[i] = p(n[i], c, s, normal)
  822. of nkBreakStmt:
  823. s.needsTry = true
  824. result = n
  825. of nkReturnStmt:
  826. result = shallowCopy(n)
  827. for i in 0..<n.len:
  828. result[i] = p(n[i], c, s, mode)
  829. s.needsTry = true
  830. of nkCast:
  831. result = shallowCopy(n)
  832. result[0] = n[0]
  833. result[1] = p(n[1], c, s, mode)
  834. of nkCheckedFieldExpr:
  835. result = shallowCopy(n)
  836. result[0] = p(n[0], c, s, mode)
  837. for i in 1..<n.len:
  838. result[i] = n[i]
  839. of nkGotoState, nkState, nkAsmStmt:
  840. result = n
  841. else:
  842. internalError(c.graph.config, n.info, "cannot inject destructors to node kind: " & $n.kind)
  843. proc sameLocation*(a, b: PNode): bool =
  844. proc sameConstant(a, b: PNode): bool =
  845. a.kind in nkLiterals and a.intVal == b.intVal
  846. const nkEndPoint = {nkSym, nkDotExpr, nkCheckedFieldExpr, nkBracketExpr}
  847. if a.kind in nkEndPoint and b.kind in nkEndPoint:
  848. if a.kind == b.kind:
  849. case a.kind
  850. of nkSym: a.sym == b.sym
  851. of nkDotExpr, nkCheckedFieldExpr: sameLocation(a[0], b[0]) and sameLocation(a[1], b[1])
  852. of nkBracketExpr: sameLocation(a[0], b[0]) and sameConstant(a[1], b[1])
  853. else: false
  854. else: false
  855. else:
  856. case a.kind
  857. of nkSym, nkDotExpr, nkCheckedFieldExpr, nkBracketExpr:
  858. # Reached an endpoint, flip to recurse the other side.
  859. sameLocation(b, a)
  860. of nkAddr, nkHiddenAddr, nkDerefExpr, nkHiddenDeref:
  861. # We don't need to check addr/deref levels or differentiate between the two,
  862. # since pointers don't have hooks :) (e.g: var p: ptr pointer; p[] = addr p)
  863. sameLocation(a[0], b)
  864. of nkObjDownConv, nkObjUpConv: sameLocation(a[0], b)
  865. of nkHiddenStdConv, nkHiddenSubConv: sameLocation(a[1], b)
  866. else: false
  867. proc genFieldAccessSideEffects(c: var Con; dest, ri: PNode, isDecl: bool): PNode =
  868. # with side effects
  869. var temp = newSym(skLet, getIdent(c.graph.cache, "bracketTmp"), nextSymId c.idgen, c.owner, ri[1].info)
  870. temp.typ = ri[1].typ
  871. var v = newNodeI(nkLetSection, ri[1].info)
  872. let tempAsNode = newSymNode(temp)
  873. var vpart = newNodeI(nkIdentDefs, tempAsNode.info, 3)
  874. vpart[0] = tempAsNode
  875. vpart[1] = newNodeI(nkEmpty, tempAsNode.info)
  876. vpart[2] = ri[1]
  877. v.add(vpart)
  878. var newAccess = copyNode(ri)
  879. newAccess.add ri[0]
  880. newAccess.add tempAsNode
  881. var snk = c.genSink(dest, newAccess, isDecl)
  882. result = newTree(nkStmtList, v, snk, c.genWasMoved(newAccess))
  883. proc moveOrCopy(dest, ri: PNode; c: var Con; s: var Scope, isDecl = false): PNode =
  884. if sameLocation(dest, ri):
  885. # rule (self-assignment-removal):
  886. result = newNodeI(nkEmpty, dest.info)
  887. elif isCursor(dest):
  888. case ri.kind:
  889. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
  890. template process(child, s): untyped = moveOrCopy(dest, child, c, s, isDecl)
  891. # We know the result will be a stmt so we use that fact to optimize
  892. handleNestedTempl(ri, process, willProduceStmt = true)
  893. else:
  894. result = newTree(nkFastAsgn, dest, p(ri, c, s, normal))
  895. else:
  896. case ri.kind
  897. of nkCallKinds:
  898. result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
  899. of nkBracketExpr:
  900. if isUnpackedTuple(ri[0]):
  901. # unpacking of tuple: take over the elements
  902. result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
  903. elif isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s):
  904. if aliases(dest, ri) == no:
  905. # Rule 3: `=sink`(x, z); wasMoved(z)
  906. if isAtom(ri[1]):
  907. var snk = c.genSink(dest, ri, isDecl)
  908. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  909. else:
  910. result = genFieldAccessSideEffects(c, dest, ri, isDecl)
  911. else:
  912. result = c.genSink(dest, destructiveMoveVar(ri, c, s), isDecl)
  913. else:
  914. result = c.genCopy(dest, ri)
  915. result.add p(ri, c, s, consumed)
  916. c.finishCopy(result, dest, isFromSink = false)
  917. of nkBracket:
  918. # array constructor
  919. if ri.len > 0 and isDangerousSeq(ri.typ):
  920. result = c.genCopy(dest, ri)
  921. result.add p(ri, c, s, consumed)
  922. c.finishCopy(result, dest, isFromSink = false)
  923. else:
  924. result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
  925. of nkObjConstr, nkTupleConstr, nkClosure, nkCharLit..nkNilLit:
  926. result = c.genSink(dest, p(ri, c, s, consumed), isDecl)
  927. of nkSym:
  928. if isSinkParam(ri.sym) and isLastRead(ri, c, s):
  929. # Rule 3: `=sink`(x, z); wasMoved(z)
  930. let snk = c.genSink(dest, ri, isDecl)
  931. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  932. elif ri.sym.kind != skParam and ri.sym.owner == c.owner and
  933. isLastRead(ri, c, s) and canBeMoved(c, dest.typ) and not isCursor(ri):
  934. # Rule 3: `=sink`(x, z); wasMoved(z)
  935. let snk = c.genSink(dest, ri, isDecl)
  936. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  937. else:
  938. result = c.genCopy(dest, ri)
  939. result.add p(ri, c, s, consumed)
  940. c.finishCopy(result, dest, isFromSink = false)
  941. of nkHiddenSubConv, nkHiddenStdConv, nkConv, nkObjDownConv, nkObjUpConv, nkCast:
  942. result = c.genSink(dest, p(ri, c, s, sinkArg), isDecl)
  943. of nkStmtListExpr, nkBlockExpr, nkIfExpr, nkCaseStmt, nkTryStmt:
  944. template process(child, s): untyped = moveOrCopy(dest, child, c, s, isDecl)
  945. # We know the result will be a stmt so we use that fact to optimize
  946. handleNestedTempl(ri, process, willProduceStmt = true)
  947. of nkRaiseStmt:
  948. result = pRaiseStmt(ri, c, s)
  949. else:
  950. if isAnalysableFieldAccess(ri, c.owner) and isLastRead(ri, c, s) and
  951. canBeMoved(c, dest.typ):
  952. # Rule 3: `=sink`(x, z); wasMoved(z)
  953. let snk = c.genSink(dest, ri, isDecl)
  954. result = newTree(nkStmtList, snk, c.genWasMoved(ri))
  955. else:
  956. result = c.genCopy(dest, ri)
  957. result.add p(ri, c, s, consumed)
  958. c.finishCopy(result, dest, isFromSink = false)
  959. when false:
  960. proc computeUninit(c: var Con) =
  961. if not c.uninitComputed:
  962. c.uninitComputed = true
  963. c.uninit = initIntSet()
  964. var init = initIntSet()
  965. discard initialized(c.g, pc = 0, init, c.uninit, int.high)
  966. proc injectDefaultCalls(n: PNode, c: var Con) =
  967. case n.kind
  968. of nkVarSection, nkLetSection:
  969. for it in n:
  970. if it.kind == nkIdentDefs and it[^1].kind == nkEmpty:
  971. computeUninit(c)
  972. for j in 0..<it.len-2:
  973. let v = skipPragmaExpr(it[j])
  974. doAssert v.kind == nkSym
  975. if c.uninit.contains(v.sym.id):
  976. it[^1] = genDefaultCall(v.sym.typ, c, v.info)
  977. break
  978. of nkNone..nkNilLit, nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef,
  979. nkIteratorDef, nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  980. discard
  981. else:
  982. for i in 0..<n.safeLen:
  983. injectDefaultCalls(n[i], c)
  984. proc injectDestructorCalls*(g: ModuleGraph; idgen: IdGenerator; owner: PSym; n: PNode): PNode =
  985. when toDebug.len > 0:
  986. shouldDebug = toDebug == owner.name.s or toDebug == "always"
  987. if sfGeneratedOp in owner.flags or (owner.kind == skIterator and isInlineIterator(owner.typ)):
  988. return n
  989. var c = Con(owner: owner, graph: g, idgen: idgen, body: n, otherUsage: unknownLineInfo)
  990. if optCursorInference in g.config.options:
  991. computeCursors(owner, n, g)
  992. var scope = Scope(body: n)
  993. let body = p(n, c, scope, normal)
  994. if owner.kind in {skProc, skFunc, skMethod, skIterator, skConverter}:
  995. let params = owner.typ.n
  996. for i in 1..<params.len:
  997. let t = params[i].sym.typ
  998. if isSinkTypeForParam(t) and hasDestructor(c, t.skipTypes({tySink})):
  999. scope.final.add c.genDestroy(params[i])
  1000. #if optNimV2 in c.graph.config.globalOptions:
  1001. # injectDefaultCalls(n, c)
  1002. result = optimize processScope(c, scope, body)
  1003. dbg:
  1004. echo ">---------transformed-to--------->"
  1005. echo renderTree(result, {renderIds})
  1006. if g.config.arcToExpand.hasKey(owner.name.s):
  1007. echo "--expandArc: ", owner.name.s
  1008. echo renderTree(result, {renderIr, renderNoComments})
  1009. echo "-- end of expandArc ------------------------"