liftdestructors.nim 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325
  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. let skipped = orig.skipTypes({tyGenericInst, tyAlias, tySink})
  1140. if isEmptyContainer(skipped) or skipped.kind == tyStatic: return
  1141. let h = sighashes.hashType(skipped, g.config, {CoType, CoConsiderOwned, CoDistinct})
  1142. var canon = g.canonTypes.getOrDefault(h)
  1143. if canon == nil:
  1144. g.canonTypes[h] = skipped
  1145. canon = skipped
  1146. # multiple cases are to distinguish here:
  1147. # 1. we don't know yet if 'typ' has a nontrival destructor.
  1148. # 2. we have a nop destructor. --> mDestroy
  1149. # 3. we have a lifted destructor.
  1150. # 4. We have a custom destructor.
  1151. # 5. We have a (custom) generic destructor.
  1152. # we do not generate '=trace' procs if we
  1153. # have the cycle detection disabled, saves code size.
  1154. let lastAttached = if g.config.selectedGC == gcOrc: attachedTrace
  1155. else: attachedSink
  1156. # bug #15122: We need to produce all prototypes before entering the
  1157. # mind boggling recursion. Hacks like these imply we should rewrite
  1158. # this module.
  1159. var generics: array[attachedWasMoved..attachedTrace, bool] = default(array[attachedWasMoved..attachedTrace, bool])
  1160. for k in attachedWasMoved..lastAttached:
  1161. generics[k] = getAttachedOp(g, canon, k) != nil
  1162. if not generics[k]:
  1163. setAttachedOp(g, idgen.module, canon, k,
  1164. symPrototype(g, canon, canon.owner, k, info, idgen))
  1165. # we generate the destructor first so that other operators can depend on it:
  1166. for k in attachedWasMoved..lastAttached:
  1167. if not generics[k]:
  1168. discard produceSym(g, c, canon, k, info, idgen)
  1169. else:
  1170. inst(g, c, canon, k, idgen, info)
  1171. if canon != orig:
  1172. setAttachedOp(g, idgen.module, orig, k, getAttachedOp(g, canon, k))
  1173. if not isTrival(getAttachedOp(g, orig, attachedDestructor)):
  1174. #or not isTrival(orig.assignment) or
  1175. # not isTrival(orig.sink):
  1176. orig.flags.incl tfHasAsgn
  1177. # ^ XXX Breaks IC!