injectdestructors.nim 49 KB

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