Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 9 additions & 5 deletions compiler/ccgexprs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3606,9 +3606,10 @@ proc genConstHeader(m, q: BModule; p: BProc, sym: PSym) =
getModuleDllPath(q, sym),
'"' & sym.loc.snippet & '"')
else:
# unmarked: a name at the artifact's top level would be a liveness root
var headerDecl = newBuilder("")
headerDecl.addDeclWithVisibility(Extern):
headerDecl.addVar(kind = Local, name = sym.loc.snippet,
headerDecl.addVar(kind = Local, name = stripCnifMarks(sym.loc.snippet),
typ = constType(getTypeDesc(m, sym.loc.t, dkVar)))
m.s[cfsData].add(extract(headerDecl))
if sfExportc in sym.flags and p.module.g.generatedHeader != nil:
Expand All @@ -3626,14 +3627,17 @@ proc genConstDefinition(q: BModule; p: BProc; sym: PSym) =
# Each `cg` process that demands this const emits its definition
# (emit-everywhere). Always declare it first (the data analogue of a proc
# prototype) so a TU whose copy the merge stage drops still has a valid
# declaration; wrap the definition as a droppable `'d'` unit the merge
# stage assigns to a single owner.
# declaration; wrap the definition as a droppable `'u'` unit the merge
# stage assigns to a single owner. It is no root (its uses are marked)
# unless C code may name it, or HCR registers it from the module's init
# under its `_const` name, which no marked use refers to.
let cname = stripCnifMarks(actualConstName)
var decl = newBuilder("")
decl.addDeclWithVisibility(Extern):
decl.addVar(kind = Local, name = actualConstName, typ = td)
decl.addVar(kind = Local, name = cname, typ = td)
q.s[cfsData].add(extract(decl))
q.s[cfsData].add(cnifDefDirective(cname, "d", icNifName(q, sym)))
q.s[cfsData].add(cnifDefDirective(cname,
if sfExportc in sym.flags or q.hcrOn: "d" else: "u", icNifName(q, sym)))
q.s[cfsData].add(extract(data))
q.s[cfsData].add(cnifEndDefs())
q.icDataDefs.add (cname, icNifName(q, sym))
Expand Down
5 changes: 4 additions & 1 deletion compiler/ccgstmts.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1903,7 +1903,10 @@ proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
field: PSym) =
var t = skipTypes(objtype, abstractVar)
assert t.kind == tyObject
discard genTypeInfoV1(p.module, t, a.lode.info)
let ti = genTypeInfoV1(p.module, t, a.lode.info)
if p.config.cmd == cmdNifC:
# the discriminator table below is filled by the type info's init
p.s(cpsStmts).add(cnifUsesOf(ti))
if not containsOrIncl(p.module.declaredThings, field.id):
p.module.s[cfsVars].addDeclWithVisibility(Extern):
discriminatorTableDecl(p.module, t, field, p.module.s[cfsVars])
Expand Down
111 changes: 90 additions & 21 deletions compiler/ccgtypes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,17 @@ proc fillBackendName(m: BModule; s: PSym) =
s.locImpl.snippet = markCName(result)
else:
s.locImpl.snippet = result
elif m.config.cmd == cmdNifC and not m.hcrOn and s.kind in routineKinds and
sfImportc notin s.flags and
(sfExportc notin s.flags or sfCompilerProc in s.flags) and
not hasCnifMarks(s.loc.snippet) and
allCharsInSet(s.loc.snippet, IdentChars):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hack.

# A C name from an `extern:` pragma (most of the stdlib's `rtl` procs) or
# of a compilerproc is set at sem time. Mark it too: otherwise the merge
# stage's liveness walk cannot see its uses and has to keep every such
# proc, used or not.
backendEnsureMutable s
s.locImpl.snippet = markCName(s.loc.snippet)

