liftdestructors.nim 50 KB

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