liftdestructors.nim 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## This module implements lifting for type-bound operations
  10. ## (`=sink`, `=copy`, `=destroy`, `=deepCopy`, `=wasMoved`, `=dup`).
  11. import modulegraphs, lineinfos, idents, ast, renderer, semdata,
  12. sighashes, lowerings, options, types, msgs, magicsys, ccgutils
  13. import std/tables
  14. from trees import isCaseObj
  15. when defined(nimPreviewSlimSystem):
  16. import std/assertions
  17. type
  18. TLiftCtx = object
  19. g: ModuleGraph
  20. info: TLineInfo # for construction
  21. kind: TTypeAttachedOp
  22. fn: PSym
  23. asgnForType: PType
  24. recurse: bool
  25. addMemReset: bool # add wasMoved() call after destructor call
  26. canRaise: bool
  27. filterDiscriminator: PSym # we generating destructor for case branch
  28. c: PContext # c can be nil, then we are called from lambdalifting!
  29. idgen: IdGenerator
  30. template destructor*(t: PType): PSym = getAttachedOp(c.g, t, attachedDestructor)
  31. template assignment*(t: PType): PSym = getAttachedOp(c.g, t, attachedAsgn)
  32. template dup*(t: PType): PSym = getAttachedOp(c.g, t, attachedDup)
  33. template asink*(t: PType): PSym = getAttachedOp(c.g, t, attachedSink)
  34. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode)
  35. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  36. info: TLineInfo; idgen: IdGenerator; isDistinct = false): PSym
  37. proc createTypeBoundOps*(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  38. idgen: IdGenerator)
  39. proc at(a, i: PNode, elemType: PType): PNode =
  40. result = newNodeI(nkBracketExpr, a.info, 2)
  41. result[0] = a
  42. result[1] = i
  43. result.typ() = elemType
  44. proc destructorOverridden(g: ModuleGraph; t: PType): bool =
  45. let op = getAttachedOp(g, t, attachedDestructor)
  46. op != nil and sfOverridden in op.flags
  47. proc fillBodyTup(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  48. for i, a in t.ikids:
  49. let lit = lowerings.newIntLit(c.g, x.info, i)
  50. let b = if c.kind == attachedTrace: y else: y.at(lit, a)
  51. fillBody(c, a, body, x.at(lit, a), b)
  52. proc dotField(x: PNode, f: PSym): PNode =
  53. result = newNodeI(nkDotExpr, x.info, 2)
  54. if x.typ.skipTypes(abstractInst).kind == tyVar:
  55. result[0] = x.newDeref
  56. else:
  57. result[0] = x
  58. result[1] = newSymNode(f, x.info)
  59. result.typ() = f.typ
  60. proc newAsgnStmt(le, ri: PNode): PNode =
  61. result = newNodeI(nkAsgn, le.info, 2)
  62. result[0] = le
  63. result[1] = ri
  64. proc genBuiltin*(g: ModuleGraph; idgen: IdGenerator; magic: TMagic; name: string; i: PNode): PNode =
  65. result = newNodeI(nkCall, i.info)
  66. result.add createMagic(g, idgen, name, magic).newSymNode
  67. result.add i
  68. proc genBuiltin(c: var TLiftCtx; magic: TMagic; name: string; i: PNode): PNode =
  69. result = genBuiltin(c.g, c.idgen, magic, name, i)
  70. proc defaultOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  71. if c.kind in {attachedAsgn, attachedDeepCopy, attachedSink, attachedDup}:
  72. body.add newAsgnStmt(x, y)
  73. elif c.kind == attachedDestructor and c.addMemReset:
  74. let call = genBuiltin(c, mDefault, "default", x)
  75. call.typ() = t
  76. body.add newAsgnStmt(x, call)
  77. elif c.kind == attachedWasMoved:
  78. body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  79. proc genAddr(c: var TLiftCtx; x: PNode): PNode =
  80. if x.kind == nkHiddenDeref:
  81. checkSonsLen(x, 1, c.g.config)
  82. result = x[0]
  83. else:
  84. result = newNodeIT(nkHiddenAddr, x.info, makeVarType(x.typ.owner, x.typ, c.idgen))
  85. result.add x
  86. proc genWhileLoop(c: var TLiftCtx; i, dest: PNode): PNode =
  87. result = newNodeI(nkWhileStmt, c.info, 2)
  88. let cmp = genBuiltin(c, mLtI, "<", i)
  89. cmp.add genLen(c.g, dest)
  90. cmp.typ() = getSysType(c.g, c.info, tyBool)
  91. result[0] = cmp
  92. result[1] = newNodeI(nkStmtList, c.info)
  93. proc genIf(c: var TLiftCtx; cond, action: PNode): PNode =
  94. result = newTree(nkIfStmt, newTree(nkElifBranch, cond, action))
  95. proc genContainerOf(c: var TLiftCtx; objType: PType, field, x: PSym): PNode =
  96. # generate: cast[ptr ObjType](cast[int](addr(x)) - offsetOf(objType.field))
  97. let intType = getSysType(c.g, unknownLineInfo, tyInt)
  98. let addrOf = newNodeIT(nkAddr, c.info, makePtrType(x.owner, x.typ, c.idgen))
  99. addrOf.add newDeref(newSymNode(x))
  100. let castExpr1 = newNodeIT(nkCast, c.info, intType)
  101. castExpr1.add newNodeIT(nkType, c.info, intType)
  102. castExpr1.add addrOf
  103. let dotExpr = newNodeIT(nkDotExpr, c.info, x.typ)
  104. dotExpr.add newNodeIT(nkType, c.info, objType)
  105. dotExpr.add newSymNode(field)
  106. let offsetOf = genBuiltin(c, mOffsetOf, "offsetof", dotExpr)
  107. offsetOf.typ() = intType
  108. let minusExpr = genBuiltin(c, mSubI, "-", castExpr1)
  109. minusExpr.typ() = intType
  110. minusExpr.add offsetOf
  111. let objPtr = makePtrType(objType.owner, objType, c.idgen)
  112. result = newNodeIT(nkCast, c.info, objPtr)
  113. result.add newNodeIT(nkType, c.info, objPtr)
  114. result.add minusExpr
  115. proc destructorCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  116. var destroy = newNodeIT(nkCall, x.info, op.typ.returnType)
  117. destroy.add(newSymNode(op))
  118. if op.typ.firstParamType.kind != tyVar:
  119. destroy.add x
  120. else:
  121. destroy.add genAddr(c, x)
  122. if sfNeverRaises notin op.flags:
  123. c.canRaise = true
  124. if c.addMemReset:
  125. result = newTree(nkStmtList, destroy, genBuiltin(c, mWasMoved, "`=wasMoved`", x))
  126. else:
  127. result = destroy
  128. proc genWasMovedCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  129. result = newNodeIT(nkCall, x.info, op.typ.returnType)
  130. result.add(newSymNode(op))
  131. result.add genAddr(c, x)
  132. proc fillBodyObj(c: var TLiftCtx; n, body, x, y: PNode; enforceDefaultOp: bool, enforceWasMoved = false) =
  133. case n.kind
  134. of nkSym:
  135. if c.filterDiscriminator != nil: return
  136. let f = n.sym
  137. let b = if c.kind == attachedTrace: y else: y.dotField(f)
  138. if (sfCursor in f.flags and c.g.config.selectedGC in {gcArc, gcAtomicArc, gcOrc, gcHooks}) or
  139. enforceDefaultOp:
  140. defaultOp(c, f.typ, body, x.dotField(f), b)
  141. else:
  142. if enforceWasMoved:
  143. body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x.dotField(f))
  144. fillBody(c, f.typ, body, x.dotField(f), b)
  145. of nkNilLit: discard
  146. of nkRecCase:
  147. # XXX This is only correct for 'attachedSink'!
  148. var localEnforceDefaultOp = enforceDefaultOp
  149. if c.kind == attachedSink:
  150. # the value needs to be destroyed before we assign the selector
  151. # or the value is lost
  152. let prevKind = c.kind
  153. let prevAddMemReset = c.addMemReset
  154. c.kind = attachedDestructor
  155. c.addMemReset = true
  156. fillBodyObj(c, n, body, x, y, enforceDefaultOp = false)
  157. c.kind = prevKind
  158. c.addMemReset = prevAddMemReset
  159. localEnforceDefaultOp = true
  160. if c.kind != attachedDestructor:
  161. # copy the selector before case stmt, but destroy after case stmt
  162. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  163. let oldfilterDiscriminator = c.filterDiscriminator
  164. if c.filterDiscriminator == n[0].sym:
  165. c.filterDiscriminator = nil # we have found the case part, proceed as normal
  166. # we need to generate a case statement:
  167. var caseStmt = newNodeI(nkCaseStmt, c.info)
  168. # XXX generate 'if' that checks same branches
  169. # generate selector:
  170. var access = dotField(x, n[0].sym)
  171. caseStmt.add(access)
  172. var emptyBranches = 0
  173. # copy the branches over, but replace the fields with the for loop body:
  174. for i in 1..<n.len:
  175. var branch = copyTree(n[i])
  176. branch[^1] = newNodeI(nkStmtList, c.info)
  177. fillBodyObj(c, n[i].lastSon, branch[^1], x, y,
  178. enforceDefaultOp = localEnforceDefaultOp, enforceWasMoved = c.kind == attachedAsgn)
  179. if branch[^1].len == 0: inc emptyBranches
  180. caseStmt.add(branch)
  181. if emptyBranches != n.len-1:
  182. body.add(caseStmt)
  183. if c.kind == attachedDestructor:
  184. # destructor for selector is done after case stmt
  185. fillBodyObj(c, n[0], body, x, y, enforceDefaultOp = false)
  186. c.filterDiscriminator = oldfilterDiscriminator
  187. of nkRecList:
  188. for t in items(n): fillBodyObj(c, t, body, x, y, enforceDefaultOp, enforceWasMoved)
  189. else:
  190. illFormedAstLocal(n, c.g.config)
  191. proc fillBodyObjTImpl(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  192. if t.baseClass != nil:
  193. let dest = newNodeIT(nkHiddenSubConv, c.info, t.baseClass)
  194. dest.add newNodeI(nkEmpty, c.info)
  195. dest.add x
  196. var src = y
  197. if c.kind in {attachedAsgn, attachedDeepCopy, attachedSink}:
  198. src = newNodeIT(nkHiddenSubConv, c.info, t.baseClass)
  199. src.add newNodeI(nkEmpty, c.info)
  200. src.add y
  201. fillBody(c, skipTypes(t.baseClass, abstractPtrs), body, dest, src)
  202. fillBodyObj(c, t.n, body, x, y, enforceDefaultOp = false)
  203. proc fillBodyObjT(c: var TLiftCtx; t: PType, body, x, y: PNode) =
  204. var hasCase = isCaseObj(t.n)
  205. var obj = t
  206. while obj.baseClass != nil:
  207. obj = skipTypes(obj.baseClass, abstractPtrs)
  208. hasCase = hasCase or isCaseObj(obj.n)
  209. if hasCase and c.kind in {attachedAsgn, attachedDeepCopy}:
  210. # assignment for case objects is complex, we do:
  211. # =destroy(dest)
  212. # wasMoved(dest)
  213. # for every field:
  214. # `=` dest.field, src.field
  215. # ^ this is what we used to do, but for 'result = result.sons[0]' it
  216. # destroys 'result' too early.
  217. # So this is what we really need to do:
  218. # let blob {.cursor.} = dest # remembers the old dest.kind
  219. # wasMoved(dest)
  220. # dest.kind = src.kind
  221. # for every field (dependent on dest.kind):
  222. # `=` dest.field, src.field
  223. # =destroy(blob)
  224. var dummy = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  225. dummy.typ = y.typ
  226. if ccgIntroducedPtr(c.g.config, dummy, y.typ):
  227. # Because of potential aliasing when the src param is passed by ref, we need to check for equality here,
  228. # because the wasMoved(dest) call would zero out src, if dest aliases src.
  229. var cond = newTree(nkCall, newSymNode(c.g.getSysMagic(c.info, "==", mEqRef)),
  230. newTreeIT(nkAddr, c.info, makePtrType(c.fn, x.typ, c.idgen), x), newTreeIT(nkAddr, c.info, makePtrType(c.fn, y.typ, c.idgen), y))
  231. cond.typ() = getSysType(c.g, x.info, tyBool)
  232. body.add genIf(c, cond, newTreeI(nkReturnStmt, c.info, newNodeI(nkEmpty, c.info)))
  233. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  234. temp.typ = x.typ
  235. incl(temp.flags, sfFromGeneric)
  236. var v = newNodeI(nkVarSection, c.info)
  237. let blob = newSymNode(temp)
  238. v.addVar(blob, x)
  239. body.add v
  240. #body.add newAsgnStmt(blob, x)
  241. var wasMovedCall = newNodeI(nkCall, c.info)
  242. wasMovedCall.add(newSymNode(createMagic(c.g, c.idgen, "`=wasMoved`", mWasMoved)))
  243. wasMovedCall.add x # mWasMoved does not take the address
  244. body.add wasMovedCall
  245. fillBodyObjTImpl(c, t, body, x, y)
  246. when false:
  247. # does not work yet due to phase-ordering problems:
  248. assert t.destructor != nil
  249. body.add destructorCall(c.g, t.destructor, blob)
  250. let prevKind = c.kind
  251. c.kind = attachedDestructor
  252. fillBodyObjTImpl(c, t, body, blob, y)
  253. c.kind = prevKind
  254. else:
  255. fillBodyObjTImpl(c, t, body, x, y)
  256. proc boolLit*(g: ModuleGraph; info: TLineInfo; value: bool): PNode =
  257. result = newIntLit(g, info, ord value)
  258. result.typ() = getSysType(g, info, tyBool)
  259. proc getCycleParam(c: TLiftCtx): PNode =
  260. assert c.kind in {attachedAsgn, attachedDup}
  261. if c.fn.typ.len == 3 + ord(c.kind == attachedAsgn):
  262. result = c.fn.typ.n.lastSon
  263. assert result.kind == nkSym
  264. assert result.sym.name.s == "cyclic"
  265. else:
  266. result = boolLit(c.g, c.info, true)
  267. proc newHookCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  268. #if sfError in op.flags:
  269. # localError(c.config, x.info, "usage of '$1' is a user-defined error" % op.name.s)
  270. result = newNodeI(nkCall, x.info)
  271. result.add newSymNode(op)
  272. if sfNeverRaises notin op.flags:
  273. c.canRaise = true
  274. if op.typ.firstParamType.kind == tyVar:
  275. result.add genAddr(c, x)
  276. else:
  277. result.add x
  278. if y != nil:
  279. result.add y
  280. if op.typ.signatureLen == 4:
  281. assert y != nil
  282. if c.fn.typ.signatureLen == 4:
  283. result.add getCycleParam(c)
  284. else:
  285. # assume the worst: A cycle is created:
  286. result.add boolLit(c.g, y.info, true)
  287. proc newOpCall(c: var TLiftCtx; op: PSym; x: PNode): PNode =
  288. result = newNodeIT(nkCall, x.info, op.typ.returnType)
  289. result.add(newSymNode(op))
  290. result.add x
  291. if sfNeverRaises notin op.flags:
  292. c.canRaise = true
  293. if c.kind == attachedDup and op.typ.len == 3:
  294. assert x != nil
  295. if c.fn.typ.len == 3:
  296. result.add getCycleParam(c)
  297. else:
  298. # assume the worst: A cycle is created:
  299. result.add boolLit(c.g, x.info, true)
  300. proc newDeepCopyCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  301. result = newAsgnStmt(x, newOpCall(c, op, y))
  302. proc newDupCall(c: var TLiftCtx; op: PSym; x, y: PNode): PNode =
  303. result = newAsgnStmt(x, newOpCall(c, op, y))
  304. proc usesBuiltinArc(t: PType): bool =
  305. proc wrap(t: PType): bool {.nimcall.} = ast.isGCedMem(t)
  306. result = types.searchTypeFor(t, wrap)
  307. proc useNoGc(c: TLiftCtx; t: PType): bool {.inline.} =
  308. result = optSeqDestructors in c.g.config.globalOptions and
  309. ({tfHasGCedMem, tfHasOwned} * t.flags != {} or usesBuiltinArc(t))
  310. proc requiresDestructor(c: TLiftCtx; t: PType): bool {.inline.} =
  311. result = optSeqDestructors in c.g.config.globalOptions and
  312. containsGarbageCollectedRef(t)
  313. proc instantiateGeneric(c: var TLiftCtx; op: PSym; t, typeInst: PType): PSym =
  314. if c.c != nil and typeInst != nil:
  315. result = c.c.instTypeBoundOp(c.c, op, typeInst, c.info, attachedAsgn, 1)
  316. else:
  317. localError(c.g.config, c.info,
  318. "cannot generate destructor for generic type: " & typeToString(t))
  319. result = nil
  320. proc considerAsgnOrSink(c: var TLiftCtx; t: PType; body, x, y: PNode;
  321. field: var PSym): bool =
  322. if optSeqDestructors in c.g.config.globalOptions:
  323. var op = field
  324. let destructorOverridden = destructorOverridden(c.g, t)
  325. if op != nil and op != c.fn and
  326. (sfOverridden in op.flags or destructorOverridden):
  327. if sfError in op.flags:
  328. incl c.fn.flags, sfError
  329. #else:
  330. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  331. onUse(c.info, op)
  332. body.add newHookCall(c, op, x, y)
  333. result = true
  334. elif op == nil and destructorOverridden:
  335. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  336. body.add newHookCall(c, op, x, y)
  337. result = true
  338. else:
  339. result = false
  340. elif tfHasAsgn in t.flags:
  341. var op: PSym
  342. if sameType(t, c.asgnForType):
  343. # generate recursive call:
  344. if c.recurse:
  345. op = c.fn
  346. else:
  347. c.recurse = true
  348. return false
  349. else:
  350. op = field
  351. if op == nil:
  352. op = produceSym(c.g, c.c, t, c.kind, c.info, c.idgen)
  353. if sfError in op.flags:
  354. incl c.fn.flags, sfError
  355. #else:
  356. # markUsed(c.g.config, c.info, op, c.g.usageSym)
  357. onUse(c.info, op)
  358. # We also now do generic instantiations in the destructor lifting pass:
  359. if op.ast.isGenericRoutine:
  360. op = instantiateGeneric(c, op, t, t.typeInst)
  361. field = op
  362. #echo "trying to use ", op.ast
  363. #echo "for ", op.name.s, " "
  364. #debug(t)
  365. #return false
  366. assert op.ast[genericParamsPos].kind == nkEmpty
  367. body.add newHookCall(c, op, x, y)
  368. result = true
  369. else:
  370. result = false
  371. proc addDestructorCall(c: var TLiftCtx; orig: PType; body, x: PNode) =
  372. let t = orig.skipTypes(abstractInst - {tyDistinct})
  373. var op = t.destructor
  374. if op != nil and sfOverridden in op.flags:
  375. if op.ast.isGenericRoutine:
  376. # patch generic destructor:
  377. op = instantiateGeneric(c, op, t, t.typeInst)
  378. setAttachedOp(c.g, c.idgen.module, t, attachedDestructor, op)
  379. if op == nil and (useNoGc(c, t) or requiresDestructor(c, t)):
  380. op = produceSym(c.g, c.c, t, attachedDestructor, c.info, c.idgen)
  381. doAssert op != nil
  382. doAssert op == t.destructor
  383. if op != nil:
  384. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  385. onUse(c.info, op)
  386. body.add destructorCall(c, op, x)
  387. elif useNoGc(c, t):
  388. internalError(c.g.config, c.info,
  389. "type-bound operator could not be resolved")
  390. proc considerUserDefinedOp(c: var TLiftCtx; t: PType; body, x, y: PNode): bool =
  391. case c.kind
  392. of attachedDestructor:
  393. var op = t.destructor
  394. if op != nil and sfOverridden in op.flags:
  395. if op.ast.isGenericRoutine:
  396. # patch generic destructor:
  397. op = instantiateGeneric(c, op, t, t.typeInst)
  398. setAttachedOp(c.g, c.idgen.module, t, attachedDestructor, op)
  399. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  400. onUse(c.info, op)
  401. body.add destructorCall(c, op, x)
  402. result = true
  403. else:
  404. result = false
  405. #result = addDestructorCall(c, t, body, x)
  406. of attachedAsgn, attachedSink, attachedTrace:
  407. var op = getAttachedOp(c.g, t, c.kind)
  408. if op != nil and sfOverridden in op.flags:
  409. if op.ast.isGenericRoutine:
  410. # patch generic =trace:
  411. op = instantiateGeneric(c, op, t, t.typeInst)
  412. setAttachedOp(c.g, c.idgen.module, t, c.kind, op)
  413. result = considerAsgnOrSink(c, t, body, x, y, op)
  414. if op != nil:
  415. setAttachedOp(c.g, c.idgen.module, t, c.kind, op)
  416. of attachedDeepCopy:
  417. let op = getAttachedOp(c.g, t, attachedDeepCopy)
  418. if op != nil:
  419. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  420. onUse(c.info, op)
  421. body.add newDeepCopyCall(c, op, x, y)
  422. result = true
  423. else:
  424. result = false
  425. of attachedWasMoved:
  426. var op = getAttachedOp(c.g, t, attachedWasMoved)
  427. if op != nil and sfOverridden in op.flags:
  428. if op.ast.isGenericRoutine:
  429. # patch generic destructor:
  430. op = instantiateGeneric(c, op, t, t.typeInst)
  431. setAttachedOp(c.g, c.idgen.module, t, attachedWasMoved, op)
  432. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  433. onUse(c.info, op)
  434. body.add genWasMovedCall(c, op, x)
  435. result = true
  436. else:
  437. result = false
  438. of attachedDup:
  439. var op = getAttachedOp(c.g, t, attachedDup)
  440. if op != nil and sfOverridden in op.flags:
  441. if op.ast.isGenericRoutine:
  442. # patch generic destructor:
  443. op = instantiateGeneric(c, op, t, t.typeInst)
  444. setAttachedOp(c.g, c.idgen.module, t, attachedDup, op)
  445. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  446. onUse(c.info, op)
  447. body.add newDupCall(c, op, x, y)
  448. result = true
  449. else:
  450. result = false
  451. proc declareCounter(c: var TLiftCtx; body: PNode; first: BiggestInt): PNode =
  452. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  453. temp.typ = getSysType(c.g, body.info, tyInt)
  454. incl(temp.flags, sfFromGeneric)
  455. var v = newNodeI(nkVarSection, c.info)
  456. result = newSymNode(temp)
  457. v.addVar(result, lowerings.newIntLit(c.g, body.info, first))
  458. body.add v
  459. proc declareTempOf(c: var TLiftCtx; body: PNode; value: PNode): PNode =
  460. var temp = newSym(skTemp, getIdent(c.g.cache, lowerings.genPrefix), c.idgen, c.fn, c.info)
  461. temp.typ = value.typ
  462. incl(temp.flags, sfFromGeneric)
  463. var v = newNodeI(nkVarSection, c.info)
  464. result = newSymNode(temp)
  465. v.addVar(result, value)
  466. body.add v
  467. proc addIncStmt(c: var TLiftCtx; body, i: PNode) =
  468. let incCall = genBuiltin(c, mInc, "inc", i)
  469. incCall.add lowerings.newIntLit(c.g, c.info, 1)
  470. body.add incCall
  471. proc newSeqCall(c: var TLiftCtx; x, y: PNode): PNode =
  472. # don't call genAddr(c, x) here:
  473. result = genBuiltin(c, mNewSeq, "newSeq", x)
  474. let lenCall = genBuiltin(c, mLengthSeq, "len", y)
  475. lenCall.typ() = getSysType(c.g, x.info, tyInt)
  476. result.add lenCall
  477. proc setLenStrCall(c: var TLiftCtx; x, y: PNode): PNode =
  478. let lenCall = genBuiltin(c, mLengthStr, "len", y)
  479. lenCall.typ() = getSysType(c.g, x.info, tyInt)
  480. result = genBuiltin(c, mSetLengthStr, "setLen", x) # genAddr(g, x))
  481. result.add lenCall
  482. proc setLenSeqCall(c: var TLiftCtx; t: PType; x, y: PNode): PNode =
  483. let lenCall = genBuiltin(c, mLengthSeq, "len", y)
  484. lenCall.typ() = getSysType(c.g, x.info, tyInt)
  485. var op = getSysMagic(c.g, x.info, "setLen", mSetLengthSeq)
  486. op = instantiateGeneric(c, op, t, t)
  487. result = newTree(nkCall, newSymNode(op, x.info), x, lenCall)
  488. proc forallElements(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  489. let counterIdx = body.len
  490. let i = declareCounter(c, body, toInt64(firstOrd(c.g.config, t)))
  491. let whileLoop = genWhileLoop(c, i, x)
  492. let elemType = t.elementType
  493. let b = if c.kind == attachedTrace: y else: y.at(i, elemType)
  494. fillBody(c, elemType, whileLoop[1], x.at(i, elemType), b)
  495. if whileLoop[1].len > 0:
  496. addIncStmt(c, whileLoop[1], i)
  497. body.add whileLoop
  498. else:
  499. body.sons.setLen counterIdx
  500. proc checkSelfAssignment(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  501. var cond = callCodegenProc(c.g, "sameSeqPayload", c.info,
  502. newTreeIT(nkAddr, c.info, makePtrType(c.fn, x.typ, c.idgen), x),
  503. newTreeIT(nkAddr, c.info, makePtrType(c.fn, y.typ, c.idgen), y)
  504. )
  505. cond.typ() = getSysType(c.g, c.info, tyBool)
  506. body.add genIf(c, cond, newTreeI(nkReturnStmt, c.info, newNodeI(nkEmpty, c.info)))
  507. proc fillSeqOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  508. case c.kind
  509. of attachedDup:
  510. body.add setLenSeqCall(c, t, x, y)
  511. forallElements(c, t, body, x, y)
  512. of attachedAsgn, attachedDeepCopy:
  513. # we generate:
  514. # if x.p == y.p:
  515. # return
  516. # setLen(dest, y.len)
  517. # var i = 0
  518. # while i < y.len: dest[i] = y[i]; inc(i)
  519. # This is usually more efficient than a destroy/create pair.
  520. checkSelfAssignment(c, t, body, x, y)
  521. body.add setLenSeqCall(c, t, x, y)
  522. forallElements(c, t, body, x, y)
  523. of attachedSink:
  524. let moveCall = genBuiltin(c, mMove, "move", x)
  525. moveCall.add y
  526. doAssert t.destructor != nil
  527. moveCall.add destructorCall(c, t.destructor, x)
  528. body.add moveCall
  529. of attachedDestructor:
  530. # destroy all elements:
  531. forallElements(c, t, body, x, y)
  532. body.add genBuiltin(c, mDestroy, "destroy", x)
  533. of attachedTrace:
  534. if canFormAcycle(c.g, t.elemType):
  535. # follow all elements:
  536. forallElements(c, t, body, x, y)
  537. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  538. proc useSeqOrStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  539. createTypeBoundOps(c.g, c.c, t, body.info, c.idgen)
  540. # recursions are tricky, so we might need to forward the generated
  541. # operation here:
  542. var t = t
  543. if t.assignment == nil or t.destructor == nil or t.dup == nil:
  544. let h = sighashes.hashType(t,c.g.config, {CoType, CoConsiderOwned, CoDistinct})
  545. let canon = c.g.canonTypes.getOrDefault(h)
  546. if canon != nil: t = canon
  547. case c.kind
  548. of attachedAsgn, attachedDeepCopy:
  549. # XXX: replace these with assertions.
  550. if t.assignment == nil:
  551. return # protect from recursion
  552. body.add newHookCall(c, t.assignment, x, y)
  553. of attachedSink:
  554. # we always inline the move for better performance:
  555. let moveCall = genBuiltin(c, mMove, "move", x)
  556. moveCall.add y
  557. doAssert t.destructor != nil
  558. moveCall.add destructorCall(c, t.destructor, x)
  559. body.add moveCall
  560. # alternatively we could do this:
  561. when false:
  562. doAssert t.asink != nil
  563. body.add newHookCall(c, t.asink, x, y)
  564. of attachedDestructor:
  565. doAssert t.destructor != nil
  566. body.add destructorCall(c, t.destructor, x)
  567. of attachedTrace:
  568. if t.kind != tyString and canFormAcycle(c.g, t.elemType):
  569. let op = getAttachedOp(c.g, t, c.kind)
  570. if op == nil:
  571. return # protect from recursion
  572. body.add newHookCall(c, op, x, y)
  573. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  574. of attachedDup:
  575. # XXX: replace these with assertions.
  576. let op = getAttachedOp(c.g, t, c.kind)
  577. if op == nil:
  578. return # protect from recursion
  579. body.add newDupCall(c, op, x, y)
  580. proc fillStrOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  581. case c.kind
  582. of attachedAsgn, attachedDeepCopy, attachedDup:
  583. body.add callCodegenProc(c.g, "nimAsgnStrV2", c.info, genAddr(c, x), y)
  584. of attachedSink:
  585. let moveCall = genBuiltin(c, mMove, "move", x)
  586. moveCall.add y
  587. doAssert t.destructor != nil
  588. moveCall.add destructorCall(c, t.destructor, x)
  589. body.add moveCall
  590. of attachedDestructor:
  591. body.add genBuiltin(c, mDestroy, "destroy", x)
  592. of attachedTrace:
  593. discard "strings are atomic and have no inner elements that are to trace"
  594. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  595. proc cyclicType*(g: ModuleGraph, t: PType): bool =
  596. case t.kind
  597. of tyRef: result = types.canFormAcycle(g, t.elementType)
  598. of tyProc: result = t.callConv == ccClosure
  599. else: result = false
  600. proc atomicRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  601. #[ bug #15753 is really subtle. Usually the classical write barrier for reference
  602. counting looks like this::
  603. incRef source # increment first; this takes care of self-assignments1
  604. decRef dest
  605. dest[] = source
  606. However, 'decRef dest' might trigger a cycle collection and then the collector
  607. traverses the graph. It is crucial that when it follows the pointers the assignment
  608. 'dest[] = source' already happened so that we don't do trial deletion on a wrong
  609. graph -- this causes premature freeing of objects! The correct barrier looks like
  610. this::
  611. let tmp = dest
  612. incRef source
  613. dest[] = source
  614. decRef tmp
  615. ]#
  616. var actions = newNodeI(nkStmtList, c.info)
  617. let elemType = t.elementType
  618. createTypeBoundOps(c.g, c.c, elemType, c.info, c.idgen)
  619. let isCyclic = c.g.config.selectedGC == gcOrc and types.canFormAcycle(c.g, elemType)
  620. let isInheritableAcyclicRef = c.g.config.selectedGC == gcOrc and
  621. (not isPureObject(elemType)) and
  622. tfAcyclic in skipTypes(elemType, abstractInst+{tyOwned}-{tyTypeDesc}).flags
  623. # dynamic Acyclic refs need to use dyn decRef
  624. let tmp =
  625. if isCyclic and c.kind in {attachedAsgn, attachedSink, attachedDup}:
  626. declareTempOf(c, body, x)
  627. else:
  628. x
  629. if isFinal(elemType):
  630. addDestructorCall(c, elemType, actions, genDeref(tmp, nkDerefExpr))
  631. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  632. alignOf.typ() = getSysType(c.g, c.info, tyInt)
  633. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, tmp, alignOf)
  634. else:
  635. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(tmp, nkDerefExpr))
  636. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  637. var cond: PNode
  638. if isCyclic:
  639. if isFinal(elemType):
  640. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  641. typInfo.typ() = getSysType(c.g, c.info, tyPointer)
  642. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicStatic", c.info, tmp, typInfo)
  643. else:
  644. cond = callCodegenProc(c.g, "nimDecRefIsLastCyclicDyn", c.info, tmp)
  645. elif isInheritableAcyclicRef:
  646. cond = callCodegenProc(c.g, "nimDecRefIsLastDyn", c.info, x)
  647. else:
  648. cond = callCodegenProc(c.g, "nimDecRefIsLast", c.info, x)
  649. cond.typ() = getSysType(c.g, x.info, tyBool)
  650. case c.kind
  651. of attachedSink:
  652. if isCyclic:
  653. body.add newAsgnStmt(x, y)
  654. body.add genIf(c, cond, actions)
  655. else:
  656. body.add genIf(c, cond, actions)
  657. body.add newAsgnStmt(x, y)
  658. of attachedAsgn:
  659. if isCyclic:
  660. body.add genIf(c, y, callCodegenProc(c.g,
  661. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  662. body.add newAsgnStmt(x, y)
  663. body.add genIf(c, cond, actions)
  664. else:
  665. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  666. body.add genIf(c, cond, actions)
  667. body.add newAsgnStmt(x, y)
  668. of attachedDestructor:
  669. body.add genIf(c, cond, actions)
  670. of attachedDeepCopy: assert(false, "cannot happen")
  671. of attachedTrace:
  672. if isCyclic:
  673. if isFinal(elemType):
  674. let typInfo = genBuiltin(c, mGetTypeInfoV2, "getTypeInfoV2", newNodeIT(nkType, x.info, elemType))
  675. typInfo.typ() = getSysType(c.g, c.info, tyPointer)
  676. body.add callCodegenProc(c.g, "nimTraceRef", c.info, genAddrOf(x, c.idgen), typInfo, y)
  677. else:
  678. # If the ref is polymorphic we have to account for this
  679. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(x, c.idgen), y)
  680. #echo "can follow ", elemType, " static ", isFinal(elemType)
  681. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  682. of attachedDup:
  683. if isCyclic:
  684. body.add newAsgnStmt(x, y)
  685. body.add genIf(c, y, callCodegenProc(c.g,
  686. "nimIncRefCyclic", c.info, y, getCycleParam(c)))
  687. else:
  688. body.add newAsgnStmt(x, y)
  689. body.add genIf(c, y, callCodegenProc(c.g,
  690. "nimIncRef", c.info, y))
  691. proc atomicClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  692. ## Closures are really like refs except they always use a virtual destructor
  693. ## and we need to do the refcounting only on the ref field which we call 'xenv':
  694. let xenv = genBuiltin(c, mAccessEnv, "accessEnv", x)
  695. xenv.typ() = getSysType(c.g, c.info, tyPointer)
  696. let isCyclic = c.g.config.selectedGC == gcOrc
  697. let tmp =
  698. if isCyclic and c.kind in {attachedAsgn, attachedSink, attachedDup}:
  699. declareTempOf(c, body, xenv)
  700. else:
  701. xenv
  702. var actions = newNodeI(nkStmtList, c.info)
  703. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, tmp)
  704. let decRefProc =
  705. if isCyclic: "nimDecRefIsLastCyclicDyn"
  706. else: "nimDecRefIsLast"
  707. let cond = callCodegenProc(c.g, decRefProc, c.info, tmp)
  708. cond.typ() = getSysType(c.g, x.info, tyBool)
  709. case c.kind
  710. of attachedSink:
  711. if isCyclic:
  712. body.add newAsgnStmt(x, y)
  713. body.add genIf(c, cond, actions)
  714. else:
  715. body.add genIf(c, cond, actions)
  716. body.add newAsgnStmt(x, y)
  717. of attachedAsgn:
  718. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  719. yenv.typ() = getSysType(c.g, c.info, tyPointer)
  720. if isCyclic:
  721. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  722. body.add newAsgnStmt(x, y)
  723. body.add genIf(c, cond, actions)
  724. else:
  725. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  726. body.add genIf(c, cond, actions)
  727. body.add newAsgnStmt(x, y)
  728. of attachedDup:
  729. let yenv = genBuiltin(c, mAccessEnv, "accessEnv", y)
  730. yenv.typ() = getSysType(c.g, c.info, tyPointer)
  731. if isCyclic:
  732. body.add newAsgnStmt(x, y)
  733. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRefCyclic", c.info, yenv, getCycleParam(c)))
  734. else:
  735. body.add newAsgnStmt(x, y)
  736. body.add genIf(c, yenv, callCodegenProc(c.g, "nimIncRef", c.info, yenv))
  737. of attachedDestructor:
  738. body.add genIf(c, cond, actions)
  739. of attachedDeepCopy: assert(false, "cannot happen")
  740. of attachedTrace:
  741. body.add callCodegenProc(c.g, "nimTraceRefDyn", c.info, genAddrOf(xenv, c.idgen), y)
  742. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  743. proc weakrefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  744. case c.kind
  745. of attachedSink:
  746. # we 'nil' y out afterwards so we *need* to take over its reference
  747. # count value:
  748. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  749. body.add newAsgnStmt(x, y)
  750. of attachedAsgn:
  751. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  752. body.add genIf(c, x, callCodegenProc(c.g, "nimDecWeakRef", c.info, x))
  753. body.add newAsgnStmt(x, y)
  754. of attachedDup:
  755. body.add newAsgnStmt(x, y)
  756. body.add genIf(c, y, callCodegenProc(c.g, "nimIncRef", c.info, y))
  757. of attachedDestructor:
  758. # it's better to prepend the destruction of weak refs in order to
  759. # prevent wrong "dangling refs exist" problems:
  760. var actions = newNodeI(nkStmtList, c.info)
  761. actions.add callCodegenProc(c.g, "nimDecWeakRef", c.info, x)
  762. let des = genIf(c, x, actions)
  763. if body.len == 0:
  764. body.add des
  765. else:
  766. body.sons.insert(des, 0)
  767. of attachedDeepCopy: assert(false, "cannot happen")
  768. of attachedTrace: discard
  769. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  770. proc ownedRefOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  771. var actions = newNodeI(nkStmtList, c.info)
  772. let elemType = t.skipModifier
  773. #fillBody(c, elemType, actions, genDeref(x), genDeref(y))
  774. #var disposeCall = genBuiltin(c, mDispose, "dispose", x)
  775. if isFinal(elemType):
  776. addDestructorCall(c, elemType, actions, genDeref(x, nkDerefExpr))
  777. var alignOf = genBuiltin(c, mAlignOf, "alignof", newNodeIT(nkType, c.info, elemType))
  778. alignOf.typ() = getSysType(c.g, c.info, tyInt)
  779. actions.add callCodegenProc(c.g, "nimRawDispose", c.info, x, alignOf)
  780. else:
  781. addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(x, nkDerefExpr))
  782. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, x)
  783. case c.kind
  784. of attachedSink, attachedAsgn:
  785. body.add genIf(c, x, actions)
  786. body.add newAsgnStmt(x, y)
  787. of attachedDup:
  788. body.add newAsgnStmt(x, y)
  789. of attachedDestructor:
  790. body.add genIf(c, x, actions)
  791. of attachedDeepCopy: assert(false, "cannot happen")
  792. of attachedTrace: discard
  793. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  794. proc closureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  795. if c.kind == attachedDeepCopy:
  796. # a big problem is that we don't know the environment's type here, so we
  797. # have to go through some indirection; we delegate this to the codegen:
  798. let call = newNodeI(nkCall, c.info, 2)
  799. call.typ() = t
  800. call[0] = newSymNode(createMagic(c.g, c.idgen, "deepCopy", mDeepCopy))
  801. call[1] = y
  802. body.add newAsgnStmt(x, call)
  803. elif (optOwnedRefs in c.g.config.globalOptions and
  804. optRefCheck in c.g.config.options) or c.g.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  805. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  806. xx.typ() = getSysType(c.g, c.info, tyPointer)
  807. case c.kind
  808. of attachedSink:
  809. # we 'nil' y out afterwards so we *need* to take over its reference
  810. # count value:
  811. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  812. body.add newAsgnStmt(x, y)
  813. of attachedAsgn:
  814. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  815. yy.typ() = getSysType(c.g, c.info, tyPointer)
  816. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  817. body.add genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  818. body.add newAsgnStmt(x, y)
  819. of attachedDup:
  820. let yy = genBuiltin(c, mAccessEnv, "accessEnv", y)
  821. yy.typ() = getSysType(c.g, c.info, tyPointer)
  822. body.add newAsgnStmt(x, y)
  823. body.add genIf(c, yy, callCodegenProc(c.g, "nimIncRef", c.info, yy))
  824. of attachedDestructor:
  825. let des = genIf(c, xx, callCodegenProc(c.g, "nimDecWeakRef", c.info, xx))
  826. if body.len == 0:
  827. body.add des
  828. else:
  829. body.sons.insert(des, 0)
  830. of attachedDeepCopy: assert(false, "cannot happen")
  831. of attachedTrace: discard
  832. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  833. proc ownedClosureOp(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  834. let xx = genBuiltin(c, mAccessEnv, "accessEnv", x)
  835. xx.typ() = getSysType(c.g, c.info, tyPointer)
  836. var actions = newNodeI(nkStmtList, c.info)
  837. #discard addDestructorCall(c, elemType, newNodeI(nkStmtList, c.info), genDeref(xx))
  838. actions.add callCodegenProc(c.g, "nimDestroyAndDispose", c.info, xx)
  839. case c.kind
  840. of attachedSink, attachedAsgn:
  841. body.add genIf(c, xx, actions)
  842. body.add newAsgnStmt(x, y)
  843. of attachedDup:
  844. body.add newAsgnStmt(x, y)
  845. of attachedDestructor:
  846. body.add genIf(c, xx, actions)
  847. of attachedDeepCopy: assert(false, "cannot happen")
  848. of attachedTrace: discard
  849. of attachedWasMoved: body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  850. proc fillBody(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  851. case t.kind
  852. of tyNone, tyEmpty, tyVoid: discard
  853. of tyPointer, tySet, tyBool, tyChar, tyEnum, tyInt..tyUInt64, tyCstring,
  854. tyPtr, tyUncheckedArray, tyVar, tyLent:
  855. defaultOp(c, t, body, x, y)
  856. of tyRef:
  857. if c.g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  858. atomicRefOp(c, t, body, x, y)
  859. elif (optOwnedRefs in c.g.config.globalOptions and
  860. optRefCheck in c.g.config.options):
  861. weakrefOp(c, t, body, x, y)
  862. else:
  863. defaultOp(c, t, body, x, y)
  864. of tyProc:
  865. if t.callConv == ccClosure:
  866. if c.g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc}:
  867. atomicClosureOp(c, t, body, x, y)
  868. else:
  869. closureOp(c, t, body, x, y)
  870. else:
  871. defaultOp(c, t, body, x, y)
  872. of tyOwned:
  873. let base = t.skipTypes(abstractInstOwned)
  874. if optOwnedRefs in c.g.config.globalOptions:
  875. case base.kind
  876. of tyRef:
  877. ownedRefOp(c, base, body, x, y)
  878. return
  879. of tyProc:
  880. if base.callConv == ccClosure:
  881. ownedClosureOp(c, base, body, x, y)
  882. return
  883. else: discard
  884. defaultOp(c, base, body, x, y)
  885. of tyArray:
  886. if tfHasAsgn in t.flags or useNoGc(c, t):
  887. forallElements(c, t, body, x, y)
  888. else:
  889. defaultOp(c, t, body, x, y)
  890. of tySequence:
  891. if useNoGc(c, t):
  892. useSeqOrStrOp(c, t, body, x, y)
  893. elif optSeqDestructors in c.g.config.globalOptions:
  894. # note that tfHasAsgn is propagated so we need the check on
  895. # 'selectedGC' here to determine if we have the new runtime.
  896. discard considerUserDefinedOp(c, t, body, x, y)
  897. elif tfHasAsgn in t.flags:
  898. if c.kind in {attachedAsgn, attachedSink, attachedDeepCopy}:
  899. body.add newSeqCall(c, x, y)
  900. forallElements(c, t, body, x, y)
  901. else:
  902. defaultOp(c, t, body, x, y)
  903. of tyString:
  904. if useNoGc(c, t):
  905. useSeqOrStrOp(c, t, body, x, y)
  906. elif tfHasAsgn in t.flags:
  907. discard considerUserDefinedOp(c, t, body, x, y)
  908. else:
  909. defaultOp(c, t, body, x, y)
  910. of tyObject:
  911. if not considerUserDefinedOp(c, t, body, x, y):
  912. if t.sym != nil and sfImportc in t.sym.flags:
  913. case c.kind
  914. of {attachedAsgn, attachedSink, attachedDup}:
  915. body.add newAsgnStmt(x, y)
  916. of attachedWasMoved:
  917. body.add genBuiltin(c, mWasMoved, "`=wasMoved`", x)
  918. else:
  919. fillBodyObjT(c, t, body, x, y)
  920. else:
  921. if c.kind == attachedDup:
  922. var op2 = getAttachedOp(c.g, t, attachedAsgn)
  923. if op2 != nil and sfOverridden in op2.flags:
  924. #markUsed(c.g.config, c.info, op, c.g.usageSym)
  925. onUse(c.info, op2)
  926. body.add newHookCall(c, t.assignment, x, y)
  927. else:
  928. fillBodyObjT(c, t, body, x, y)
  929. else:
  930. fillBodyObjT(c, t, body, x, y)
  931. of tyDistinct:
  932. if not considerUserDefinedOp(c, t, body, x, y):
  933. fillBody(c, t.elementType, body, x, y)
  934. of tyTuple:
  935. fillBodyTup(c, t, body, x, y)
  936. of tyVarargs, tyOpenArray:
  937. if c.kind == attachedDestructor and (tfHasAsgn in t.flags or useNoGc(c, t)):
  938. forallElements(c, t, body, x, y)
  939. else:
  940. discard "cannot copy openArray"
  941. of tyFromExpr, tyError, tyBuiltInTypeClass, tyUserTypeClass,
  942. tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything,
  943. tyGenericParam, tyGenericBody, tyNil, tyUntyped, tyTyped,
  944. tyTypeDesc, tyGenericInvocation, tyForward, tyStatic:
  945. #internalError(c.g.config, c.info, "assignment requested for type: " & typeToString(t))
  946. discard
  947. of tyOrdinal, tyRange, tyInferred,
  948. tyGenericInst, tyAlias, tySink:
  949. fillBody(c, skipModifier(t), body, x, y)
  950. of tyConcept, tyIterable: raiseAssert "unreachable"
  951. proc produceSymDistinctType(g: ModuleGraph; c: PContext; typ: PType;
  952. kind: TTypeAttachedOp; info: TLineInfo;
  953. idgen: IdGenerator): PSym =
  954. assert typ.kind == tyDistinct
  955. let baseType = typ.elementType
  956. if getAttachedOp(g, baseType, kind) == nil:
  957. # TODO: fixme `isDistinct` is a fix for #23552; remove it after
  958. # `-d:nimPreviewNonVarDestructor` becomes the default
  959. discard produceSym(g, c, baseType, kind, info, idgen, isDistinct = true)
  960. result = getAttachedOp(g, baseType, kind)
  961. setAttachedOp(g, idgen.module, typ, kind, result)
  962. proc symDupPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  963. info: TLineInfo; idgen: IdGenerator): PSym =
  964. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  965. result = newSym(skProc, procname, idgen, owner, info)
  966. let res = newSym(skResult, getIdent(g.cache, "result"), idgen, result, info)
  967. let src = newSym(skParam, getIdent(g.cache, "src"),
  968. idgen, result, info)
  969. res.typ = typ
  970. src.typ = typ
  971. result.typ = newType(tyProc, idgen, owner)
  972. result.typ.n = newNodeI(nkFormalParams, info)
  973. rawAddSon(result.typ, res.typ)
  974. result.typ.n.add newNodeI(nkEffectList, info)
  975. result.typ.addParam src
  976. if g.config.selectedGC == gcOrc and
  977. cyclicType(g, typ.skipTypes(abstractInst)):
  978. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  979. idgen, result, info)
  980. cycleParam.typ = getSysType(g, info, tyBool)
  981. result.typ.addParam cycleParam
  982. var n = newNodeI(nkProcDef, info, bodyPos+2)
  983. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  984. n[namePos] = newSymNode(result)
  985. n[paramsPos] = result.typ.n
  986. n[bodyPos] = newNodeI(nkStmtList, info)
  987. n[resultPos] = newSymNode(res)
  988. result.ast = n
  989. incl result.flags, sfFromGeneric
  990. incl result.flags, sfGeneratedOp
  991. proc symPrototype(g: ModuleGraph; typ: PType; owner: PSym; kind: TTypeAttachedOp;
  992. info: TLineInfo; idgen: IdGenerator; isDiscriminant = false; isDistinct = false): PSym =
  993. if kind == attachedDup:
  994. return symDupPrototype(g, typ, owner, kind, info, idgen)
  995. let procname = getIdent(g.cache, AttachedOpToStr[kind])
  996. result = newSym(skProc, procname, idgen, owner, info)
  997. let dest = newSym(skParam, getIdent(g.cache, "dest"), idgen, result, info)
  998. let src = newSym(skParam, getIdent(g.cache, if kind == attachedTrace: "env" else: "src"),
  999. idgen, result, info)
  1000. if kind == attachedDestructor and g.config.selectedGC in {gcArc, gcOrc, gcAtomicArc} and
  1001. ((g.config.isDefined("nimPreviewNonVarDestructor") and not isDiscriminant) or (typ.kind in {tyRef, tyString, tySequence} and not isDistinct)):
  1002. dest.typ = typ
  1003. else:
  1004. dest.typ = makeVarType(typ.owner, typ, idgen)
  1005. if kind == attachedTrace:
  1006. src.typ = getSysType(g, info, tyPointer)
  1007. else:
  1008. src.typ = typ
  1009. result.typ = newProcType(info, idgen, owner)
  1010. result.typ.addParam dest
  1011. if kind notin {attachedDestructor, attachedWasMoved}:
  1012. result.typ.addParam src
  1013. if kind == attachedAsgn and g.config.selectedGC == gcOrc and
  1014. cyclicType(g, typ.skipTypes(abstractInst)):
  1015. let cycleParam = newSym(skParam, getIdent(g.cache, "cyclic"),
  1016. idgen, result, info)
  1017. cycleParam.typ = getSysType(g, info, tyBool)
  1018. result.typ.addParam cycleParam
  1019. var n = newNodeI(nkProcDef, info, bodyPos+1)
  1020. for i in 0..<n.len: n[i] = newNodeI(nkEmpty, info)
  1021. n[namePos] = newSymNode(result)
  1022. n[paramsPos] = result.typ.n
  1023. n[bodyPos] = newNodeI(nkStmtList, info)
  1024. result.ast = n
  1025. incl result.flags, sfFromGeneric
  1026. incl result.flags, sfGeneratedOp
  1027. if kind == attachedWasMoved:
  1028. incl result.flags, sfNoSideEffect
  1029. incl result.typ.flags, tfNoSideEffect
  1030. proc genTypeFieldCopy(c: var TLiftCtx; t: PType; body, x, y: PNode) =
  1031. let xx = genBuiltin(c, mAccessTypeField, "accessTypeField", x)
  1032. let yy = genBuiltin(c, mAccessTypeField, "accessTypeField", y)
  1033. xx.typ() = getSysType(c.g, c.info, tyPointer)
  1034. yy.typ() = xx.typ
  1035. body.add newAsgnStmt(xx, yy)
  1036. proc produceSym(g: ModuleGraph; c: PContext; typ: PType; kind: TTypeAttachedOp;
  1037. info: TLineInfo; idgen: IdGenerator; isDistinct = false): PSym =
  1038. if typ.kind == tyDistinct:
  1039. return produceSymDistinctType(g, c, typ, kind, info, idgen)
  1040. result = getAttachedOp(g, typ, kind)
  1041. if result == nil:
  1042. result = symPrototype(g, typ, typ.owner, kind, info, idgen, isDistinct = isDistinct)
  1043. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, asgnForType: typ, idgen: idgen,
  1044. fn: result)
  1045. let dest = if kind == attachedDup: result.ast[resultPos].sym else: result.typ.n[1].sym
  1046. let d = if result.typ.firstParamType.kind == tyVar: newDeref(newSymNode(dest)) else: newSymNode(dest)
  1047. let src = case kind
  1048. of {attachedDestructor, attachedWasMoved}: newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  1049. of attachedDup: newSymNode(result.typ.n[1].sym)
  1050. else: newSymNode(result.typ.n[2].sym)
  1051. # register this operation already:
  1052. setAttachedOpPartial(g, idgen.module, typ, kind, result)
  1053. if kind == attachedSink and destructorOverridden(g, typ):
  1054. ## compiler can use a combination of `=destroy` and memCopy for sink op
  1055. dest.flags.incl sfCursor
  1056. let op = getAttachedOp(g, typ, attachedDestructor)
  1057. result.ast[bodyPos].add newOpCall(a, op, if op.typ.firstParamType.kind == tyVar: d[0] else: d)
  1058. result.ast[bodyPos].add newAsgnStmt(d, src)
  1059. else:
  1060. var tk: TTypeKind
  1061. if g.config.selectedGC in {gcArc, gcOrc, gcHooks, gcAtomicArc}:
  1062. tk = skipTypes(typ, {tyOrdinal, tyRange, tyInferred, tyGenericInst, tyStatic, tyAlias, tySink}).kind
  1063. else:
  1064. tk = tyNone # no special casing for strings and seqs
  1065. case tk
  1066. of tySequence:
  1067. fillSeqOp(a, typ, result.ast[bodyPos], d, src)
  1068. of tyString:
  1069. fillStrOp(a, typ, result.ast[bodyPos], d, src)
  1070. else:
  1071. fillBody(a, typ, result.ast[bodyPos], d, src)
  1072. if tk == tyObject and a.kind in {attachedAsgn, attachedSink, attachedDeepCopy, attachedDup} and not lacksMTypeField(typ):
  1073. # bug #19205: Do not forget to also copy the hidden type field:
  1074. genTypeFieldCopy(a, typ, result.ast[bodyPos], d, src)
  1075. if not a.canRaise:
  1076. incl result.flags, sfNeverRaises
  1077. result.ast[pragmasPos] = newNodeI(nkPragma, info)
  1078. result.ast[pragmasPos].add newTree(nkExprColonExpr,
  1079. newIdentNode(g.cache.getIdent("raises"), info), newNodeI(nkBracket, info))
  1080. completePartialOp(g, idgen.module, typ, kind, result)
  1081. proc produceDestructorForDiscriminator*(g: ModuleGraph; typ: PType; field: PSym,
  1082. info: TLineInfo; idgen: IdGenerator): PSym =
  1083. assert(typ.skipTypes({tyAlias, tyGenericInst}).kind == tyObject)
  1084. # discrimantor assignments needs pointers to destroy fields; alas, we cannot use non-var destructor here
  1085. result = symPrototype(g, field.typ, typ.owner, attachedDestructor, info, idgen, isDiscriminant = true)
  1086. var a = TLiftCtx(info: info, g: g, kind: attachedDestructor, asgnForType: typ, idgen: idgen,
  1087. fn: result)
  1088. a.asgnForType = typ
  1089. a.filterDiscriminator = field
  1090. a.addMemReset = true
  1091. let discrimantDest = result.typ.n[1].sym
  1092. let dst = newSym(skVar, getIdent(g.cache, "dest"), idgen, result, info)
  1093. dst.typ = makePtrType(typ.owner, typ, idgen)
  1094. let dstSym = newSymNode(dst)
  1095. let d = newDeref(dstSym)
  1096. let v = newNodeI(nkVarSection, info)
  1097. v.addVar(dstSym, genContainerOf(a, typ, field, discrimantDest))
  1098. result.ast[bodyPos].add v
  1099. let placeHolder = newNodeIT(nkSym, info, getSysType(g, info, tyPointer))
  1100. fillBody(a, typ, result.ast[bodyPos], d, placeHolder)
  1101. if not a.canRaise: incl result.flags, sfNeverRaises
  1102. template liftTypeBoundOps*(c: PContext; typ: PType; info: TLineInfo) =
  1103. discard "now a nop"
  1104. proc patchBody(g: ModuleGraph; c: PContext; n: PNode; info: TLineInfo; idgen: IdGenerator) =
  1105. if n.kind in nkCallKinds:
  1106. if n[0].kind == nkSym and n[0].sym.magic == mDestroy:
  1107. let t = n[1].typ.skipTypes(abstractVar)
  1108. if getAttachedOp(g, t, attachedDestructor) == nil:
  1109. discard produceSym(g, c, t, attachedDestructor, info, idgen)
  1110. let op = getAttachedOp(g, t, attachedDestructor)
  1111. if op != nil:
  1112. if op.ast.isGenericRoutine:
  1113. internalError(g.config, info, "resolved destructor is generic")
  1114. if op.magic == mDestroy and t.kind != tyString:
  1115. internalError(g.config, info, "patching mDestroy with mDestroy?")
  1116. n[0] = newSymNode(op)
  1117. for x in n: patchBody(g, c, x, info, idgen)
  1118. proc inst(g: ModuleGraph; c: PContext; t: PType; kind: TTypeAttachedOp; idgen: IdGenerator;
  1119. info: TLineInfo) =
  1120. let op = getAttachedOp(g, t, kind)
  1121. if op != nil and op.ast != nil and op.ast.isGenericRoutine:
  1122. if t.typeInst != nil:
  1123. var a = TLiftCtx(info: info, g: g, kind: kind, c: c, idgen: idgen)
  1124. let opInst = instantiateGeneric(a, op, t, t.typeInst)
  1125. if opInst.ast != nil:
  1126. patchBody(g, c, opInst.ast, info, a.idgen)
  1127. setAttachedOp(g, idgen.module, t, kind, opInst)
  1128. else:
  1129. localError(g.config, info, "unresolved generic parameter")
  1130. proc isTrival*(s: PSym): bool {.inline.} =
  1131. s == nil or (s.ast != nil and s.ast[bodyPos].len == 0)
  1132. proc createTypeBoundOps(g: ModuleGraph; c: PContext; orig: PType; info: TLineInfo;
  1133. idgen: IdGenerator) =
  1134. ## In the semantic pass this is called in strategic places
  1135. ## to ensure we lift assignment, destructors and moves properly.
  1136. ## The later 'injectdestructors' pass depends on it.
  1137. if orig == nil or {tfCheckedForDestructor, tfHasMeta} * orig.flags != {}: return
  1138. incl orig.flags, tfCheckedForDestructor
  1139. # for user defined generic destructors:
  1140. let origRoot = genericRoot(orig)
  1141. if origRoot != nil:
  1142. incl origRoot.flags, tfGenericHasDestructor
  1143. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  1144. if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
  1145. let h = sighashes.hashType(skipped, g.config, {CoType, CoConsiderOwned, CoDistinct})
  1146. var canon = g.canonTypes.getOrDefault(h)
  1147. if canon == nil:
  1148. g.canonTypes[h] = skipped
  1149. canon = skipped
  1150. # multiple cases are to distinguish here:
  1151. # 1. we don't know yet if 'typ' has a nontrival destructor.
  1152. # 2. we have a nop destructor. --> mDestroy
  1153. # 3. we have a lifted destructor.
  1154. # 4. We have a custom destructor.
  1155. # 5. We have a (custom) generic destructor.
  1156. # we do not generate '=trace' procs if we
  1157. # have the cycle detection disabled, saves code size.
  1158. let lastAttached = if g.config.selectedGC == gcOrc: attachedTrace
  1159. else: attachedSink
  1160. # bug #15122: We need to produce all prototypes before entering the
  1161. # mind boggling recursion. Hacks like these imply we should rewrite
  1162. # this module.
  1163. var generics: array[attachedWasMoved..attachedTrace, bool] = default(array[attachedWasMoved..attachedTrace, bool])
  1164. for k in attachedWasMoved..lastAttached:
  1165. generics[k] = getAttachedOp(g, canon, k) != nil
  1166. if not generics[k]:
  1167. setAttachedOp(g, idgen.module, canon, k,
  1168. symPrototype(g, canon, canon.owner, k, info, idgen))
  1169. # we generate the destructor first so that other operators can depend on it:
  1170. for k in attachedWasMoved..lastAttached:
  1171. if not generics[k]:
  1172. discard produceSym(g, c, canon, k, info, idgen)
  1173. else:
  1174. inst(g, c, canon, k, idgen, info)
  1175. if canon != orig:
  1176. setAttachedOp(g, idgen.module, orig, k, getAttachedOp(g, canon, k))
  1177. if not isTrival(getAttachedOp(g, orig, attachedDestructor)):
  1178. #or not isTrival(orig.assignment) or
  1179. # not isTrival(orig.sink):
  1180. orig.flags.incl tfHasAsgn
  1181. # ^ XXX Breaks IC!