proc fillParamName(m: BModule; s: PSym) =
if s.loc.snippet == "":
Expand Down Expand Up @@ -1464,12 +1475,13 @@ proc genTypeInfoAuxBase(m: BModule; typ, origType: PType;
# `cg` process emits this type info's tentative definition. Declare it
# `extern` first (the data analogue of a proc prototype) so a TU whose copy
# the merge stage drops still has a valid declaration; wrap the definition
# as a droppable `'d'` unit the merge stage assigns to a single owner so
# as a droppable `'u'` unit the merge stage assigns to a single owner so
# exactly one external-linkage tentative definition survives (preserving
# the RTTI pointer identity refc relies on).
# the RTTI pointer identity refc relies on). Unlike `'d'` it is no root:
# its uses are marked (`rttiRef`), so it lives only if something does.
m.s[cfsStrData].addDeclWithVisibility(Extern):
m.s[cfsStrData].addVar(kind = Local, name = name, typ = "TNimType")
m.s[cfsStrData].add(cnifDefDirective(name, "d", icNifName(m, origType)))
m.s[cfsStrData].add(cnifDefDirective(name, "u", icNifName(m, origType)))
m.s[cfsStrData].addDeclWithVisibility(Private):
m.s[cfsStrData].addVar(kind = Local, name = name, typ = "TNimType")
m.s[cfsStrData].add(cnifEndDefs())
Expand Down Expand Up @@ -1766,6 +1778,15 @@ proc genDeepCopyProc(m: BModule; s: PSym; result: Rope) =
m.s[cfsTypeInit3].addFieldAssignmentWithValue(result, "deepcopy"):
m.s[cfsTypeInit3].add(cCast(pt, s.loc.snippet))

proc rttiRef(m: BModule; name: Snippet): Snippet =
## A reference to the type info `name`. In the per-module backend it is
## cnif-marked: the type info is a DCE'd unit, live only when used.
if m.config.cmd == cmdNifC and not m.hcrOn and name.startsWith("NTI") and

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hack.

allCharsInSet(name, IdentChars):
markCName(name)
else:
name

proc declareNimType(m: BModule; name: string; str: Rope, module: int) =
let nr = rope(name)
if m.hcrOn:
Expand All @@ -1779,13 +1800,11 @@ proc declareNimType(m: BModule; name: string; str: Rope, module: int) =
m.s[cfsTypeInit1].addArgument(hcrGlobal):
m.s[cfsTypeInit1].add("\"" & str & "\"")
else:
# cnif-mark the name: this extern declaration is the reference the
# def-retention check consults when the defining TU regenerates and
# the typeinfo cannot be re-demanded (type vanished) — the referencing
# TU must lose its reuse then instead of producing a link error
let declName = if m.config.cmd == cmdNifC: markCName(str) else: str
# NOT cnif-marked: a name at the artifact's top level is a liveness root.
# The uses are marked instead (`rttiRef`), which also makes them the
# references the def-retention check consults.
m.s[cfsStrData].addDeclWithVisibility(Extern):
m.s[cfsStrData].addVar(kind = Local, name = declName, typ = nr)
m.s[cfsStrData].addVar(kind = Local, name = str, typ = nr)

proc genTypeInfo2Name(m: BModule; t: PType): Rope =
var it = t
Expand Down Expand Up @@ -2047,7 +2066,12 @@ proc genTypeInfoV2OldImpl(m: BModule; t, origType: PType, tiName: Rope; info: TL
m.s[cfsTypeInit3].add extract(typeEntry)

if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions:
discard genTypeInfoV1(m, t, info)
let v1 = genTypeInfoV1(m, t, info)
if m.config.cmd == cmdNifC and not m.hcrOn:
# see `genTypeInfoV2Impl`
m.s[cfsVars].add(cnifDefDirective(tiName, "d", ""))
m.s[cfsVars].add(cnifUsesOf(v1))
m.s[cfsVars].add(cnifEndDefs())

proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineInfo) =
cgsym(m, "TNimTypeV2")
Expand Down Expand Up @@ -2121,14 +2145,24 @@ proc genTypeInfoV2Impl(m: BModule; t, origType: PType, name: Rope; info: TLineIn
typeEntry.addField(typeInit, name = "flags"):
typeEntry.addIntValue(flags)
if m.config.cmd == cmdNifC:
m.s[cfsVars].add(cnifDefDirective(name, "d", icNifName(m, origType)))
# 'u', not 'd': no root, its uses are marked (`rttiRef`) and it keeps the
# hooks it points to alive only while it is live itself. Under HCR its
# uses look it up by its string name (`hcrGetGlobal`): a root.
m.s[cfsVars].add(cnifDefDirective(name, if m.hcrOn: "d" else: "u",
icNifName(m, origType)))
m.s[cfsVars].add extract(typeEntry)
m.s[cfsVars].add(cnifEndDefs())
else:
m.s[cfsVars].add extract(typeEntry)

if t.kind == tyObject and t.baseClass != nil and optEnableDeepCopy in m.config.globalOptions:
discard genTypeInfoV1(m, t, info)
let v1 = genTypeInfoV1(m, t, info)
if m.config.cmd == cmdNifC:
# deepCopy reaches the V1 info through this one's `typeInfoV1` field,
# which the V1 info's init sets: depend on it
m.s[cfsVars].add(cnifDefDirective(name, if m.hcrOn: "d" else: "u", ""))
m.s[cfsVars].add(cnifUsesOf(v1))
m.s[cfsVars].add(cnifEndDefs())

proc myModuleOpenForCodegen(m: BModule; idx: FileIndex): bool {.inline.} =
if moduleOpenForCodegen(m.g.graph, idx):
Expand All @@ -2145,7 +2179,7 @@ proc genTypeInfoV2(m: BModule; t: PType; info: TLineInfo): Rope =
if m.hcrOn:
wrapPar(x)
else:
cAddr(x)
cAddr(rttiRef(m, x))

let sig = hashType(origType, m.config)
result = m.typeInfoMarkerV2.getOrDefault(sig)
Expand Down Expand Up @@ -2232,6 +2266,7 @@ type
markers: Builder
typeNodes: int
typeNodesName: Rope
procUses: seq[string] # the enclosing definition's `icProcUses`

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why?


proc beginRttiInit(m: BModule; scope: var RttiInitScope) =
## The per-module backend emits V1 type info everywhere it is demanded, and
Expand All @@ -2250,6 +2285,12 @@ proc beginRttiInit(m: BModule; scope: var RttiInitScope) =
scope.typeNodesName = m.typeNodesName
m.typeNodes = 0
m.typeNodesName = getTempName(m)
inc m.rttiInitDepth
scope.procUses = move m.icProcUses
inc m.icProcDepth

proc emitRttiInit(m: BModule; name: Rope; markers: Snippet; body: var Builder;
uses: seq[string])

proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) =
## Wraps the init code gathered since `beginRttiInit` into `<name>_init`,
Expand All @@ -2268,19 +2309,31 @@ proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) =
swap(m.s[s], scope.sections[s])
m.typeNodes = scope.typeNodes
m.typeNodesName = scope.typeNodesName
if body.buf.len == 0: return

