liftdestructors.nim 49 KB

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