injectdestructors.nim 49 KB

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