liftdestructors.nim 43 KB

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