injectdestructors.nim 43 KB

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