dec m.rttiInitDepth
let uses = move m.icProcUses
m.icProcUses = move scope.procUses
dec m.icProcDepth
if body.buf.len > 0: emitRttiInit(m, name, markers, body, uses)
if m.rttiInitDepth == 0 and m.rttiInitCalls.buf.len > 0:
m.s[cfsTypeInit3].add(extract(m.rttiInitCalls))

proc emitRttiInit(m: BModule; name: Rope; markers: Snippet; body: var Builder;
uses: seq[string]) =
let initName = name & "_init"
var header = newBuilder("")
header.addDeclWithVisibility(Private):
header.addProcHeader(ccNimCall, initName, CVoid, cProcParams())
let proto = extract(header)
m.s[cfsProcHeaders].add(proto)
m.s[cfsProcHeaders].finishProcHeaderAsProto()
# 'd': a liveness root kept by its owner only; 'u': a unique proc body, so a
# split module may move it into any of its C files. The prototype comes
# first so the unit starts like a proc, and the markers precede their use.
m.s[cfsProcs].add(cnifDefDirective(initName, "ud", ""))
# 'u': a unique proc body, so a split module may move it into any of its C
# files. It is no root: it lives while its type info does (see the call
# below). The prototype comes first so the unit starts like a proc, and the
# markers precede their use. The invisible use keeps the type info alive
# with the init that writes it.
m.s[cfsProcs].add(cnifDefDirective(initName, "u", ""))
m.s[cfsProcs].add(cnifUse(name))
for u in uses: m.s[cfsProcs].add(cnifUse(u))
m.s[cfsProcs].add(proto)
m.s[cfsProcs].finishProcHeaderAsProto()
m.s[cfsProcs].add(markers)
Expand All @@ -2293,7 +2346,23 @@ proc endRttiInit(m: BModule; scope: var RttiInitScope; name: Rope) =
m.s[cfsProcs].addAssignment("nimRttiDone", NimTrue)
m.s[cfsProcs].add(extract(body))
m.s[cfsProcs].add(cnifEndDefs())
m.s[cfsTypeInit3].addCallStmt(initName)
if m.rttiInitDepth > 0:
# built for an enclosing type info: its init runs this one first
m.s[cfsTypeInit3].addCallStmt(markCName(initName))
# The DatInit call belongs to the type info: a unit of the same name, so the
# init runs if and only if the type info is live (and only in its owner;
# every DatInit runs before any module's init code). A nested type info gets
# its own call too, as it can outlive the enclosing one.
# Under HCR the type info is no cnif unit (`declareTypeInfoForHcr`) and so
# never live: the call stays at the top level, a liveness root.
var call = newBuilder("")
if not m.hcrOn: call.add(cnifDefDirective(name, "u", ""))
call.addCallStmt(markCName(initName))
if not m.hcrOn: call.add(cnifEndDefs())
if m.rttiInitDepth > 0:
m.rttiInitCalls.add(extract(call))
else:
m.s[cfsTypeInit3].add(extract(call))

proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope =
let origType = t
Expand All @@ -2303,7 +2372,7 @@ proc genTypeInfoV1(m: BModule; t: PType; info: TLineInfo): Rope =
if m.hcrOn:
wrapPar(x)
else:
cAddr(x)
cAddr(rttiRef(m, x))

let sig = hashType(origType, m.config)
result = m.typeInfoMarker.getOrDefault(sig)
Expand Down
31 changes: 29 additions & 2 deletions compiler/cgen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -1531,6 +1531,15 @@ proc cgsym(m: BModule, name: string) =
let sym = magicsys.getCompilerProc(m.g.graph, name)
if sym != nil:
cgsymImpl m, sym
if m.config.cmd == cmdNifC and sym.kind in routineKinds:
# The caller writes `name` into the C text itself, unmarked: the merge
# stage cannot see that use, so it is recorded explicitly. Uses
# through `cgsymValue` (and `#name` in `ropecg`) carry the marked name.
# Inside a proc (or RTTI init) it is an invisible use of that definition.
let r = stripCnifMarks(sym.loc.snippet)
if m.icProcDepth > 0:
if r notin m.icProcUses: m.icProcUses.add r
elif r notin m.icCgsymRoots: m.icCgsymRoots.add r
else:
rawMessage(m.config, errGenerated, "system module needs: " & name)

Expand Down Expand Up @@ -1826,7 +1835,7 @@ proc resultDestructorCpp(p: BProc; prc: PSym; res: PSym; procBody: PNode): PNode
arg = newTreeIT(nkHiddenAddr, res.info, makePtrType(res.typ, p.module.idgen), arg)
result = newTreeI(nkCall, res.info, newSymNode(op), arg)

proc genProcLvl3*(m: BModule, prc: PSym) =
proc genProcLvl3Impl(m: BModule, prc: PSym) =
if m.config.cmd == cmdNifC:
fillBackendName(m, prc)
if (prc.disamb and (InstanceDisambBit or HookDisambBit)) != 0'i32 and
Expand Down Expand Up @@ -2058,7 +2067,12 @@ proc genProcLvl3*(m: BModule, prc: PSym) =
# cfsProcs emitters (NimMain block, trav markers, ...) never end up
# inside a definition's span.
var defFlags = ""
if sfExportc in prc.flags or sfConstructor in prc.flags: defFlags.add 'x'
# A compilerproc is `exportc` only to fix its C name: like in whole-program
# codegen it is generated when used, so it is no root (unless exported
# from a library).
if (sfExportc in prc.flags and sfCompilerProc notin prc.flags) or
sfConstructor in prc.flags or lfExportLib in prc.loc.flags:
defFlags.add 'x'
if sfCompilerProc in prc.flags: defFlags.add 'c'
if prc.kind == skMethod or sfDispatcher in prc.flags: defFlags.add 'm'
if (prc.typ == nil or prc.typ.callConv != ccInline) and
Expand Down Expand Up @@ -2087,6 +2101,7 @@ proc genProcLvl3*(m: BModule, prc: PSym) =
if sfCppMember * prc.flags != {}: icNifName(m, prc)
else: stripCnifMarks(prc.loc.snippet)
m.s[cfsProcs].add(cnifDefDirective(defName, defFlags, icNifName(m, prc)))
for u in m.icProcUses: m.s[cfsProcs].add(cnifUse(u))
let pushed = icTargetPush(m, prc)
m.s[cfsProcs].add(extract(generatedProc))
if pushed: icTargetPop(m)
Expand All @@ -2105,6 +2120,17 @@ proc genProcLvl3*(m: BModule, prc: PSym) =
'"' & prc.loc.snippet & '"',
cCast(CPointer, prc.loc.snippet & "_actual"))

proc genProcLvl3*(m: BModule, prc: PSym) =
if m.config.cmd == cmdNifC:
# collect the compilerprocs `cgsym` demands by name for this proc's text
var saved = move m.icProcUses
inc m.icProcDepth
genProcLvl3Impl(m, prc)
dec m.icProcDepth
swap m.icProcUses, saved
else:
genProcLvl3Impl(m, prc)

proc requiresExternC(m: BModule; sym: PSym): bool {.inline.} =
result = (sfCompileToCpp in m.module.flags and
sfCompileToCpp notin sym.getModule().flags and
Expand Down Expand Up @@ -3120,6 +3146,7 @@ proc genModule(m: BModule, cfile: Cfile): Rope =
# close the definitions section: the init procs that follow belong to
# the artifact's top level (always-run code, hence liveness roots)
res.add(cnifEndDefs())
for r in m.icCgsymRoots: res.add(cnifUse(r))

if m.s[cfsInitProc].buf.len > 0:
moduleIsEmpty = false
Expand Down
9 changes: 9 additions & 0 deletions compiler/cgendata.nim
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,15 @@ type
# recorded in the cnif artifact so a later run
# can reuse the TU and re-demand definitions
# that cached TUs still reference
icCgsymRoots*: seq[string] # per-module backend: the routines `cgsym`
# demanded by NAME. Their C text names them
# verbatim, out of reach of the cnif marks, so
# they become liveness roots of the module.
icProcUses*: seq[string] # the same for the proc being generated:
# invisible uses of its definition
icProcDepth*: int # nesting of procs (and RTTI inits) being built
rttiInitDepth*: int # nesting of V1 RTTI init procs being built
rttiInitCalls*: Builder # their DatInit calls, flushed by the outermost
hasTopLevelEmit*: bool # a top-level `{.emit.}` wrote user C text into
# a file section: `emit` must not split the
# module, its text may define anything
Expand Down
Loading
Loading