cgen.nim 90 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365
  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 the C code generator.
  10. import
  11. ast, astalgo, trees, platform, magicsys, extccomp, options,
  12. nversion, nimsets, msgs, bitsets, idents, types,
  13. ccgutils, ropes, wordrecg, treetab, cgmeth,
  14. rodutils, renderer, cgendata, aliases,
  15. lowerings, ndi, lineinfos, pathutils, transf,
  16. injectdestructors, astmsgs, modulepaths, pushpoppragmas,
  17. mangleutils
  18. from expanddefaults import caseObjDefaultBranch
  19. import pipelineutils
  20. when defined(nimPreviewSlimSystem):
  21. import std/assertions
  22. when not defined(leanCompiler):
  23. import spawn, semparallel
  24. import std/strutils except `%`, addf # collides with ropes.`%`
  25. from ic / ic import ModuleBackendFlag
  26. import std/[dynlib, math, tables, sets, os, intsets, hashes]
  27. const
  28. # we use some ASCII control characters to insert directives that will be converted to real code in a postprocessing pass
  29. postprocessDirStart = '\1'
  30. postprocessDirSep = '\31'
  31. postprocessDirEnd = '\23'
  32. when not declared(dynlib.libCandidates):
  33. proc libCandidates(s: string, dest: var seq[string]) =
  34. ## given a library name pattern `s` write possible library names to `dest`.
  35. var le = strutils.find(s, '(')
  36. var ri = strutils.find(s, ')', le+1)
  37. if le >= 0 and ri > le:
  38. var prefix = substr(s, 0, le - 1)
  39. var suffix = substr(s, ri + 1)
  40. for middle in split(substr(s, le + 1, ri - 1), '|'):
  41. libCandidates(prefix & middle & suffix, dest)
  42. else:
  43. dest.add(s)
  44. when options.hasTinyCBackend:
  45. import tccgen
  46. proc hcrOn(m: BModule): bool = m.config.hcrOn
  47. proc hcrOn(p: BProc): bool = p.module.config.hcrOn
  48. proc addForwardedProc(m: BModule, prc: PSym) =
  49. m.g.forwardedProcs.add(prc)
  50. proc findPendingModule(m: BModule, s: PSym): BModule =
  51. # TODO fixme
  52. if m.config.symbolFiles == v2Sf:
  53. let ms = s.itemId.module #getModule(s)
  54. result = m.g.modules[ms]
  55. else:
  56. var ms = getModule(s)
  57. result = m.g.modules[ms.position]
  58. proc initLoc(k: TLocKind, lode: PNode, s: TStorageLoc, flags: TLocFlags = {}): TLoc =
  59. result = TLoc(k: k, storage: s, lode: lode,
  60. snippet: "", flags: flags)
  61. proc fillLoc(a: var TLoc, k: TLocKind, lode: PNode, r: Rope, s: TStorageLoc) {.inline.} =
  62. # fills the loc if it is not already initialized
  63. if a.k == locNone:
  64. a.k = k
  65. a.lode = lode
  66. a.storage = s
  67. if a.snippet == "": a.snippet = r
  68. proc fillLoc(a: var TLoc, k: TLocKind, lode: PNode, s: TStorageLoc) {.inline.} =
  69. # fills the loc if it is not already initialized
  70. if a.k == locNone:
  71. a.k = k
  72. a.lode = lode
  73. a.storage = s
  74. proc t(a: TLoc): PType {.inline.} =
  75. if a.lode.kind == nkSym:
  76. result = a.lode.sym.typ
  77. else:
  78. result = a.lode.typ
  79. proc lodeTyp(t: PType): PNode =
  80. result = newNode(nkEmpty)
  81. result.typ = t
  82. proc isSimpleConst(typ: PType): bool =
  83. let t = skipTypes(typ, abstractVar)
  84. result = t.kind notin
  85. {tyTuple, tyObject, tyArray, tySet, tySequence} and not
  86. (t.kind == tyProc and t.callConv == ccClosure)
  87. proc useHeader(m: BModule, sym: PSym) =
  88. if lfHeader in sym.loc.flags:
  89. assert(sym.annex != nil)
  90. let str = getStr(sym.annex.path)
  91. m.includeHeader(str)
  92. proc cgsym(m: BModule, name: string)
  93. proc cgsymValue(m: BModule, name: string): Rope
  94. proc getCFile(m: BModule): AbsoluteFile
  95. proc getModuleDllPath(m: BModule): Rope =
  96. let (dir, name, ext) = splitFile(getCFile(m))
  97. let filename = strutils.`%`(platform.OS[m.g.config.target.targetOS].dllFrmt, [name & ext])
  98. result = makeCString(dir.string & "/" & filename)
  99. proc getModuleDllPath(m: BModule, module: int): Rope =
  100. result = getModuleDllPath(m.g.modules[module])
  101. proc getModuleDllPath(m: BModule, s: PSym): Rope =
  102. result = getModuleDllPath(m.g.modules[s.itemId.module])
  103. import std/macros
  104. proc cgFormatValue(result: var string; value: string) =
  105. result.add value
  106. proc cgFormatValue(result: var string; value: BiggestInt) =
  107. result.addInt value
  108. proc cgFormatValue(result: var string; value: Int128) =
  109. result.addInt128 value
  110. # TODO: please document
  111. macro ropecg(m: BModule, frmt: static[FormatStr], args: untyped): Rope =
  112. args.expectKind nnkBracket
  113. # echo "ropecg ", newLit(frmt).repr, ", ", args.repr
  114. var i = 0
  115. result = nnkStmtListExpr.newTree()
  116. result.add quote do:
  117. assert `m` != nil
  118. let resVar = genSym(nskVar, "res")
  119. # during `koch boot` the median of all generates strings from this
  120. # macro is around 40 bytes in length.
  121. result.add newVarStmt(resVar, newCall(bindSym"newStringOfCap", newLit(80)))
  122. let formatValue = bindSym"cgFormatValue"
  123. var num = 0
  124. var strLit = ""
  125. template flushStrLit() =
  126. if strLit != "":
  127. result.add newCall(ident "add", resVar, newLit(strLit))
  128. strLit.setLen 0
  129. while i < frmt.len:
  130. if frmt[i] == '$':
  131. inc(i) # skip '$'
  132. case frmt[i]
  133. of '$':
  134. strLit.add '$'
  135. inc(i)
  136. of '#':
  137. flushStrLit()
  138. inc(i)
  139. result.add newCall(formatValue, resVar, args[num])
  140. inc(num)
  141. of '^':
  142. flushStrLit()
  143. inc(i)
  144. result.add newCall(formatValue, resVar, args[^1])
  145. inc(num)
  146. of '0'..'9':
  147. var j = 0
  148. while true:
  149. j = (j * 10) + ord(frmt[i]) - ord('0')
  150. inc(i)
  151. if i >= frmt.len or not (frmt[i] in {'0'..'9'}): break
  152. num = j
  153. if j > args.len:
  154. error("ropes: invalid format string " & newLit(frmt).repr & " args.len: " & $args.len)
  155. flushStrLit()
  156. result.add newCall(formatValue, resVar, args[j-1])
  157. of 'n':
  158. flushStrLit()
  159. result.add quote do:
  160. if optLineDir notin `m`.config.options:
  161. `resVar`.add("\L")
  162. inc(i)
  163. of 'N':
  164. strLit.add "\L"
  165. inc(i)
  166. else:
  167. error("ropes: invalid format string $" & frmt[i])
  168. elif frmt[i] == '#' and frmt[i+1] in IdentStartChars:
  169. inc(i)
  170. var j = i
  171. while frmt[j] in IdentChars: inc(j)
  172. var ident = newLit(substr(frmt, i, j-1))
  173. i = j
  174. flushStrLit()
  175. result.add newCall(formatValue, resVar, newCall(ident"cgsymValue", m, ident))
  176. elif frmt[i] == '#' and frmt[i+1] == '$':
  177. inc(i, 2)
  178. var j = 0
  179. while frmt[i] in Digits:
  180. j = (j * 10) + ord(frmt[i]) - ord('0')
  181. inc(i)
  182. let ident = args[j-1]
  183. flushStrLit()
  184. result.add newCall(formatValue, resVar, newCall(ident"cgsymValue", m, ident))
  185. elif frmt[i] == '#' and frmt[i+1] == '#':
  186. inc(i, 2)
  187. strLit.add("#")
  188. else:
  189. strLit.add(frmt[i])
  190. inc(i)
  191. flushStrLit()
  192. result.add newCall(ident"rope", resVar)
  193. proc addIndent(p: BProc; result: var Rope) =
  194. var i = result.len
  195. let newLen = i + p.blocks.len
  196. result.setLen newLen
  197. while i < newLen:
  198. result[i] = '\t'
  199. inc i
  200. template appcg(m: BModule, c: var Rope, frmt: FormatStr,
  201. args: untyped) =
  202. c.add(ropecg(m, frmt, args))
  203. template appcg(m: BModule, sec: TCFileSection, frmt: FormatStr,
  204. args: untyped) =
  205. m.s[sec].add(ropecg(m, frmt, args))
  206. template appcg(p: BProc, sec: TCProcSection, frmt: FormatStr,
  207. args: untyped) =
  208. p.s(sec).add(ropecg(p.module, frmt, args))
  209. template line(p: BProc, sec: TCProcSection, r: string) =
  210. addIndent p, p.s(sec)
  211. p.s(sec).add(r)
  212. template lineF(p: BProc, sec: TCProcSection, frmt: FormatStr,
  213. args: untyped) =
  214. addIndent p, p.s(sec)
  215. p.s(sec).add(frmt % args)
  216. template lineCg(p: BProc, sec: TCProcSection, frmt: FormatStr,
  217. args: untyped) =
  218. addIndent p, p.s(sec)
  219. p.s(sec).add(ropecg(p.module, frmt, args))
  220. template linefmt(p: BProc, sec: TCProcSection, frmt: FormatStr,
  221. args: untyped) =
  222. addIndent p, p.s(sec)
  223. p.s(sec).add(ropecg(p.module, frmt, args))
  224. proc safeLineNm(info: TLineInfo): int =
  225. result = toLinenumber(info)
  226. if result < 0: result = 0 # negative numbers are not allowed in #line
  227. proc genPostprocessDir(field1, field2, field3: string): string =
  228. result = postprocessDirStart & field1 & postprocessDirSep & field2 & postprocessDirSep & field3 & postprocessDirEnd
  229. proc genCLineDir(r: var Rope, fileIdx: FileIndex, line: int; conf: ConfigRef) =
  230. assert line >= 0
  231. if optLineDir in conf.options and line > 0:
  232. if fileIdx == InvalidFileIdx:
  233. r.add(rope("\n#line " & $line & " \"generated_not_to_break_here\"\n"))
  234. else:
  235. r.add(rope("\n#line " & $line & " FX_" & $fileIdx.int32 & "\n"))
  236. proc genCLineDir(r: var Rope, fileIdx: FileIndex, line: int; p: BProc; info: TLineInfo; lastFileIndex: FileIndex) =
  237. assert line >= 0
  238. if optLineDir in p.config.options and line > 0:
  239. if fileIdx == InvalidFileIdx:
  240. r.add(rope("\n#line " & $line & " \"generated_not_to_break_here\"\n"))
  241. else:
  242. r.add(rope("\n#line " & $line & " FX_" & $fileIdx.int32 & "\n"))
  243. proc genCLineDir(r: var Rope, info: TLineInfo; conf: ConfigRef) =
  244. if optLineDir in conf.options:
  245. genCLineDir(r, info.fileIndex, info.safeLineNm, conf)
  246. proc freshLineInfo(p: BProc; info: TLineInfo): bool =
  247. if p.lastLineInfo.line != info.line or
  248. p.lastLineInfo.fileIndex != info.fileIndex:
  249. p.lastLineInfo.line = info.line
  250. p.lastLineInfo.fileIndex = info.fileIndex
  251. result = true
  252. else:
  253. result = false
  254. proc genCLineDir(r: var Rope, p: BProc, info: TLineInfo; conf: ConfigRef) =
  255. if optLineDir in conf.options:
  256. let lastFileIndex = p.lastLineInfo.fileIndex
  257. if freshLineInfo(p, info):
  258. genCLineDir(r, info.fileIndex, info.safeLineNm, p, info, lastFileIndex)
  259. proc genLineDir(p: BProc, t: PNode) =
  260. if p == p.module.preInitProc: return
  261. let line = t.info.safeLineNm
  262. if optEmbedOrigSrc in p.config.globalOptions:
  263. p.s(cpsStmts).add("//" & sourceLine(p.config, t.info) & "\L")
  264. let lastFileIndex = p.lastLineInfo.fileIndex
  265. let freshLine = freshLineInfo(p, t.info)
  266. if freshLine:
  267. genCLineDir(p.s(cpsStmts), t.info.fileIndex, line, p, t.info, lastFileIndex)
  268. if ({optLineTrace, optStackTrace} * p.options == {optLineTrace, optStackTrace}) and
  269. (p.prc == nil or sfPure notin p.prc.flags) and t.info.fileIndex != InvalidFileIdx:
  270. if freshLine:
  271. line(p, cpsStmts, genPostprocessDir("nimln", $line, $t.info.fileIndex.int32))
  272. proc accessThreadLocalVar(p: BProc, s: PSym)
  273. proc emulatedThreadVars(conf: ConfigRef): bool {.inline.}
  274. proc genProc(m: BModule, prc: PSym)
  275. proc raiseInstr(p: BProc; result: var Rope)
  276. template compileToCpp(m: BModule): untyped =
  277. m.config.backend == backendCpp or sfCompileToCpp in m.module.flags
  278. proc getTempName(m: BModule): Rope =
  279. result = m.tmpBase & rope(m.labels)
  280. inc m.labels
  281. proc rdLoc(a: TLoc): Rope =
  282. # 'read' location (deref if indirect)
  283. if lfIndirect in a.flags:
  284. result = "(*" & a.snippet & ")"
  285. else:
  286. result = a.snippet
  287. proc addRdLoc(a: TLoc; result: var Rope) =
  288. if lfIndirect in a.flags:
  289. result.add "(*" & a.snippet & ")"
  290. else:
  291. result.add a.snippet
  292. proc lenField(p: BProc): Rope {.inline.} =
  293. result = rope(if p.module.compileToCpp: "len" else: "Sup.len")
  294. proc lenExpr(p: BProc; a: TLoc): Rope =
  295. if optSeqDestructors in p.config.globalOptions:
  296. result = rdLoc(a) & ".len"
  297. else:
  298. result = "($1 ? $1->$2 : 0)" % [rdLoc(a), lenField(p)]
  299. proc dataFieldAccessor(p: BProc, sym: Rope): Rope =
  300. if optSeqDestructors in p.config.globalOptions:
  301. result = "(" & sym & ").p"
  302. else:
  303. result = sym
  304. proc dataField(p: BProc): Rope =
  305. if optSeqDestructors in p.config.globalOptions:
  306. result = rope".p->data"
  307. else:
  308. result = rope"->data"
  309. proc genProcPrototype(m: BModule, sym: PSym)
  310. include cbuilder
  311. include ccgliterals
  312. include ccgtypes
  313. # ------------------------------ Manager of temporaries ------------------
  314. template mapTypeChooser(n: PNode): TSymKind =
  315. (if n.kind == nkSym: n.sym.kind else: skVar)
  316. template mapTypeChooser(a: TLoc): TSymKind = mapTypeChooser(a.lode)
  317. proc addAddrLoc(conf: ConfigRef; a: TLoc; result: var Rope) =
  318. if lfIndirect notin a.flags and mapType(conf, a.t, mapTypeChooser(a) == skParam) != ctArray:
  319. result.add "(&" & a.snippet & ")"
  320. else:
  321. result.add a.snippet
  322. proc addrLoc(conf: ConfigRef; a: TLoc): Rope =
  323. if lfIndirect notin a.flags and mapType(conf, a.t, mapTypeChooser(a) == skParam) != ctArray:
  324. result = "(&" & a.snippet & ")"
  325. else:
  326. result = a.snippet
  327. proc byRefLoc(p: BProc; a: TLoc): Rope =
  328. if lfIndirect notin a.flags and mapType(p.config, a.t, mapTypeChooser(a) == skParam) != ctArray and not
  329. p.module.compileToCpp:
  330. result = "(&" & a.snippet & ")"
  331. else:
  332. result = a.snippet
  333. proc rdCharLoc(a: TLoc): Rope =
  334. # read a location that may need a char-cast:
  335. result = rdLoc(a)
  336. if skipTypes(a.t, abstractRange).kind == tyChar:
  337. result = "((NU8)($1))" % [result]
  338. type
  339. TAssignmentFlag = enum
  340. needToCopy
  341. needToCopySinkParam
  342. needTempForOpenArray
  343. needAssignCall
  344. TAssignmentFlags = set[TAssignmentFlag]
  345. proc genObjConstr(p: BProc, e: PNode, d: var TLoc)
  346. proc rawConstExpr(p: BProc, n: PNode; d: var TLoc)
  347. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags)
  348. type
  349. ObjConstrMode = enum
  350. constructObj,
  351. constructRefObj
  352. proc genObjectInit(p: BProc, section: TCProcSection, t: PType, a: var TLoc,
  353. mode: ObjConstrMode) =
  354. #if optNimV2 in p.config.globalOptions: return
  355. case analyseObjectWithTypeField(t)
  356. of frNone:
  357. discard
  358. of frHeader:
  359. var r = rdLoc(a)
  360. if mode == constructRefObj: r = "(*$1)" % [r]
  361. var s = skipTypes(t, abstractInst)
  362. if not p.module.compileToCpp:
  363. while s.kind == tyObject and s[0] != nil:
  364. r.add(".Sup")
  365. s = skipTypes(s[0], skipPtrs)
  366. if optTinyRtti in p.config.globalOptions:
  367. linefmt(p, section, "$1.m_type = $2;$n", [r, genTypeInfoV2(p.module, t, a.lode.info)])
  368. else:
  369. linefmt(p, section, "$1.m_type = $2;$n", [r, genTypeInfoV1(p.module, t, a.lode.info)])
  370. of frEmbedded:
  371. if optTinyRtti in p.config.globalOptions:
  372. var tmp: TLoc = default(TLoc)
  373. if mode == constructRefObj:
  374. let objType = t.skipTypes(abstractInst+{tyRef})
  375. rawConstExpr(p, newNodeIT(nkType, a.lode.info, objType), tmp)
  376. linefmt(p, cpsStmts,
  377. "#nimCopyMem((void*)$1, (NIM_CONST void*)&$2, sizeof($3));$n",
  378. [rdLoc(a), rdLoc(tmp), getTypeDesc(p.module, objType, descKindFromSymKind mapTypeChooser(a))])
  379. else:
  380. rawConstExpr(p, newNodeIT(nkType, a.lode.info, t), tmp)
  381. genAssignment(p, a, tmp, {})
  382. else:
  383. # worst case for performance:
  384. var r = if mode == constructObj: addrLoc(p.config, a) else: rdLoc(a)
  385. linefmt(p, section, "#objectInit($1, $2);$n", [r, genTypeInfoV1(p.module, t, a.lode.info)])
  386. if isException(t):
  387. var r = rdLoc(a)
  388. if mode == constructRefObj: r = "(*$1)" % [r]
  389. var s = skipTypes(t, abstractInst)
  390. if not p.module.compileToCpp:
  391. while s.kind == tyObject and s[0] != nil and s.sym.magic != mException:
  392. r.add(".Sup")
  393. s = skipTypes(s[0], skipPtrs)
  394. linefmt(p, section, "$1.name = $2;$n", [r, makeCString(t.skipTypes(abstractInst).sym.name.s)])
  395. proc genRefAssign(p: BProc, dest, src: TLoc)
  396. proc isComplexValueType(t: PType): bool {.inline.} =
  397. let t = t.skipTypes(abstractInst + tyUserTypeClasses)
  398. result = t.kind in {tyArray, tySet, tyTuple, tyObject, tyOpenArray} or
  399. (t.kind == tyProc and t.callConv == ccClosure)
  400. include ccgreset
  401. proc resetLoc(p: BProc, loc: var TLoc) =
  402. let containsGcRef = optSeqDestructors notin p.config.globalOptions and containsGarbageCollectedRef(loc.t)
  403. let typ = skipTypes(loc.t, abstractVarRange)
  404. if isImportedCppType(typ):
  405. var didGenTemp = false
  406. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(loc), genCppInitializer(p.module, p, typ, didGenTemp)])
  407. return
  408. if optSeqDestructors in p.config.globalOptions and typ.kind in {tyString, tySequence}:
  409. assert loc.snippet != ""
  410. let atyp = skipTypes(loc.t, abstractInst)
  411. if atyp.kind in {tyVar, tyLent}:
  412. linefmt(p, cpsStmts, "$1->len = 0; $1->p = NIM_NIL;$n", [rdLoc(loc)])
  413. else:
  414. linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
  415. elif not isComplexValueType(typ):
  416. if containsGcRef:
  417. var nilLoc: TLoc = initLoc(locTemp, loc.lode, OnStack)
  418. nilLoc.snippet = rope("NIM_NIL")
  419. genRefAssign(p, loc, nilLoc)
  420. else:
  421. linefmt(p, cpsStmts, "$1 = 0;$n", [rdLoc(loc)])
  422. else:
  423. if loc.storage != OnStack and containsGcRef:
  424. specializeReset(p, loc)
  425. when false:
  426. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  427. [addrLoc(p.config, loc), genTypeInfoV1(p.module, loc.t, loc.lode.info)])
  428. # XXX: generated reset procs should not touch the m_type
  429. # field, so disabling this should be safe:
  430. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  431. else:
  432. # array passed as argument decayed into pointer, bug #7332
  433. # so we use getTypeDesc here rather than rdLoc(loc)
  434. let tyDesc = getTypeDesc(p.module, loc.t, descKindFromSymKind mapTypeChooser(loc))
  435. if p.module.compileToCpp and isOrHasImportedCppType(typ):
  436. if lfIndirect in loc.flags:
  437. #C++ cant be just zeroed. We need to call the ctors
  438. var tmp = getTemp(p, loc.t)
  439. linefmt(p, cpsStmts,"#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  440. [addrLoc(p.config, loc), addrLoc(p.config, tmp), tyDesc])
  441. else:
  442. linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  443. [addrLoc(p.config, loc), tyDesc])
  444. # XXX: We can be extra clever here and call memset only
  445. # on the bytes following the m_type field?
  446. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  447. proc constructLoc(p: BProc, loc: var TLoc, isTemp = false) =
  448. let typ = loc.t
  449. if optSeqDestructors in p.config.globalOptions and skipTypes(typ, abstractInst + {tyStatic}).kind in {tyString, tySequence}:
  450. linefmt(p, cpsStmts, "$1.len = 0; $1.p = NIM_NIL;$n", [rdLoc(loc)])
  451. elif not isComplexValueType(typ):
  452. if containsGarbageCollectedRef(loc.t):
  453. var nilLoc: TLoc = initLoc(locTemp, loc.lode, OnStack)
  454. nilLoc.snippet = rope("NIM_NIL")
  455. genRefAssign(p, loc, nilLoc)
  456. else:
  457. linefmt(p, cpsStmts, "$1 = ($2)0;$n", [rdLoc(loc),
  458. getTypeDesc(p.module, typ, descKindFromSymKind mapTypeChooser(loc))])
  459. else:
  460. if (not isTemp or containsGarbageCollectedRef(loc.t)) and not hasNoInit(loc.t):
  461. # don't use nimZeroMem for temporary values for performance if we can
  462. # avoid it:
  463. if not isOrHasImportedCppType(typ):
  464. linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  465. [addrLoc(p.config, loc), getTypeDesc(p.module, typ, descKindFromSymKind mapTypeChooser(loc))])
  466. genObjectInit(p, cpsStmts, loc.t, loc, constructObj)
  467. proc initLocalVar(p: BProc, v: PSym, immediateAsgn: bool) =
  468. if sfNoInit notin v.flags:
  469. # we know it is a local variable and thus on the stack!
  470. # If ``not immediateAsgn`` it is not initialized in a binding like
  471. # ``var v = X`` and thus we need to init it.
  472. # If ``v`` contains a GC-ref we may pass it to ``unsureAsgnRef`` somehow
  473. # which requires initialization. However this can really only happen if
  474. # ``var v = X()`` gets transformed into ``X(&v)``.
  475. # Nowadays the logic in ccgcalls deals with this case however.
  476. if not immediateAsgn:
  477. constructLoc(p, v.loc)
  478. proc getTemp(p: BProc, t: PType, needsInit=false): TLoc =
  479. inc(p.labels)
  480. result = TLoc(snippet: "T" & rope(p.labels) & "_", k: locTemp, lode: lodeTyp t,
  481. storage: OnStack, flags: {})
  482. if p.module.compileToCpp and isOrHasImportedCppType(t):
  483. var didGenTemp = false
  484. linefmt(p, cpsLocals, "$1 $2$3;$n", [getTypeDesc(p.module, t, dkVar), result.snippet,
  485. genCppInitializer(p.module, p, t, didGenTemp)])
  486. else:
  487. linefmt(p, cpsLocals, "$1 $2;$n", [getTypeDesc(p.module, t, dkVar), result.snippet])
  488. constructLoc(p, result, not needsInit)
  489. when false:
  490. # XXX Introduce a compiler switch in order to detect these easily.
  491. if getSize(p.config, t) > 1024 * 1024:
  492. if p.prc != nil:
  493. echo "ENORMOUS TEMPORARY! ", p.config $ p.prc.info
  494. else:
  495. echo "ENORMOUS TEMPORARY! ", p.config $ p.lastLineInfo
  496. writeStackTrace()
  497. proc getTempCpp(p: BProc, t: PType, value: Rope): TLoc =
  498. inc(p.labels)
  499. result = TLoc(snippet: "T" & rope(p.labels) & "_", k: locTemp, lode: lodeTyp t,
  500. storage: OnStack, flags: {})
  501. linefmt(p, cpsStmts, "auto $1 = $2;$n", [result.snippet, value])
  502. proc getIntTemp(p: BProc): TLoc =
  503. inc(p.labels)
  504. result = TLoc(snippet: "T" & rope(p.labels) & "_", k: locTemp,
  505. storage: OnStack, lode: lodeTyp getSysType(p.module.g.graph, unknownLineInfo, tyInt),
  506. flags: {})
  507. linefmt(p, cpsLocals, "NI $1;$n", [result.snippet])
  508. proc localVarDecl(p: BProc; n: PNode): Rope =
  509. result = ""
  510. let s = n.sym
  511. if s.loc.k == locNone:
  512. fillLocalName(p, s)
  513. fillLoc(s.loc, locLocalVar, n, OnStack)
  514. if s.kind == skLet: incl(s.loc.flags, lfNoDeepCopy)
  515. if s.kind in {skLet, skVar, skField, skForVar} and s.alignment > 0:
  516. result.addf("NIM_ALIGN($1) ", [rope(s.alignment)])
  517. genCLineDir(result, p, n.info, p.config)
  518. result.add getTypeDesc(p.module, s.typ, dkVar)
  519. if sfCodegenDecl notin s.flags:
  520. if sfRegister in s.flags: result.add(" register")
  521. #elif skipTypes(s.typ, abstractInst).kind in GcTypeKinds:
  522. # decl.add(" GC_GUARD")
  523. if sfVolatile in s.flags: result.add(" volatile")
  524. if sfNoalias in s.flags: result.add(" NIM_NOALIAS")
  525. result.add(" ")
  526. result.add(s.loc.snippet)
  527. else:
  528. result = runtimeFormat(s.cgDeclFrmt, [result, s.loc.snippet])
  529. proc assignLocalVar(p: BProc, n: PNode) =
  530. #assert(s.loc.k == locNone) # not yet assigned
  531. # this need not be fulfilled for inline procs; they are regenerated
  532. # for each module that uses them!
  533. let nl = if optLineDir in p.config.options: "" else: "\n"
  534. var decl = localVarDecl(p, n)
  535. if p.module.compileToCpp and isOrHasImportedCppType(n.typ):
  536. var didGenTemp = false
  537. decl.add genCppInitializer(p.module, p, n.typ, didGenTemp)
  538. decl.add ";" & nl
  539. line(p, cpsLocals, decl)
  540. include ccgthreadvars
  541. proc varInDynamicLib(m: BModule, sym: PSym)
  542. proc treatGlobalDifferentlyForHCR(m: BModule, s: PSym): bool =
  543. return m.hcrOn and {sfThread, sfGlobal} * s.flags == {sfGlobal} and
  544. ({lfNoDecl, lfHeader} * s.loc.flags == {})
  545. # and s.owner.kind == skModule # owner isn't always a module (global pragma on local var)
  546. # and s.loc.k == locGlobalVar # loc isn't always initialized when this proc is used
  547. proc genGlobalVarDecl(p: BProc, n: PNode; td, value: Rope; decl: var Rope) =
  548. let s = n.sym
  549. if sfCodegenDecl notin s.flags:
  550. if s.kind in {skLet, skVar, skField, skForVar} and s.alignment > 0:
  551. decl.addf "NIM_ALIGN($1) ", [rope(s.alignment)]
  552. if p.hcrOn: decl.add("static ")
  553. elif sfImportc in s.flags: decl.add("extern ")
  554. elif lfExportLib in s.loc.flags: decl.add("N_LIB_EXPORT_VAR ")
  555. else: decl.add("N_LIB_PRIVATE ")
  556. if s.kind == skLet and value != "": decl.add("NIM_CONST ")
  557. decl.add(td)
  558. if p.hcrOn: decl.add("*")
  559. if sfRegister in s.flags: decl.add(" register")
  560. if sfVolatile in s.flags: decl.add(" volatile")
  561. if sfNoalias in s.flags: decl.add(" NIM_NOALIAS")
  562. else:
  563. if value != "":
  564. decl = runtimeFormat(s.cgDeclFrmt & " = $#;$n", [td, s.loc.snippet, value])
  565. else:
  566. decl = runtimeFormat(s.cgDeclFrmt & ";$n", [td, s.loc.snippet])
  567. proc genCppVarForCtor(p: BProc; call: PNode; decl: var Rope; didGenTemp: var bool)
  568. proc assignGlobalVar(p: BProc, n: PNode; value: Rope) =
  569. let s = n.sym
  570. if s.loc.k == locNone:
  571. fillBackendName(p.module, s)
  572. fillLoc(s.loc, locGlobalVar, n, OnHeap)
  573. if treatGlobalDifferentlyForHCR(p.module, s): incl(s.loc.flags, lfIndirect)
  574. if lfDynamicLib in s.loc.flags:
  575. var q = findPendingModule(p.module, s)
  576. if q != nil and not containsOrIncl(q.declaredThings, s.id):
  577. varInDynamicLib(q, s)
  578. else:
  579. s.loc.snippet = mangleDynLibProc(s)
  580. if value != "":
  581. internalError(p.config, n.info, ".dynlib variables cannot have a value")
  582. return
  583. useHeader(p.module, s)
  584. if lfNoDecl in s.loc.flags: return
  585. if not containsOrIncl(p.module.declaredThings, s.id):
  586. if sfThread in s.flags:
  587. declareThreadVar(p.module, s, sfImportc in s.flags)
  588. if value != "":
  589. internalError(p.config, n.info, ".threadvar variables cannot have a value")
  590. else:
  591. var decl: Rope = ""
  592. let td = getTypeDesc(p.module, s.loc.t, dkVar)
  593. genGlobalVarDecl(p, n, td, value, decl)
  594. if s.constraint.isNil:
  595. if value != "":
  596. if p.module.compileToCpp and value.startsWith "{{}":
  597. # TODO: taking this branch, re"\{\{\}(,\s\{\})*\}" might be emitted, resulting in
  598. # either warnings (GCC 12.2+) or errors (Clang 15, MSVC 19.3+) of C++11+ compilers **when
  599. # explicit constructors are around** due to overload resolution rules in place [^0][^1][^2]
  600. # *Workaround* here: have C++'s static initialization mechanism do the default init work,
  601. # for us lacking a deeper knowledge of an imported object's constructors' ex-/implicitness
  602. # (so far) *and yet* trying to achieve default initialization.
  603. # Still, generating {}s in genConstObjConstr() just to omit them here is faaaar from ideal;
  604. # need to figure out a better way, possibly by keeping around more data about the
  605. # imported objects' contructors?
  606. #
  607. # [^0]: https://en.cppreference.com/w/cpp/language/aggregate_initialization
  608. # [^1]: https://cplusplus.github.io/CWG/issues/1518.html
  609. # [^2]: https://eel.is/c++draft/over.match.ctor
  610. decl.addf(" $1;$n", [s.loc.snippet])
  611. else:
  612. decl.addf(" $1 = $2;$n", [s.loc.snippet, value])
  613. else:
  614. decl.addf(" $1;$n", [s.loc.snippet])
  615. p.module.s[cfsVars].add(decl)
  616. if p.withinLoop > 0 and value == "":
  617. # fixes tests/run/tzeroarray:
  618. resetLoc(p, s.loc)
  619. proc callGlobalVarCppCtor(p: BProc; v: PSym; vn, value: PNode; didGenTemp: var bool) =
  620. let s = vn.sym
  621. fillBackendName(p.module, s)
  622. fillLoc(s.loc, locGlobalVar, vn, OnHeap)
  623. var decl: Rope = ""
  624. let td = getTypeDesc(p.module, vn.sym.typ, dkVar)
  625. genGlobalVarDecl(p, vn, td, "", decl)
  626. decl.add " " & $s.loc.snippet
  627. genCppVarForCtor(p, value, decl, didGenTemp)
  628. if didGenTemp: return # generated in the caller
  629. p.module.s[cfsVars].add decl
  630. proc assignParam(p: BProc, s: PSym, retType: PType) =
  631. assert(s.loc.snippet != "")
  632. scopeMangledParam(p, s)
  633. proc fillProcLoc(m: BModule; n: PNode) =
  634. let sym = n.sym
  635. if sym.loc.k == locNone:
  636. fillBackendName(m, sym)
  637. fillLoc(sym.loc, locProc, n, OnStack)
  638. proc getLabel(p: BProc): TLabel =
  639. inc(p.labels)
  640. result = "LA" & rope(p.labels) & "_"
  641. proc fixLabel(p: BProc, labl: TLabel) =
  642. p.s(cpsStmts).add("$1: ;$n" % [labl])
  643. proc genVarPrototype(m: BModule, n: PNode)
  644. proc requestConstImpl(p: BProc, sym: PSym)
  645. proc genStmts(p: BProc, t: PNode)
  646. proc expr(p: BProc, n: PNode, d: var TLoc)
  647. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc)
  648. proc intLiteral(i: BiggestInt; result: var Rope)
  649. proc genLiteral(p: BProc, n: PNode; result: var Rope)
  650. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope; argsCounter: var int)
  651. proc raiseExit(p: BProc)
  652. proc raiseExitCleanup(p: BProc, destroy: string)
  653. proc initLocExpr(p: BProc, e: PNode, flags: TLocFlags = {}): TLoc =
  654. result = initLoc(locNone, e, OnUnknown, flags)
  655. expr(p, e, result)
  656. proc initLocExprSingleUse(p: BProc, e: PNode): TLoc =
  657. result = initLoc(locNone, e, OnUnknown)
  658. if e.kind in nkCallKinds and (e[0].kind != nkSym or e[0].sym.magic == mNone):
  659. # We cannot check for tfNoSideEffect here because of mutable parameters.
  660. discard "bug #8202; enforce evaluation order for nested calls for C++ too"
  661. # We may need to consider that 'f(g())' cannot be rewritten to 'tmp = g(); f(tmp)'
  662. # if 'tmp' lacks a move/assignment operator.
  663. if e[0].kind == nkSym and sfCompileToCpp in e[0].sym.flags:
  664. result.flags.incl lfSingleUse
  665. else:
  666. result.flags.incl lfSingleUse
  667. expr(p, e, result)
  668. include ccgcalls, "ccgstmts.nim"
  669. proc initFrame(p: BProc, procname, filename: Rope): Rope =
  670. const frameDefines = """
  671. $1define nimfr_(proc, file) \
  672. TFrame FR_; \
  673. FR_.procname = proc; FR_.filename = file; FR_.line = 0; FR_.len = 0; #nimFrame(&FR_);
  674. $1define nimfrs_(proc, file, slots, length) \
  675. struct {TFrame* prev;NCSTRING procname;NI line;NCSTRING filename;NI len;VarSlot s[slots];} FR_; \
  676. FR_.procname = proc; FR_.filename = file; FR_.line = 0; FR_.len = length; #nimFrame((TFrame*)&FR_);
  677. $1define nimln_(n) \
  678. FR_.line = n;
  679. $1define nimlf_(n, file) \
  680. FR_.line = n; FR_.filename = file;
  681. """
  682. if p.module.s[cfsFrameDefines].len == 0:
  683. appcg(p.module, p.module.s[cfsFrameDefines], frameDefines, ["#"])
  684. cgsym(p.module, "nimFrame")
  685. result = ropecg(p.module, "\tnimfr_($1, $2);$n", [procname, filename])
  686. proc initFrameNoDebug(p: BProc; frame, procname, filename: Rope; line: int): Rope =
  687. cgsym(p.module, "nimFrame")
  688. p.blocks[0].sections[cpsLocals].addf("TFrame $1;$n", [frame])
  689. result = ropecg(p.module, "\t$1.procname = $2; $1.filename = $3; " &
  690. " $1.line = $4; $1.len = -1; nimFrame(&$1);$n",
  691. [frame, procname, filename, line])
  692. proc deinitFrameNoDebug(p: BProc; frame: Rope): Rope =
  693. result = ropecg(p.module, "\t#popFrameOfAddr(&$1);$n", [frame])
  694. proc deinitFrame(p: BProc): Rope =
  695. result = ropecg(p.module, "\t#popFrame();$n", [])
  696. include ccgexprs
  697. # ----------------------------- dynamic library handling -----------------
  698. # We don't finalize dynamic libs as the OS does this for us.
  699. proc isGetProcAddr(lib: PLib): bool =
  700. let n = lib.path
  701. result = n.kind in nkCallKinds and n.typ != nil and
  702. n.typ.kind in {tyPointer, tyProc}
  703. proc loadDynamicLib(m: BModule, lib: PLib) =
  704. assert(lib != nil)
  705. if not lib.generated:
  706. lib.generated = true
  707. var tmp = getTempName(m)
  708. assert(lib.name == "")
  709. lib.name = tmp # BUGFIX: cgsym has awful side-effects
  710. m.s[cfsVars].addf("static void* $1;$n", [tmp])
  711. if lib.path.kind in {nkStrLit..nkTripleStrLit}:
  712. var s: TStringSeq = @[]
  713. libCandidates(lib.path.strVal, s)
  714. rawMessage(m.config, hintDependency, lib.path.strVal)
  715. var loadlib: Rope = ""
  716. for i in 0..high(s):
  717. inc(m.labels)
  718. if i > 0: loadlib.add("||")
  719. let n = newStrNode(nkStrLit, s[i])
  720. n.info = lib.path.info
  721. appcg(m, loadlib, "($1 = #nimLoadLibrary(", [tmp])
  722. genStringLiteral(m, n, loadlib)
  723. loadlib.addf "))$n", []
  724. appcg(m, m.s[cfsDynLibInit],
  725. "if (!($1)) #nimLoadLibraryError(",
  726. [loadlib])
  727. genStringLiteral(m, lib.path, m.s[cfsDynLibInit])
  728. m.s[cfsDynLibInit].addf ");$n", []
  729. else:
  730. var p = newProc(nil, m)
  731. p.options.excl optStackTrace
  732. p.flags.incl nimErrorFlagDisabled
  733. var dest: TLoc = initLoc(locTemp, lib.path, OnStack)
  734. dest.snippet = getTempName(m)
  735. appcg(m, m.s[cfsDynLibInit],"$1 $2;$n",
  736. [getTypeDesc(m, lib.path.typ, dkVar), rdLoc(dest)])
  737. expr(p, lib.path, dest)
  738. m.s[cfsVars].add(p.s(cpsLocals))
  739. m.s[cfsDynLibInit].add(p.s(cpsInit))
  740. m.s[cfsDynLibInit].add(p.s(cpsStmts))
  741. appcg(m, m.s[cfsDynLibInit],
  742. "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n",
  743. [tmp, rdLoc(dest)])
  744. if lib.name == "": internalError(m.config, "loadDynamicLib")
  745. proc mangleDynLibProc(sym: PSym): Rope =
  746. # we have to build this as a single rope in order not to trip the
  747. # optimization in genInfixCall, see test tests/cpp/t8241.nim
  748. if sfCompilerProc in sym.flags:
  749. # NOTE: sym.loc.snippet is the external name!
  750. result = rope(sym.name.s)
  751. else:
  752. result = rope(strutils.`%`("Dl_$1_", $sym.id))
  753. proc symInDynamicLib(m: BModule, sym: PSym) =
  754. var lib = sym.annex
  755. let isCall = isGetProcAddr(lib)
  756. var extname = sym.loc.snippet
  757. if not isCall: loadDynamicLib(m, lib)
  758. var tmp = mangleDynLibProc(sym)
  759. sym.loc.snippet = tmp # from now on we only need the internal name
  760. sym.typ.sym = nil # generate a new name
  761. inc(m.labels, 2)
  762. if isCall:
  763. let n = lib.path
  764. var a: TLoc = initLocExpr(m.initProc, n[0])
  765. var params = rdLoc(a) & "("
  766. for i in 1..<n.len-1:
  767. a = initLocExpr(m.initProc, n[i])
  768. params.add(rdLoc(a))
  769. params.add(", ")
  770. let load = "\t$1 = ($2) ($3$4));$n" %
  771. [tmp, getTypeDesc(m, sym.typ, dkVar), params, makeCString($extname)]
  772. var last = lastSon(n)
  773. if last.kind == nkHiddenStdConv: last = last[1]
  774. internalAssert(m.config, last.kind == nkStrLit)
  775. let idx = last.strVal
  776. if idx.len == 0:
  777. m.initProc.s(cpsStmts).add(load)
  778. elif idx.len == 1 and idx[0] in {'0'..'9'}:
  779. m.extensionLoaders[idx[0]].add(load)
  780. else:
  781. internalError(m.config, sym.info, "wrong index: " & idx)
  782. else:
  783. appcg(m, m.s[cfsDynLibInit],
  784. "\t$1 = ($2) #nimGetProcAddr($3, $4);$n",
  785. [tmp, getTypeDesc(m, sym.typ, dkVar), lib.name, makeCString($extname)])
  786. m.s[cfsVars].addf("$2 $1;$n", [sym.loc.snippet, getTypeDesc(m, sym.loc.t, dkVar)])
  787. proc varInDynamicLib(m: BModule, sym: PSym) =
  788. var lib = sym.annex
  789. var extname = sym.loc.snippet
  790. loadDynamicLib(m, lib)
  791. incl(sym.loc.flags, lfIndirect)
  792. var tmp = mangleDynLibProc(sym)
  793. sym.loc.snippet = tmp # from now on we only need the internal name
  794. inc(m.labels, 2)
  795. appcg(m, m.s[cfsDynLibInit],
  796. "$1 = ($2*) #nimGetProcAddr($3, $4);$n",
  797. [tmp, getTypeDesc(m, sym.typ, dkVar), lib.name, makeCString($extname)])
  798. m.s[cfsVars].addf("$2* $1;$n",
  799. [sym.loc.snippet, getTypeDesc(m, sym.loc.t, dkVar)])
  800. proc symInDynamicLibPartial(m: BModule, sym: PSym) =
  801. sym.loc.snippet = mangleDynLibProc(sym)
  802. sym.typ.sym = nil # generate a new name
  803. proc cgsymImpl(m: BModule; sym: PSym) {.inline.} =
  804. case sym.kind
  805. of skProc, skFunc, skMethod, skConverter, skIterator: genProc(m, sym)
  806. of skVar, skResult, skLet: genVarPrototype(m, newSymNode sym)
  807. of skType: discard getTypeDesc(m, sym.typ)
  808. else: internalError(m.config, "cgsym: " & $sym.kind)
  809. proc cgsym(m: BModule, name: string) =
  810. let sym = magicsys.getCompilerProc(m.g.graph, name)
  811. if sym != nil:
  812. cgsymImpl m, sym
  813. else:
  814. rawMessage(m.config, errGenerated, "system module needs: " & name)
  815. proc cgsymValue(m: BModule, name: string): Rope =
  816. let sym = magicsys.getCompilerProc(m.g.graph, name)
  817. if sym != nil:
  818. cgsymImpl m, sym
  819. else:
  820. rawMessage(m.config, errGenerated, "system module needs: " & name)
  821. result = sym.loc.snippet
  822. if m.hcrOn and sym != nil and sym.kind in {skProc..skIterator}:
  823. result.addActualSuffixForHCR(m.module, sym)
  824. proc generateHeaders(m: BModule) =
  825. var nimbase = m.config.nimbasePattern
  826. if nimbase == "": nimbase = "nimbase.h"
  827. m.s[cfsHeaders].addf("\L#include \"$1\"\L", [nimbase])
  828. for it in m.headerFiles:
  829. if it[0] == '#':
  830. m.s[cfsHeaders].add(rope(it.replace('`', '"') & "\L"))
  831. elif it[0] notin {'"', '<'}:
  832. m.s[cfsHeaders].addf("#include \"$1\"$N", [rope(it)])
  833. else:
  834. m.s[cfsHeaders].addf("#include $1$N", [rope(it)])
  835. m.s[cfsHeaders].add("""#undef LANGUAGE_C
  836. #undef MIPSEB
  837. #undef MIPSEL
  838. #undef PPC
  839. #undef R3000
  840. #undef R4000
  841. #undef i386
  842. #undef linux
  843. #undef mips
  844. #undef near
  845. #undef far
  846. #undef powerpc
  847. #undef unix
  848. """)
  849. proc openNamespaceNim(namespace: string; result: var Rope) =
  850. result.add("namespace ")
  851. result.add(namespace)
  852. result.add(" {\L")
  853. proc closeNamespaceNim(result: var Rope) =
  854. result.add("}\L")
  855. proc closureSetup(p: BProc, prc: PSym) =
  856. if tfCapturesEnv notin prc.typ.flags: return
  857. # prc.ast[paramsPos].last contains the type we're after:
  858. var ls = lastSon(prc.ast[paramsPos])
  859. if ls.kind != nkSym:
  860. internalError(p.config, prc.info, "closure generation failed")
  861. var env = ls.sym
  862. #echo "created environment: ", env.id, " for ", prc.name.s
  863. assignLocalVar(p, ls)
  864. # generate cast assignment:
  865. if p.config.selectedGC == gcGo:
  866. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, ($2) ClE_0);$n",
  867. [addrLoc(p.config, env.loc), getTypeDesc(p.module, env.typ)])
  868. else:
  869. linefmt(p, cpsStmts, "$1 = ($2) ClE_0;$n",
  870. [rdLoc(env.loc), getTypeDesc(p.module, env.typ)])
  871. const harmless = {nkConstSection, nkTypeSection, nkEmpty, nkCommentStmt, nkTemplateDef,
  872. nkMacroDef, nkMixinStmt, nkBindStmt, nkFormalParams} +
  873. declarativeDefs
  874. proc containsResult(n: PNode): bool =
  875. result = false
  876. case n.kind
  877. of succ(nkEmpty)..pred(nkSym), succ(nkSym)..nkNilLit, harmless:
  878. discard
  879. of nkReturnStmt:
  880. for i in 0..<n.len:
  881. if containsResult(n[i]): return true
  882. result = n.len > 0 and n[0].kind == nkEmpty
  883. of nkSym:
  884. if n.sym.kind == skResult:
  885. result = true
  886. else:
  887. for i in 0..<n.len:
  888. if containsResult(n[i]): return true
  889. proc easyResultAsgn(n: PNode): PNode =
  890. result = nil
  891. case n.kind
  892. of nkStmtList, nkStmtListExpr:
  893. var i = 0
  894. while i < n.len and n[i].kind in harmless: inc i
  895. if i < n.len: result = easyResultAsgn(n[i])
  896. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  897. if n[0].kind == nkSym and n[0].sym.kind == skResult and not containsResult(n[1]):
  898. incl n.flags, nfPreventCg
  899. return n[1]
  900. of nkReturnStmt:
  901. if n.len > 0:
  902. result = easyResultAsgn(n[0])
  903. if result != nil: incl n.flags, nfPreventCg
  904. else: discard
  905. type
  906. InitResultEnum = enum Unknown, InitSkippable, InitRequired
  907. proc allPathsAsgnResult(p: BProc; n: PNode): InitResultEnum =
  908. # Exceptions coming from calls don't have not be considered here:
  909. #
  910. # proc bar(): string = raise newException(...)
  911. #
  912. # proc foo(): string =
  913. # # optimized out: 'reset(result)'
  914. # result = bar()
  915. #
  916. # try:
  917. # a = foo()
  918. # except:
  919. # echo "a was not written to"
  920. #
  921. template allPathsInBranch(it) =
  922. let a = allPathsAsgnResult(p, it)
  923. case a
  924. of InitRequired: return InitRequired
  925. of InitSkippable: discard
  926. of Unknown:
  927. # sticky, but can be overwritten by InitRequired:
  928. result = Unknown
  929. result = Unknown
  930. case n.kind
  931. of nkStmtList, nkStmtListExpr:
  932. for it in n:
  933. result = allPathsAsgnResult(p, it)
  934. if result != Unknown: return result
  935. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  936. if n[0].kind == nkSym and n[0].sym.kind == skResult:
  937. if not containsResult(n[1]):
  938. if allPathsAsgnResult(p, n[1]) == InitRequired:
  939. result = InitRequired
  940. else:
  941. result = InitSkippable
  942. else: result = InitRequired
  943. elif containsResult(n):
  944. result = InitRequired
  945. else:
  946. result = allPathsAsgnResult(p, n[1])
  947. of nkReturnStmt:
  948. if n.len > 0:
  949. if n[0].kind == nkEmpty and result != InitSkippable:
  950. # This is a bare `return` statement, if `result` was not initialized
  951. # anywhere else (or if we're not sure about this) let's require it to be
  952. # initialized. This avoids cases like #9286 where this heuristic lead to
  953. # wrong code being generated.
  954. result = InitRequired
  955. else: result = allPathsAsgnResult(p, n[0])
  956. of nkIfStmt, nkIfExpr:
  957. var exhaustive = false
  958. result = InitSkippable
  959. for it in n:
  960. # Every condition must not use 'result':
  961. if it.len == 2 and containsResult(it[0]):
  962. return InitRequired
  963. if it.len == 1: exhaustive = true
  964. allPathsInBranch(it.lastSon)
  965. # if the 'if' statement is not exhaustive and yet it touched 'result'
  966. # in some way, say Unknown.
  967. if not exhaustive: result = Unknown
  968. of nkCaseStmt:
  969. if containsResult(n[0]): return InitRequired
  970. result = InitSkippable
  971. var exhaustive = skipTypes(n[0].typ,
  972. abstractVarRange-{tyTypeDesc}).kind notin {tyFloat..tyFloat128, tyString, tyCstring}
  973. for i in 1..<n.len:
  974. let it = n[i]
  975. allPathsInBranch(it.lastSon)
  976. if it.kind == nkElse: exhaustive = true
  977. if not exhaustive: result = Unknown
  978. of nkWhileStmt:
  979. # some dubious code can assign the result in the 'while'
  980. # condition and that would be fine. Everything else isn't:
  981. result = allPathsAsgnResult(p, n[0])
  982. if result == Unknown:
  983. result = allPathsAsgnResult(p, n[1])
  984. # we cannot assume that the 'while' loop is really executed at least once:
  985. if result == InitSkippable: result = Unknown
  986. of harmless:
  987. result = Unknown
  988. of nkGotoState, nkBreakState:
  989. # give up for now.
  990. result = InitRequired
  991. of nkSym:
  992. # some path reads from 'result' before it was written to!
  993. if n.sym.kind == skResult: result = InitRequired
  994. of nkTryStmt, nkHiddenTryStmt:
  995. # We need to watch out for the following problem:
  996. # try:
  997. # result = stuffThatRaises()
  998. # except:
  999. # discard "result was not set"
  1000. #
  1001. # So ... even if the assignment to 'result' is the very first
  1002. # assignment this is not good enough! The only pattern we allow for
  1003. # is 'finally: result = x'
  1004. result = InitSkippable
  1005. allPathsInBranch(n[0])
  1006. for i in 1..<n.len:
  1007. if n[i].kind == nkFinally:
  1008. result = allPathsAsgnResult(p, n[i].lastSon)
  1009. else:
  1010. allPathsInBranch(n[i].lastSon)
  1011. of nkCallKinds:
  1012. if canRaiseDisp(p, n[0]):
  1013. result = InitRequired
  1014. else:
  1015. for i in 0..<n.safeLen:
  1016. allPathsInBranch(n[i])
  1017. of nkRaiseStmt:
  1018. result = InitRequired
  1019. of nkChckRangeF, nkChckRange64, nkChckRange:
  1020. # TODO: more checks might need to be covered like overflow, indexDefect etc.
  1021. # bug #22852
  1022. result = InitRequired
  1023. else:
  1024. for i in 0..<n.safeLen:
  1025. allPathsInBranch(n[i])
  1026. proc getProcTypeCast(m: BModule, prc: PSym): Rope =
  1027. result = getTypeDesc(m, prc.loc.t)
  1028. if prc.typ.callConv == ccClosure:
  1029. var rettype, params: Rope = ""
  1030. var check = initIntSet()
  1031. genProcParams(m, prc.typ, rettype, params, check)
  1032. result = "$1(*)$2" % [rettype, params]
  1033. proc genProcBody(p: BProc; procBody: PNode) =
  1034. genStmts(p, procBody) # modifies p.locals, p.init, etc.
  1035. if {nimErrorFlagAccessed, nimErrorFlagDeclared, nimErrorFlagDisabled} * p.flags == {nimErrorFlagAccessed}:
  1036. p.flags.incl nimErrorFlagDeclared
  1037. p.blocks[0].sections[cpsLocals].add(ropecg(p.module, "NIM_BOOL* nimErr_;$n", []))
  1038. p.blocks[0].sections[cpsInit].add(ropecg(p.module, "nimErr_ = #nimErrorFlag();$n", []))
  1039. proc isNoReturn(m: BModule; s: PSym): bool {.inline.} =
  1040. sfNoReturn in s.flags and m.config.exc != excGoto
  1041. proc genProcAux*(m: BModule, prc: PSym) =
  1042. var p = newProc(prc, m)
  1043. var header = newRopeAppender()
  1044. let isCppMember = m.config.backend == backendCpp and sfCppMember * prc.flags != {}
  1045. if isCppMember:
  1046. genMemberProcHeader(m, prc, header)
  1047. else:
  1048. genProcHeader(m, prc, header)
  1049. var returnStmt: Rope = ""
  1050. assert(prc.ast != nil)
  1051. var procBody = transformBody(m.g.graph, m.idgen, prc, {})
  1052. if sfInjectDestructors in prc.flags:
  1053. procBody = injectDestructorCalls(m.g.graph, m.idgen, prc, procBody)
  1054. let tmpInfo = prc.info
  1055. discard freshLineInfo(p, prc.info)
  1056. if sfPure notin prc.flags and prc.typ.returnType != nil:
  1057. if resultPos >= prc.ast.len:
  1058. internalError(m.config, prc.info, "proc has no result symbol")
  1059. let resNode = prc.ast[resultPos]
  1060. let res = resNode.sym # get result symbol
  1061. if not isInvalidReturnType(m.config, prc.typ) and sfConstructor notin prc.flags:
  1062. if sfNoInit in prc.flags: incl(res.flags, sfNoInit)
  1063. if sfNoInit in prc.flags and p.module.compileToCpp and (let val = easyResultAsgn(procBody); val != nil):
  1064. var decl = localVarDecl(p, resNode)
  1065. var a: TLoc = initLocExprSingleUse(p, val)
  1066. linefmt(p, cpsStmts, "$1 = $2;$n", [decl, rdLoc(a)])
  1067. else:
  1068. # declare the result symbol:
  1069. assignLocalVar(p, resNode)
  1070. assert(res.loc.snippet != "")
  1071. if p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc} and
  1072. allPathsAsgnResult(p, procBody) == InitSkippable:
  1073. # In an ideal world the codegen could rely on injectdestructors doing its job properly
  1074. # and then the analysis step would not be required.
  1075. discard "result init optimized out"
  1076. else:
  1077. initLocalVar(p, res, immediateAsgn=false)
  1078. returnStmt = ropecg(p.module, "\treturn $1;$n", [rdLoc(res.loc)])
  1079. elif sfConstructor in prc.flags:
  1080. resNode.sym.loc.flags.incl lfIndirect
  1081. fillLoc(resNode.sym.loc, locParam, resNode, "this", OnHeap)
  1082. prc.loc.snippet = getTypeDesc(m, resNode.sym.loc.t, dkVar)
  1083. else:
  1084. fillResult(p.config, resNode, prc.typ)
  1085. assignParam(p, res, prc.typ.returnType)
  1086. # We simplify 'unsureAsgn(result, nil); unsureAsgn(result, x)'
  1087. # to 'unsureAsgn(result, x)'
  1088. # Sketch why this is correct: If 'result' points to a stack location
  1089. # the 'unsureAsgn' is a nop. If it points to a global variable the
  1090. # global is either 'nil' or points to valid memory and so the RC operation
  1091. # succeeds without touching not-initialized memory.
  1092. if sfNoInit in prc.flags: discard
  1093. elif allPathsAsgnResult(p, procBody) == InitSkippable: discard
  1094. else:
  1095. resetLoc(p, res.loc)
  1096. if skipTypes(res.typ, abstractInst).kind == tyArray:
  1097. #incl(res.loc.flags, lfIndirect)
  1098. res.loc.storage = OnUnknown
  1099. for i in 1..<prc.typ.n.len:
  1100. let param = prc.typ.n[i].sym
  1101. if param.typ.isCompileTimeOnly: continue
  1102. assignParam(p, param, prc.typ.returnType)
  1103. closureSetup(p, prc)
  1104. genProcBody(p, procBody)
  1105. prc.info = tmpInfo
  1106. var generatedProc: Rope = ""
  1107. generatedProc.genCLineDir prc.info, m.config
  1108. if isNoReturn(p.module, prc):
  1109. if hasDeclspec in extccomp.CC[p.config.cCompiler].props and not isCppMember:
  1110. header = "__declspec(noreturn) " & header
  1111. if sfPure in prc.flags:
  1112. if hasDeclspec in extccomp.CC[p.config.cCompiler].props and not isCppMember:
  1113. header = "__declspec(naked) " & header
  1114. generatedProc.add ropecg(p.module, "$1 {$n$2$3$4}$N$N",
  1115. [header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)])
  1116. else:
  1117. if m.hcrOn and isReloadable(m, prc):
  1118. # Add forward declaration for "_actual"-suffixed functions defined in the same module (or inline).
  1119. # This fixes the use of methods and also the case when 2 functions within the same module
  1120. # call each other using directly the "_actual" versions (an optimization) - see issue #11608
  1121. m.s[cfsProcHeaders].addf("$1;\n", [header])
  1122. generatedProc.add ropecg(p.module, "$1 {$n", [header])
  1123. if optStackTrace in prc.options:
  1124. generatedProc.add(p.s(cpsLocals))
  1125. var procname = makeCString(prc.name.s)
  1126. generatedProc.add(initFrame(p, procname, quotedFilename(p.config, prc.info)))
  1127. else:
  1128. generatedProc.add(p.s(cpsLocals))
  1129. if optProfiler in prc.options:
  1130. # invoke at proc entry for recursion:
  1131. appcg(p, cpsInit, "\t#nimProfile();$n", [])
  1132. # this pair of {} is required for C++ (C++ is weird with its
  1133. # control flow integrity checks):
  1134. if beforeRetNeeded in p.flags: generatedProc.add("{")
  1135. generatedProc.add(p.s(cpsInit))
  1136. generatedProc.add(p.s(cpsStmts))
  1137. if beforeRetNeeded in p.flags: generatedProc.add("\t}BeforeRet_: ;\n")
  1138. if optStackTrace in prc.options: generatedProc.add(deinitFrame(p))
  1139. generatedProc.add(returnStmt)
  1140. generatedProc.add("}\n")
  1141. m.s[cfsProcs].add(generatedProc)
  1142. if isReloadable(m, prc):
  1143. m.s[cfsDynLibInit].addf("\t$1 = ($3) hcrRegisterProc($4, \"$1\", (void*)$2);$n",
  1144. [prc.loc.snippet, prc.loc.snippet & "_actual", getProcTypeCast(m, prc), getModuleDllPath(m, prc)])
  1145. proc requiresExternC(m: BModule; sym: PSym): bool {.inline.} =
  1146. result = (sfCompileToCpp in m.module.flags and
  1147. sfCompileToCpp notin sym.getModule().flags and
  1148. m.config.backend != backendCpp) or (
  1149. sym.flags * {sfInfixCall, sfCompilerProc, sfMangleCpp} == {} and
  1150. sym.flags * {sfImportc, sfExportc} != {} and
  1151. sym.magic == mNone and
  1152. m.config.backend == backendCpp)
  1153. proc genProcPrototype(m: BModule, sym: PSym) =
  1154. useHeader(m, sym)
  1155. if lfNoDecl in sym.loc.flags or sfCppMember * sym.flags != {}: return
  1156. if lfDynamicLib in sym.loc.flags:
  1157. if sym.itemId.module != m.module.position and
  1158. not containsOrIncl(m.declaredThings, sym.id):
  1159. m.s[cfsVars].add(ropecg(m, "$1 $2 $3;$n",
  1160. [(if isReloadable(m, sym): "static" else: "extern"),
  1161. getTypeDesc(m, sym.loc.t), mangleDynLibProc(sym)]))
  1162. if isReloadable(m, sym):
  1163. m.s[cfsDynLibInit].addf("\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  1164. [mangleDynLibProc(sym), getTypeDesc(m, sym.loc.t), getModuleDllPath(m, sym)])
  1165. elif not containsOrIncl(m.declaredProtos, sym.id):
  1166. let asPtr = isReloadable(m, sym)
  1167. var header = newRopeAppender()
  1168. genProcHeader(m, sym, header, asPtr)
  1169. if not asPtr:
  1170. if isNoReturn(m, sym) and hasDeclspec in extccomp.CC[m.config.cCompiler].props:
  1171. header = "__declspec(noreturn) " & header
  1172. if sym.typ.callConv != ccInline and requiresExternC(m, sym):
  1173. header = "extern \"C\" " & header
  1174. if sfPure in sym.flags and hasAttribute in CC[m.config.cCompiler].props:
  1175. header.add(" __attribute__((naked))")
  1176. if isNoReturn(m, sym) and hasAttribute in CC[m.config.cCompiler].props:
  1177. header.add(" __attribute__((noreturn))")
  1178. m.s[cfsProcHeaders].add(ropecg(m, "$1;$N", [header]))
  1179. # TODO: figure out how to rename this - it DOES generate a forward declaration
  1180. proc genProcNoForward(m: BModule, prc: PSym) =
  1181. if lfImportCompilerProc in prc.loc.flags:
  1182. fillProcLoc(m, prc.ast[namePos])
  1183. useHeader(m, prc)
  1184. # dependency to a compilerproc:
  1185. cgsym(m, prc.name.s)
  1186. return
  1187. if lfNoDecl in prc.loc.flags:
  1188. fillProcLoc(m, prc.ast[namePos])
  1189. genProcPrototype(m, prc)
  1190. elif lfDynamicLib in prc.loc.flags:
  1191. var q = findPendingModule(m, prc)
  1192. fillProcLoc(q, prc.ast[namePos])
  1193. genProcPrototype(m, prc)
  1194. if q != nil and not containsOrIncl(q.declaredThings, prc.id):
  1195. symInDynamicLib(q, prc)
  1196. # register the procedure even though it is in a different dynamic library and will not be
  1197. # reloadable (and has no _actual suffix) - other modules will need to be able to get it through
  1198. # the hcr dynlib (also put it in the DynLibInit section - right after it gets loaded)
  1199. if isReloadable(q, prc):
  1200. q.s[cfsDynLibInit].addf("\t$1 = ($2) hcrRegisterProc($3, \"$1\", (void*)$1);$n",
  1201. [prc.loc.snippet, getTypeDesc(q, prc.loc.t), getModuleDllPath(m, q.module)])
  1202. else:
  1203. symInDynamicLibPartial(m, prc)
  1204. elif prc.typ.callConv == ccInline:
  1205. # We add inline procs to the calling module to enable C based inlining.
  1206. # This also means that a check with ``q.declaredThings`` is wrong, we need
  1207. # a check for ``m.declaredThings``.
  1208. if not containsOrIncl(m.declaredThings, prc.id):
  1209. #if prc.loc.k == locNone:
  1210. # mangle the inline proc based on the module where it is defined -
  1211. # not on the first module that uses it
  1212. let m2 = if m.config.symbolFiles != disabledSf: m
  1213. else: findPendingModule(m, prc)
  1214. fillProcLoc(m2, prc.ast[namePos])
  1215. #elif {sfExportc, sfImportc} * prc.flags == {}:
  1216. # # reset name to restore consistency in case of hashing collisions:
  1217. # echo "resetting ", prc.id, " by ", m.module.name.s
  1218. # prc.loc.snippet = nil
  1219. # prc.loc.snippet = mangleName(m, prc)
  1220. genProcPrototype(m, prc)
  1221. genProcAux(m, prc)
  1222. elif sfImportc notin prc.flags:
  1223. var q = findPendingModule(m, prc)
  1224. fillProcLoc(q, prc.ast[namePos])
  1225. # generate a getProc call to initialize the pointer for this
  1226. # externally-to-the-current-module defined proc, also important
  1227. # to do the declaredProtos check before the call to genProcPrototype
  1228. if isReloadable(m, prc) and prc.id notin m.declaredProtos and
  1229. q != nil and q.module.id != m.module.id:
  1230. m.s[cfsDynLibInit].addf("\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  1231. [prc.loc.snippet, getProcTypeCast(m, prc), getModuleDllPath(m, prc)])
  1232. genProcPrototype(m, prc)
  1233. if q != nil and not containsOrIncl(q.declaredThings, prc.id):
  1234. # make sure there is a "prototype" in the external module
  1235. # which will actually become a function pointer
  1236. if isReloadable(m, prc):
  1237. genProcPrototype(q, prc)
  1238. genProcAux(q, prc)
  1239. else:
  1240. fillProcLoc(m, prc.ast[namePos])
  1241. useHeader(m, prc)
  1242. if sfInfixCall notin prc.flags: genProcPrototype(m, prc)
  1243. proc requestConstImpl(p: BProc, sym: PSym) =
  1244. if genConstSetup(p, sym):
  1245. let m = p.module
  1246. # declare implementation:
  1247. var q = findPendingModule(m, sym)
  1248. if q != nil and not containsOrIncl(q.declaredThings, sym.id):
  1249. assert q.initProc.module == q
  1250. genConstDefinition(q, p, sym)
  1251. # declare header:
  1252. if q != m and not containsOrIncl(m.declaredThings, sym.id):
  1253. genConstHeader(m, q, p, sym)
  1254. proc isActivated(prc: PSym): bool = prc.typ != nil
  1255. proc genProc(m: BModule, prc: PSym) =
  1256. if sfBorrow in prc.flags or not isActivated(prc): return
  1257. if sfForward in prc.flags:
  1258. addForwardedProc(m, prc)
  1259. fillProcLoc(m, prc.ast[namePos])
  1260. else:
  1261. genProcNoForward(m, prc)
  1262. if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and
  1263. m.g.generatedHeader != nil and lfNoDecl notin prc.loc.flags:
  1264. genProcPrototype(m.g.generatedHeader, prc)
  1265. if prc.typ.callConv == ccInline:
  1266. if not containsOrIncl(m.g.generatedHeader.declaredThings, prc.id):
  1267. genProcAux(m.g.generatedHeader, prc)
  1268. proc genVarPrototype(m: BModule, n: PNode) =
  1269. #assert(sfGlobal in sym.flags)
  1270. let sym = n.sym
  1271. useHeader(m, sym)
  1272. fillBackendName(m, sym)
  1273. fillLoc(sym.loc, locGlobalVar, n, OnHeap)
  1274. if treatGlobalDifferentlyForHCR(m, sym): incl(sym.loc.flags, lfIndirect)
  1275. if (lfNoDecl in sym.loc.flags) or contains(m.declaredThings, sym.id):
  1276. return
  1277. if sym.owner.id != m.module.id:
  1278. # else we already have the symbol generated!
  1279. assert(sym.loc.snippet != "")
  1280. incl(m.declaredThings, sym.id)
  1281. if sfThread in sym.flags:
  1282. declareThreadVar(m, sym, true)
  1283. else:
  1284. if sym.kind in {skLet, skVar, skField, skForVar} and sym.alignment > 0:
  1285. m.s[cfsVars].addf "NIM_ALIGN($1) ", [rope(sym.alignment)]
  1286. m.s[cfsVars].add(if m.hcrOn: "static " else: "extern ")
  1287. m.s[cfsVars].add(getTypeDesc(m, sym.loc.t, dkVar))
  1288. if m.hcrOn: m.s[cfsVars].add("*")
  1289. if lfDynamicLib in sym.loc.flags: m.s[cfsVars].add("*")
  1290. if sfRegister in sym.flags: m.s[cfsVars].add(" register")
  1291. if sfVolatile in sym.flags: m.s[cfsVars].add(" volatile")
  1292. if sfNoalias in sym.flags: m.s[cfsVars].add(" NIM_NOALIAS")
  1293. m.s[cfsVars].addf(" $1;$n", [sym.loc.snippet])
  1294. if m.hcrOn: m.initProc.procSec(cpsLocals).addf(
  1295. "\t$1 = ($2*)hcrGetGlobal($3, \"$1\");$n", [sym.loc.snippet,
  1296. getTypeDesc(m, sym.loc.t, dkVar), getModuleDllPath(m, sym)])
  1297. proc addNimDefines(result: var Rope; conf: ConfigRef) {.inline.} =
  1298. result.addf("#define NIM_INTBITS $1\L", [
  1299. platform.CPU[conf.target.targetCPU].intSize.rope])
  1300. if conf.cppCustomNamespace.len > 0:
  1301. result.add("#define USE_NIM_NAMESPACE ")
  1302. result.add(conf.cppCustomNamespace)
  1303. result.add("\L")
  1304. if conf.isDefined("nimEmulateOverflowChecks"):
  1305. result.add("#define NIM_EmulateOverflowChecks\L")
  1306. proc headerTop(): Rope =
  1307. result = "/* Generated by Nim Compiler v$1 */$N" % [rope(VersionAsString)]
  1308. proc getCopyright(conf: ConfigRef; cfile: Cfile): Rope =
  1309. result = headerTop()
  1310. if optCompileOnly notin conf.globalOptions:
  1311. result.add ("/* Compiled for: $1, $2, $3 */$N" &
  1312. "/* Command for C compiler:$n $4 */$N") %
  1313. [rope(platform.OS[conf.target.targetOS].name),
  1314. rope(platform.CPU[conf.target.targetCPU].name),
  1315. rope(extccomp.CC[conf.cCompiler].name),
  1316. rope(getCompileCFileCmd(conf, cfile))]
  1317. proc getFileHeader(conf: ConfigRef; cfile: Cfile): Rope =
  1318. result = getCopyright(conf, cfile)
  1319. if conf.hcrOn: result.add("#define NIM_HOT_CODE_RELOADING\L")
  1320. addNimDefines(result, conf)
  1321. proc getSomeNameForModule(conf: ConfigRef, filename: AbsoluteFile): Rope =
  1322. ## Returns a mangled module name.
  1323. result = mangleModuleName(conf, filename).mangle
  1324. proc getSomeNameForModule(m: BModule): Rope =
  1325. ## Returns a mangled module name.
  1326. assert m.module.kind == skModule
  1327. assert m.module.owner.kind == skPackage
  1328. result = mangleModuleName(m.g.config, m.filename).mangle
  1329. proc getSomeInitName(m: BModule, suffix: string): Rope =
  1330. if not m.hcrOn:
  1331. result = getSomeNameForModule(m)
  1332. else:
  1333. result = ""
  1334. result.add suffix
  1335. proc getInitName(m: BModule): Rope =
  1336. if sfMainModule in m.module.flags:
  1337. # generate constant name for main module, for "easy" debugging.
  1338. result = rope(m.config.nimMainPrefix) & rope"NimMainModule"
  1339. else:
  1340. result = getSomeInitName(m, "Init000")
  1341. proc getDatInitName(m: BModule): Rope = getSomeInitName(m, "DatInit000")
  1342. proc getHcrInitName(m: BModule): Rope = getSomeInitName(m, "HcrInit000")
  1343. proc hcrGetProcLoadCode(m: BModule, sym, prefix, handle, getProcFunc: string): Rope
  1344. proc genMainProc(m: BModule) =
  1345. ## this function is called in cgenWriteModules after all modules are closed,
  1346. ## it means raising dependency on the symbols is too late as it will not propagate
  1347. ## into other modules, only simple rope manipulations are allowed
  1348. var preMainCode: Rope = ""
  1349. if m.hcrOn:
  1350. proc loadLib(handle: string, name: string): Rope =
  1351. result = ""
  1352. let prc = magicsys.getCompilerProc(m.g.graph, name)
  1353. assert prc != nil
  1354. let n = newStrNode(nkStrLit, prc.annex.path.strVal)
  1355. n.info = prc.annex.path.info
  1356. var strLit = newRopeAppender()
  1357. genStringLiteral(m, n, strLit)
  1358. appcg(m, result, "\tif (!($1 = #nimLoadLibrary($2)))$N" &
  1359. "\t\t#nimLoadLibraryError($2);$N",
  1360. [handle, strLit])
  1361. preMainCode.add(loadLib("hcr_handle", "hcrGetProc"))
  1362. if m.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  1363. preMainCode.add("\t$1PreMain();\L" % [rope m.config.nimMainPrefix])
  1364. else:
  1365. preMainCode.add("\tvoid* rtl_handle;\L")
  1366. preMainCode.add(loadLib("rtl_handle", "nimGC_setStackBottom"))
  1367. preMainCode.add(hcrGetProcLoadCode(m, "nimGC_setStackBottom", "nimrtl_", "rtl_handle", "nimGetProcAddr"))
  1368. preMainCode.add("\tinner = $1PreMain;\L" % [rope m.config.nimMainPrefix])
  1369. preMainCode.add("\tinitStackBottomWith_actual((void *)&inner);\L")
  1370. preMainCode.add("\t(*inner)();\L")
  1371. else:
  1372. preMainCode.add("\t$1PreMain();\L" % [rope m.config.nimMainPrefix])
  1373. var posixCmdLine: Rope = ""
  1374. if optNoMain notin m.config.globalOptions:
  1375. posixCmdLine.add "N_LIB_PRIVATE int cmdCount;\L"
  1376. posixCmdLine.add "N_LIB_PRIVATE char** cmdLine;\L"
  1377. posixCmdLine.add "N_LIB_PRIVATE char** gEnv;\L"
  1378. const
  1379. # The use of a volatile function pointer to call Pre/NimMainInner
  1380. # prevents inlining of the NimMainInner function and dependent
  1381. # functions, which might otherwise merge their stack frames.
  1382. PreMainBody = "$N" &
  1383. "N_LIB_PRIVATE void $3PreMainInner(void) {$N" &
  1384. "$2" &
  1385. "}$N$N" &
  1386. "$4" &
  1387. "N_LIB_PRIVATE void $3PreMain(void) {$N" &
  1388. "##if $5$N" & # 1 for volatile call, 0 for non-volatile
  1389. "\tvoid (*volatile inner)(void);$N" &
  1390. "\tinner = $3PreMainInner;$N" &
  1391. "$1" &
  1392. "\t(*inner)();$N" &
  1393. "##else$N" &
  1394. "$1" &
  1395. "\t$3PreMainInner();$N" &
  1396. "##endif$N" &
  1397. "}$N$N"
  1398. MainProcs =
  1399. "\t$^NimMain();$N"
  1400. MainProcsWithResult =
  1401. MainProcs & ("\treturn $1nim_program_result;$N")
  1402. NimMainInner = "N_LIB_PRIVATE N_CDECL(void, $5NimMainInner)(void) {$N" &
  1403. "$1" &
  1404. "}$N$N"
  1405. NimMainProc =
  1406. "N_CDECL(void, $5NimMain)(void) {$N" &
  1407. "##if $6$N" & # 1 for volatile call, 0 for non-volatile
  1408. "\tvoid (*volatile inner)(void);$N" &
  1409. "$4" &
  1410. "\tinner = $5NimMainInner;$N" &
  1411. "$2" &
  1412. "\t(*inner)();$N" &
  1413. "##else$N" &
  1414. "$4" &
  1415. "$2" &
  1416. "\t$5NimMainInner();$N" &
  1417. "##endif$N" &
  1418. "}$N$N"
  1419. NimMainBody = NimMainInner & NimMainProc
  1420. PosixCMain =
  1421. "int main(int argc, char** args, char** env) {$N" &
  1422. "\tcmdLine = args;$N" &
  1423. "\tcmdCount = argc;$N" &
  1424. "\tgEnv = env;$N" &
  1425. MainProcsWithResult &
  1426. "}$N$N"
  1427. StandaloneCMain =
  1428. "int main(void) {$N" &
  1429. MainProcs &
  1430. "\treturn 0;$N" &
  1431. "}$N$N"
  1432. WinNimMain = NimMainBody
  1433. WinCMain = "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N" &
  1434. " HINSTANCE hPrevInstance, $N" &
  1435. " LPSTR lpCmdLine, int nCmdShow) {$N" &
  1436. MainProcsWithResult & "}$N$N"
  1437. WinNimDllMain = NimMainInner & "N_LIB_EXPORT " & NimMainProc
  1438. WinCDllMain =
  1439. "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N" &
  1440. " LPVOID lpvReserved) {$N" &
  1441. "\tif (fwdreason == DLL_PROCESS_ATTACH) {$N" & MainProcs & "\t}$N" &
  1442. "\treturn 1;$N}$N$N"
  1443. PosixNimDllMain = WinNimDllMain
  1444. PosixCDllMain =
  1445. "N_LIB_PRIVATE void NIM_POSIX_INIT NimMainInit(void) {$N" &
  1446. MainProcs &
  1447. "}$N$N"
  1448. GenodeNimMain =
  1449. "extern Genode::Env *nim_runtime_env;$N" &
  1450. "extern \"C\" void nim_component_construct(Genode::Env*);$N$N" &
  1451. NimMainBody
  1452. ComponentConstruct =
  1453. "void Libc::Component::construct(Libc::Env &env) {$N" &
  1454. "\t// Set Env used during runtime initialization$N" &
  1455. "\tnim_runtime_env = &env;$N" &
  1456. "\tLibc::with_libc([&] () {$N\t" &
  1457. "\t// Initialize runtime and globals$N" &
  1458. MainProcs &
  1459. "\t// Call application construct$N" &
  1460. "\t\tnim_component_construct(&env);$N" &
  1461. "\t});$N" &
  1462. "}$N$N"
  1463. if m.config.target.targetOS == osWindows and
  1464. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1465. m.includeHeader("<windows.h>")
  1466. elif m.config.target.targetOS == osGenode:
  1467. m.includeHeader("<libc/component.h>")
  1468. let initStackBottomCall =
  1469. if m.config.target.targetOS == osStandalone or m.config.selectedGC in {gcNone, gcArc, gcAtomicArc, gcOrc}: "".rope
  1470. else: ropecg(m, "\t#initStackBottomWith((void *)&inner);$N", [])
  1471. inc(m.labels)
  1472. let isVolatile = if m.config.selectedGC notin {gcNone, gcArc, gcAtomicArc, gcOrc}: "1" else: "0"
  1473. appcg(m, m.s[cfsProcs], PreMainBody, [m.g.mainDatInit, m.g.otherModsInit, m.config.nimMainPrefix, posixCmdLine, isVolatile])
  1474. if m.config.target.targetOS == osWindows and
  1475. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1476. if optGenGuiApp in m.config.globalOptions:
  1477. const nimMain = WinNimMain
  1478. appcg(m, m.s[cfsProcs], nimMain,
  1479. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1480. else:
  1481. const nimMain = WinNimDllMain
  1482. appcg(m, m.s[cfsProcs], nimMain,
  1483. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1484. elif m.config.target.targetOS == osGenode:
  1485. const nimMain = GenodeNimMain
  1486. appcg(m, m.s[cfsProcs], nimMain,
  1487. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1488. elif optGenDynLib in m.config.globalOptions:
  1489. const nimMain = PosixNimDllMain
  1490. appcg(m, m.s[cfsProcs], nimMain,
  1491. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1492. else:
  1493. const nimMain = NimMainBody
  1494. appcg(m, m.s[cfsProcs], nimMain,
  1495. [m.g.mainModInit, initStackBottomCall, m.labels, preMainCode, m.config.nimMainPrefix, isVolatile])
  1496. if optNoMain notin m.config.globalOptions:
  1497. if m.config.cppCustomNamespace.len > 0:
  1498. closeNamespaceNim(m.s[cfsProcs])
  1499. m.s[cfsProcs].add "using namespace " & m.config.cppCustomNamespace & ";\L"
  1500. if m.config.target.targetOS == osWindows and
  1501. m.config.globalOptions * {optGenGuiApp, optGenDynLib} != {}:
  1502. if optGenGuiApp in m.config.globalOptions:
  1503. const otherMain = WinCMain
  1504. appcg(m, m.s[cfsProcs], otherMain, [if m.hcrOn: "*" else: "", m.config.nimMainPrefix])
  1505. else:
  1506. const otherMain = WinCDllMain
  1507. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1508. elif m.config.target.targetOS == osGenode:
  1509. const otherMain = ComponentConstruct
  1510. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1511. elif optGenDynLib in m.config.globalOptions:
  1512. const otherMain = PosixCDllMain
  1513. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1514. elif m.config.target.targetOS == osStandalone:
  1515. const otherMain = StandaloneCMain
  1516. appcg(m, m.s[cfsProcs], otherMain, [m.config.nimMainPrefix])
  1517. else:
  1518. const otherMain = PosixCMain
  1519. appcg(m, m.s[cfsProcs], otherMain, [if m.hcrOn: "*" else: "", m.config.nimMainPrefix])
  1520. if m.config.cppCustomNamespace.len > 0:
  1521. openNamespaceNim(m.config.cppCustomNamespace, m.s[cfsProcs])
  1522. proc registerInitProcs*(g: BModuleList; m: PSym; flags: set[ModuleBackendFlag]) =
  1523. ## Called from the IC backend.
  1524. if HasDatInitProc in flags:
  1525. let datInit = getSomeNameForModule(g.config, g.config.toFullPath(m.info.fileIndex).AbsoluteFile) & "DatInit000"
  1526. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [datInit])
  1527. g.mainDatInit.addf("\t$1();$N", [datInit])
  1528. if HasModuleInitProc in flags:
  1529. let init = getSomeNameForModule(g.config, g.config.toFullPath(m.info.fileIndex).AbsoluteFile) & "Init000"
  1530. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [init])
  1531. let initCall = "\t$1();$N" % [init]
  1532. if sfMainModule in m.flags:
  1533. g.mainModInit.add(initCall)
  1534. elif sfSystemModule in m.flags:
  1535. g.mainDatInit.add(initCall) # systemInit must called right after systemDatInit if any
  1536. else:
  1537. g.otherModsInit.add(initCall)
  1538. proc whichInitProcs*(m: BModule): set[ModuleBackendFlag] =
  1539. # called from IC.
  1540. result = {}
  1541. if m.hcrOn or m.preInitProc.s(cpsInit).len > 0 or m.preInitProc.s(cpsStmts).len > 0:
  1542. result.incl HasModuleInitProc
  1543. for i in cfsTypeInit1..cfsDynLibInit:
  1544. if m.s[i].len != 0:
  1545. result.incl HasDatInitProc
  1546. break
  1547. proc registerModuleToMain(g: BModuleList; m: BModule) =
  1548. let
  1549. init = m.getInitName
  1550. datInit = m.getDatInitName
  1551. if m.hcrOn:
  1552. var hcrModuleMeta = "$nN_LIB_PRIVATE const char* hcr_module_list[] = {$n" % []
  1553. let systemModulePath = getModuleDllPath(m, g.modules[g.graph.config.m.systemFileIdx.int].module)
  1554. let mainModulePath = getModuleDllPath(m, m.module)
  1555. if sfMainModule in m.module.flags:
  1556. hcrModuleMeta.addf("\t$1,$n", [systemModulePath])
  1557. g.graph.importDeps.withValue(FileIndex(m.module.position), deps):
  1558. for curr in deps[]:
  1559. hcrModuleMeta.addf("\t$1,$n", [getModuleDllPath(m, g.modules[curr.int].module)])
  1560. hcrModuleMeta.addf("\t\"\"};$n", [])
  1561. hcrModuleMeta.addf("$nN_LIB_EXPORT N_NIMCALL(void**, HcrGetImportedModules)() { return (void**)hcr_module_list; }$n", [])
  1562. hcrModuleMeta.addf("$nN_LIB_EXPORT N_NIMCALL(char*, HcrGetSigHash)() { return \"$1\"; }$n$n",
  1563. [($sigHash(m.module, m.config)).rope])
  1564. if sfMainModule in m.module.flags:
  1565. g.mainModProcs.add(hcrModuleMeta)
  1566. g.mainModProcs.addf("static void* hcr_handle;$N", [])
  1567. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [init])
  1568. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void);$N", [datInit])
  1569. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void*, N_NIMCALL_PTR(void*, getProcAddr)(void*, char*));$N", [m.getHcrInitName])
  1570. g.mainModProcs.addf("N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void);$N", [])
  1571. g.mainModInit.addf("\t$1();$N", [init])
  1572. g.otherModsInit.addf("\thcrInit((void**)hcr_module_list, $1, $2, $3, hcr_handle, nimGetProcAddr);$n",
  1573. [mainModulePath, systemModulePath, datInit])
  1574. g.mainDatInit.addf("\t$1(hcr_handle, nimGetProcAddr);$N", [m.getHcrInitName])
  1575. g.mainDatInit.addf("\thcrAddModule($1);\n", [mainModulePath])
  1576. g.mainDatInit.addf("\tHcrCreateTypeInfos();$N", [])
  1577. # nasty nasty hack to get the command line functionality working with HCR
  1578. # register the 2 variables on behalf of the os module which might not even
  1579. # be loaded (in which case it will get collected but that is not a problem)
  1580. # EDIT: indeed, this hack, in combination with another un-necessary one
  1581. # (`makeCString` was doing line wrap of string litterals) was root cause for
  1582. # bug #16265.
  1583. let osModulePath = ($systemModulePath).replace("stdlib_system", "stdlib_os").rope
  1584. g.mainDatInit.addf("\thcrAddModule($1);\n", [osModulePath])
  1585. g.mainDatInit.add("\tint* cmd_count;\n")
  1586. g.mainDatInit.add("\tchar*** cmd_line;\n")
  1587. g.mainDatInit.addf("\thcrRegisterGlobal($1, \"cmdCount\", sizeof(cmd_count), NULL, (void**)&cmd_count);$N", [osModulePath])
  1588. g.mainDatInit.addf("\thcrRegisterGlobal($1, \"cmdLine\", sizeof(cmd_line), NULL, (void**)&cmd_line);$N", [osModulePath])
  1589. g.mainDatInit.add("\t*cmd_count = cmdCount;\n")
  1590. g.mainDatInit.add("\t*cmd_line = cmdLine;\n")
  1591. else:
  1592. m.s[cfsInitProc].add(hcrModuleMeta)
  1593. return
  1594. if m.s[cfsDatInitProc].len > 0:
  1595. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [datInit])
  1596. g.mainDatInit.addf("\t$1();$N", [datInit])
  1597. # Initialization of TLS and GC should be done in between
  1598. # systemDatInit and systemInit calls if any
  1599. if sfSystemModule in m.module.flags:
  1600. if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone:
  1601. g.mainDatInit.add(ropecg(m, "\t#initThreadVarsEmulation();$N", []))
  1602. if m.config.target.targetOS != osStandalone and m.config.selectedGC notin {gcNone, gcArc, gcAtomicArc, gcOrc}:
  1603. g.mainDatInit.add(ropecg(m, "\t#initStackBottomWith((void *)&inner);$N", []))
  1604. if m.s[cfsInitProc].len > 0:
  1605. g.mainModProcs.addf("N_LIB_PRIVATE N_NIMCALL(void, $1)(void);$N", [init])
  1606. let initCall = "\t$1();$N" % [init]
  1607. if sfMainModule in m.module.flags:
  1608. g.mainModInit.add(initCall)
  1609. elif sfSystemModule in m.module.flags:
  1610. g.mainDatInit.add(initCall) # systemInit must called right after systemDatInit if any
  1611. else:
  1612. g.otherModsInit.add(initCall)
  1613. proc genDatInitCode(m: BModule) =
  1614. ## this function is called in cgenWriteModules after all modules are closed,
  1615. ## it means raising dependency on the symbols is too late as it will not propagate
  1616. ## into other modules, only simple rope manipulations are allowed
  1617. var moduleDatInitRequired = m.hcrOn
  1618. var prc = "$1 N_NIMCALL(void, $2)(void) {$N" %
  1619. [rope(if m.hcrOn: "N_LIB_EXPORT" else: "N_LIB_PRIVATE"), getDatInitName(m)]
  1620. # we don't want to break into such init code - could happen if a line
  1621. # directive from a function written by the user spills after itself
  1622. genCLineDir(prc, InvalidFileIdx, 999999, m.config)
  1623. for i in cfsTypeInit1..cfsDynLibInit:
  1624. if m.s[i].len != 0:
  1625. moduleDatInitRequired = true
  1626. prc.add(m.s[i])
  1627. prc.addf("}$N$N", [])
  1628. if moduleDatInitRequired:
  1629. m.s[cfsDatInitProc].add(prc)
  1630. #rememberFlag(m.g.graph, m.module, HasDatInitProc)
  1631. # Very similar to the contents of symInDynamicLib - basically only the
  1632. # things needed for the hot code reloading runtime procs to be loaded
  1633. proc hcrGetProcLoadCode(m: BModule, sym, prefix, handle, getProcFunc: string): Rope =
  1634. let prc = magicsys.getCompilerProc(m.g.graph, sym)
  1635. assert prc != nil
  1636. fillProcLoc(m, prc.ast[namePos])
  1637. var extname = prefix & sym
  1638. var tmp = mangleDynLibProc(prc)
  1639. prc.loc.snippet = tmp
  1640. prc.typ.sym = nil
  1641. if not containsOrIncl(m.declaredThings, prc.id):
  1642. m.s[cfsVars].addf("static $2 $1;$n", [prc.loc.snippet, getTypeDesc(m, prc.loc.t, dkVar)])
  1643. result = "\t$1 = ($2) $3($4, $5);$n" %
  1644. [tmp, getTypeDesc(m, prc.typ, dkVar), getProcFunc.rope, handle.rope, makeCString(prefix & sym)]
  1645. proc genInitCode(m: BModule) =
  1646. ## this function is called in cgenWriteModules after all modules are closed,
  1647. ## it means raising dependency on the symbols is too late as it will not propagate
  1648. ## into other modules, only simple rope manipulations are allowed
  1649. var moduleInitRequired = m.hcrOn
  1650. let initname = getInitName(m)
  1651. var prc = "$1 N_NIMCALL(void, $2)(void) {$N" %
  1652. [rope(if m.hcrOn: "N_LIB_EXPORT" else: "N_LIB_PRIVATE"), initname]
  1653. # we don't want to break into such init code - could happen if a line
  1654. # directive from a function written by the user spills after itself
  1655. genCLineDir(prc, InvalidFileIdx, 999999, m.config)
  1656. if m.typeNodes > 0:
  1657. if m.hcrOn:
  1658. appcg(m, m.s[cfsTypeInit1], "\t#TNimNode* $1;$N", [m.typeNodesName])
  1659. appcg(m, m.s[cfsTypeInit1], "\thcrRegisterGlobal($3, \"$1_$2\", sizeof(TNimNode) * $2, NULL, (void**)&$1);$N",
  1660. [m.typeNodesName, m.typeNodes, getModuleDllPath(m, m.module)])
  1661. else:
  1662. appcg(m, m.s[cfsTypeInit1], "static #TNimNode $1[$2];$n",
  1663. [m.typeNodesName, m.typeNodes])
  1664. if m.nimTypes > 0:
  1665. appcg(m, m.s[cfsTypeInit1], "static #TNimType $1[$2];$n",
  1666. [m.nimTypesName, m.nimTypes])
  1667. if m.hcrOn:
  1668. prc.addf("\tint* nim_hcr_dummy_ = 0;$n" &
  1669. "\tNIM_BOOL nim_hcr_do_init_ = " &
  1670. "hcrRegisterGlobal($1, \"module_initialized_\", 1, NULL, (void**)&nim_hcr_dummy_);$n",
  1671. [getModuleDllPath(m, m.module)])
  1672. template writeSection(thing: untyped, section: TCProcSection, addHcrGuards = false) =
  1673. if m.thing.s(section).len > 0:
  1674. moduleInitRequired = true
  1675. if addHcrGuards: prc.add("\tif (nim_hcr_do_init_) {\n\n")
  1676. prc.add(m.thing.s(section))
  1677. if addHcrGuards: prc.add("\n\t} // nim_hcr_do_init_\n")
  1678. if m.preInitProc.s(cpsInit).len > 0 or m.preInitProc.s(cpsStmts).len > 0:
  1679. # Give this small function its own scope
  1680. prc.addf("{$N", [])
  1681. # Keep a bogus frame in case the code needs one
  1682. prc.add("\tTFrame FR_; FR_.len = 0;\n")
  1683. writeSection(preInitProc, cpsLocals)
  1684. writeSection(preInitProc, cpsInit, m.hcrOn)
  1685. writeSection(preInitProc, cpsStmts)
  1686. prc.addf("}/* preInitProc end */$N", [])
  1687. when false:
  1688. m.initProc.blocks[0].sections[cpsLocals].add m.preInitProc.s(cpsLocals)
  1689. m.initProc.blocks[0].sections[cpsInit].prepend m.preInitProc.s(cpsInit)
  1690. m.initProc.blocks[0].sections[cpsStmts].prepend m.preInitProc.s(cpsStmts)
  1691. # add new scope for following code, because old vcc compiler need variable
  1692. # be defined at the top of the block
  1693. prc.addf("{$N", [])
  1694. writeSection(initProc, cpsLocals)
  1695. if m.initProc.s(cpsInit).len > 0 or m.initProc.s(cpsStmts).len > 0:
  1696. moduleInitRequired = true
  1697. if optStackTrace in m.initProc.options and frameDeclared notin m.flags:
  1698. # BUT: the generated init code might depend on a current frame, so
  1699. # declare it nevertheless:
  1700. incl m.flags, frameDeclared
  1701. if preventStackTrace notin m.flags:
  1702. var procname = makeCString(m.module.name.s)
  1703. prc.add(initFrame(m.initProc, procname, quotedFilename(m.config, m.module.info)))
  1704. else:
  1705. prc.add("\tTFrame FR_; FR_.len = 0;\n")
  1706. writeSection(initProc, cpsInit, m.hcrOn)
  1707. writeSection(initProc, cpsStmts)
  1708. if beforeRetNeeded in m.initProc.flags:
  1709. prc.add("\tBeforeRet_: ;\n")
  1710. if m.config.exc == excGoto:
  1711. if getCompilerProc(m.g.graph, "nimTestErrorFlag") != nil:
  1712. m.appcg(prc, "\t#nimTestErrorFlag();$n", [])
  1713. if optStackTrace in m.initProc.options and preventStackTrace notin m.flags:
  1714. prc.add(deinitFrame(m.initProc))
  1715. prc.addf("}$N", [])
  1716. prc.addf("}$N$N", [])
  1717. # we cannot simply add the init proc to ``m.s[cfsProcs]`` anymore because
  1718. # that would lead to a *nesting* of merge sections which the merger does
  1719. # not support. So we add it to another special section: ``cfsInitProc``
  1720. if m.hcrOn:
  1721. var procsToLoad = @["hcrRegisterProc", "hcrGetProc", "hcrRegisterGlobal", "hcrGetGlobal"]
  1722. m.s[cfsInitProc].addf("N_LIB_EXPORT N_NIMCALL(void, $1)(void* handle, N_NIMCALL_PTR(void*, getProcAddr)(void*, char*)) {$N", [getHcrInitName(m)])
  1723. if sfMainModule in m.module.flags:
  1724. # additional procs to load
  1725. procsToLoad.add("hcrInit")
  1726. procsToLoad.add("hcrAddModule")
  1727. # load procs
  1728. for curr in procsToLoad:
  1729. m.s[cfsInitProc].add(hcrGetProcLoadCode(m, curr, "", "handle", "getProcAddr"))
  1730. m.s[cfsInitProc].addf("}$N$N", [])
  1731. for i, el in pairs(m.extensionLoaders):
  1732. if el != "":
  1733. let ex = "NIM_EXTERNC N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N" %
  1734. [(i.ord - '0'.ord).rope, el]
  1735. moduleInitRequired = true
  1736. prc.add(ex)
  1737. if moduleInitRequired or sfMainModule in m.module.flags:
  1738. m.s[cfsInitProc].add(prc)
  1739. #rememberFlag(m.g.graph, m.module, HasModuleInitProc)
  1740. genDatInitCode(m)
  1741. if m.hcrOn:
  1742. m.s[cfsInitProc].addf("N_LIB_EXPORT N_NIMCALL(void, HcrCreateTypeInfos)(void) {$N", [])
  1743. m.s[cfsInitProc].add(m.hcrCreateTypeInfosProc)
  1744. m.s[cfsInitProc].addf("}$N$N", [])
  1745. registerModuleToMain(m.g, m)
  1746. proc postprocessCode(conf: ConfigRef, r: var Rope) =
  1747. # find the first directive
  1748. var f = r.find(postprocessDirStart)
  1749. if f == -1:
  1750. return
  1751. var
  1752. nimlnDirLastF = ""
  1753. var res: Rope = r.substr(0, f - 1)
  1754. while f != -1:
  1755. var
  1756. e = r.find(postprocessDirEnd, f + 1)
  1757. dir = r.substr(f + 1, e - 1).split(postprocessDirSep)
  1758. case dir[0]
  1759. of "nimln":
  1760. if dir[2] == nimlnDirLastF:
  1761. res.add("nimln_(" & dir[1] & ");")
  1762. else:
  1763. res.add("nimlf_(" & dir[1] & ", " & quotedFilename(conf, dir[2].parseInt.FileIndex) & ");")
  1764. nimlnDirLastF = dir[2]
  1765. else:
  1766. raiseAssert "unexpected postprocess directive"
  1767. # find the next directive
  1768. f = r.find(postprocessDirStart, e + 1)
  1769. # copy the code until the next directive
  1770. if f != -1:
  1771. res.add(r.substr(e + 1, f - 1))
  1772. else:
  1773. res.add(r.substr(e + 1))
  1774. r = res
  1775. proc genModule(m: BModule, cfile: Cfile): Rope =
  1776. var moduleIsEmpty = true
  1777. result = getFileHeader(m.config, cfile)
  1778. generateThreadLocalStorage(m)
  1779. generateHeaders(m)
  1780. result.add(m.s[cfsHeaders])
  1781. if m.config.cppCustomNamespace.len > 0:
  1782. openNamespaceNim(m.config.cppCustomNamespace, result)
  1783. if m.s[cfsFrameDefines].len > 0:
  1784. result.add(m.s[cfsFrameDefines])
  1785. for i in cfsForwardTypes..cfsProcs:
  1786. if m.s[i].len > 0:
  1787. moduleIsEmpty = false
  1788. result.add(m.s[i])
  1789. if m.s[cfsInitProc].len > 0:
  1790. moduleIsEmpty = false
  1791. result.add(m.s[cfsInitProc])
  1792. if m.s[cfsDatInitProc].len > 0 or m.hcrOn:
  1793. moduleIsEmpty = false
  1794. result.add(m.s[cfsDatInitProc])
  1795. if m.config.cppCustomNamespace.len > 0:
  1796. closeNamespaceNim(result)
  1797. if optLineDir in m.config.options:
  1798. var srcFileDefs = ""
  1799. for fi in 0..m.config.m.fileInfos.high:
  1800. srcFileDefs.add("#define FX_" & $fi & " " & makeSingleLineCString(toFullPath(m.config, fi.FileIndex)) & "\n")
  1801. result = srcFileDefs & result
  1802. if moduleIsEmpty:
  1803. result = ""
  1804. postprocessCode(m.config, result)
  1805. proc initProcOptions(m: BModule): TOptions =
  1806. let opts = m.config.options
  1807. if sfSystemModule in m.module.flags: opts-{optStackTrace} else: opts
  1808. proc rawNewModule(g: BModuleList; module: PSym, filename: AbsoluteFile): BModule =
  1809. new(result)
  1810. result.g = g
  1811. result.tmpBase = rope("TM" & $hashOwner(module) & "_")
  1812. result.headerFiles = @[]
  1813. result.declaredThings = initIntSet()
  1814. result.declaredProtos = initIntSet()
  1815. result.cfilename = filename
  1816. result.filename = filename
  1817. result.typeCache = initTable[SigHash, Rope]()
  1818. result.forwTypeCache = initTable[SigHash, Rope]()
  1819. result.module = module
  1820. result.typeInfoMarker = initTable[SigHash, Rope]()
  1821. result.sigConflicts = initCountTable[SigHash]()
  1822. result.initProc = newProc(nil, result)
  1823. for i in low(result.s)..high(result.s): result.s[i] = newRopeAppender()
  1824. result.initProc.options = initProcOptions(result)
  1825. result.preInitProc = newProc(nil, result)
  1826. result.preInitProc.flags.incl nimErrorFlagDisabled
  1827. result.preInitProc.labels = 100_000 # little hack so that unique temporaries are generated
  1828. result.dataCache = initNodeTable()
  1829. result.typeStack = @[]
  1830. result.typeNodesName = getTempName(result)
  1831. result.nimTypesName = getTempName(result)
  1832. # no line tracing for the init sections of the system module so that we
  1833. # don't generate a TFrame which can confuse the stack bottom initialization:
  1834. if sfSystemModule in module.flags:
  1835. incl result.flags, preventStackTrace
  1836. excl(result.preInitProc.options, optStackTrace)
  1837. let ndiName = if optCDebug in g.config.globalOptions: changeFileExt(completeCfilePath(g.config, filename), "ndi")
  1838. else: AbsoluteFile""
  1839. open(result.ndi, ndiName, g.config)
  1840. proc rawNewModule(g: BModuleList; module: PSym; conf: ConfigRef): BModule =
  1841. result = rawNewModule(g, module, AbsoluteFile toFullPath(conf, module.position.FileIndex))
  1842. proc newModule*(g: BModuleList; module: PSym; conf: ConfigRef): BModule =
  1843. # we should create only one cgen module for each module sym
  1844. result = rawNewModule(g, module, conf)
  1845. if module.position >= g.modules.len:
  1846. setLen(g.modules, module.position + 1)
  1847. #growCache g.modules, module.position
  1848. g.modules[module.position] = result
  1849. template injectG() {.dirty.} =
  1850. if graph.backend == nil:
  1851. graph.backend = newModuleList(graph)
  1852. let g = BModuleList(graph.backend)
  1853. proc setupCgen*(graph: ModuleGraph; module: PSym; idgen: IdGenerator): PPassContext =
  1854. injectG()
  1855. result = newModule(g, module, graph.config)
  1856. result.idgen = idgen
  1857. if optGenIndex in graph.config.globalOptions and g.generatedHeader == nil:
  1858. let f = if graph.config.headerFile.len > 0: AbsoluteFile graph.config.headerFile
  1859. else: graph.config.projectFull
  1860. g.generatedHeader = rawNewModule(g, module,
  1861. changeFileExt(completeCfilePath(graph.config, f), hExt))
  1862. incl g.generatedHeader.flags, isHeaderFile
  1863. proc writeHeader(m: BModule) =
  1864. var result = headerTop()
  1865. var guard = "__$1__" % [m.filename.splitFile.name.rope]
  1866. result.addf("#ifndef $1$n#define $1$n", [guard])
  1867. addNimDefines(result, m.config)
  1868. generateHeaders(m)
  1869. generateThreadLocalStorage(m)
  1870. for i in cfsHeaders..cfsProcs:
  1871. result.add(m.s[i])
  1872. if m.config.cppCustomNamespace.len > 0 and i == cfsHeaders:
  1873. openNamespaceNim(m.config.cppCustomNamespace, result)
  1874. result.add(m.s[cfsInitProc])
  1875. if optGenDynLib in m.config.globalOptions:
  1876. result.add("N_LIB_IMPORT ")
  1877. result.addf("N_CDECL(void, $1NimMain)(void);$n", [rope m.config.nimMainPrefix])
  1878. if m.config.cppCustomNamespace.len > 0: closeNamespaceNim(result)
  1879. result.addf("#endif /* $1 */$n", [guard])
  1880. if not writeRope(result, m.filename):
  1881. rawMessage(m.config, errCannotOpenFile, m.filename.string)
  1882. proc getCFile(m: BModule): AbsoluteFile =
  1883. let ext =
  1884. if m.compileToCpp: ".nim.cpp"
  1885. elif m.config.backend == backendObjc or sfCompileToObjc in m.module.flags: ".nim.m"
  1886. else: ".nim.c"
  1887. result = changeFileExt(completeCfilePath(m.config, mangleModuleName(m.config, m.cfilename).AbsoluteFile), ext)
  1888. when false:
  1889. proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
  1890. injectG()
  1891. var m = newModule(g, module, graph.config)
  1892. readMergeInfo(getCFile(m), m)
  1893. result = m
  1894. proc addHcrInitGuards(p: BProc, n: PNode, inInitGuard: var bool) =
  1895. if n.kind == nkStmtList:
  1896. for child in n:
  1897. addHcrInitGuards(p, child, inInitGuard)
  1898. else:
  1899. let stmtShouldExecute = n.kind in {nkVarSection, nkLetSection} or
  1900. nfExecuteOnReload in n.flags
  1901. if inInitGuard:
  1902. if stmtShouldExecute:
  1903. endBlock(p)
  1904. inInitGuard = false
  1905. else:
  1906. if not stmtShouldExecute:
  1907. line(p, cpsStmts, "if (nim_hcr_do_init_)\n")
  1908. startBlock(p)
  1909. inInitGuard = true
  1910. genStmts(p, n)
  1911. proc genTopLevelStmt*(m: BModule; n: PNode) =
  1912. ## Also called from `ic/cbackend.nim`.
  1913. if pipelineutils.skipCodegen(m.config, n): return
  1914. m.initProc.options = initProcOptions(m)
  1915. #softRnl = if optLineDir in m.config.options: noRnl else: rnl
  1916. # XXX replicate this logic!
  1917. var transformedN = transformStmt(m.g.graph, m.idgen, m.module, n)
  1918. if sfInjectDestructors in m.module.flags:
  1919. transformedN = injectDestructorCalls(m.g.graph, m.idgen, m.module, transformedN)
  1920. if m.hcrOn:
  1921. addHcrInitGuards(m.initProc, transformedN, m.inHcrInitGuard)
  1922. else:
  1923. genProcBody(m.initProc, transformedN)
  1924. proc shouldRecompile(m: BModule; code: Rope, cfile: Cfile): bool =
  1925. if optForceFullMake notin m.config.globalOptions:
  1926. if not moduleHasChanged(m.g.graph, m.module):
  1927. result = false
  1928. elif not equalsFile(code, cfile.cname):
  1929. when false:
  1930. #m.config.symbolFiles == readOnlySf: #isDefined(m.config, "nimdiff"):
  1931. if fileExists(cfile.cname):
  1932. copyFile(cfile.cname.string, cfile.cname.string & ".backup")
  1933. echo "diff ", cfile.cname.string, ".backup ", cfile.cname.string
  1934. else:
  1935. echo "new file ", cfile.cname.string
  1936. if not writeRope(code, cfile.cname):
  1937. rawMessage(m.config, errCannotOpenFile, cfile.cname.string)
  1938. result = true
  1939. elif fileExists(cfile.obj) and os.fileNewer(cfile.obj.string, cfile.cname.string):
  1940. result = false
  1941. else:
  1942. result = true
  1943. else:
  1944. if not writeRope(code, cfile.cname):
  1945. rawMessage(m.config, errCannotOpenFile, cfile.cname.string)
  1946. result = true
  1947. # We need 2 different logics here: pending modules (including
  1948. # 'nim__dat') may require file merging for the combination of dead code
  1949. # elimination and incremental compilation! Non pending modules need no
  1950. # such logic and in fact the logic hurts for the main module at least;
  1951. # it would generate multiple 'main' procs, for instance.
  1952. proc writeModule(m: BModule, pending: bool) =
  1953. template onExit() = close(m.ndi, m.config)
  1954. let cfile = getCFile(m)
  1955. if moduleHasChanged(m.g.graph, m.module):
  1956. genInitCode(m)
  1957. finishTypeDescriptions(m)
  1958. if sfMainModule in m.module.flags:
  1959. # generate main file:
  1960. genMainProc(m)
  1961. m.s[cfsProcHeaders].add(m.g.mainModProcs)
  1962. generateThreadVarsSize(m)
  1963. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1964. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1965. var code = genModule(m, cf)
  1966. if code != "" or m.config.symbolFiles != disabledSf:
  1967. when hasTinyCBackend:
  1968. if m.config.cmd == cmdTcc:
  1969. tccgen.compileCCode($code, m.config)
  1970. onExit()
  1971. return
  1972. if not shouldRecompile(m, code, cf): cf.flags = {CfileFlag.Cached}
  1973. addFileToCompile(m.config, cf)
  1974. onExit()
  1975. proc updateCachedModule(m: BModule) =
  1976. let cfile = getCFile(m)
  1977. var cf = Cfile(nimname: m.module.name.s, cname: cfile,
  1978. obj: completeCfilePath(m.config, toObjFile(m.config, cfile)), flags: {})
  1979. if sfMainModule notin m.module.flags:
  1980. genMainProc(m)
  1981. cf.flags = {CfileFlag.Cached}
  1982. addFileToCompile(m.config, cf)
  1983. proc generateLibraryDestroyGlobals(graph: ModuleGraph; m: BModule; body: PNode; isDynlib: bool): PSym =
  1984. let procname = getIdent(graph.cache, "NimDestroyGlobals")
  1985. result = newSym(skProc, procname, m.idgen, m.module.owner, m.module.info)
  1986. result.typ = newProcType(m.module.info, m.idgen, m.module.owner)
  1987. result.typ.callConv = ccCDecl
  1988. incl result.flags, sfExportc
  1989. result.loc.snippet = "NimDestroyGlobals"
  1990. if isDynlib:
  1991. incl(result.loc.flags, lfExportLib)
  1992. let theProc = newNodeI(nkProcDef, m.module.info, bodyPos+1)
  1993. for i in 0..<theProc.len: theProc[i] = newNodeI(nkEmpty, m.module.info)
  1994. theProc[namePos] = newSymNode(result)
  1995. theProc[bodyPos] = body
  1996. result.ast = theProc
  1997. proc finalCodegenActions*(graph: ModuleGraph; m: BModule; n: PNode) =
  1998. ## Also called from IC.
  1999. if sfMainModule in m.module.flags:
  2000. # phase ordering problem here: We need to announce this
  2001. # dependency to 'nimTestErrorFlag' before system.c has been written to disk.
  2002. if m.config.exc == excGoto and getCompilerProc(graph, "nimTestErrorFlag") != nil:
  2003. cgsym(m, "nimTestErrorFlag")
  2004. if {optGenStaticLib, optGenDynLib, optNoMain} * m.config.globalOptions == {}:
  2005. for i in countdown(high(graph.globalDestructors), 0):
  2006. n.add graph.globalDestructors[i]
  2007. else:
  2008. var body = newNodeI(nkStmtList, m.module.info)
  2009. for i in countdown(high(graph.globalDestructors), 0):
  2010. body.add graph.globalDestructors[i]
  2011. body.flags.incl nfTransf # should not be further transformed
  2012. let dtor = generateLibraryDestroyGlobals(graph, m, body, optGenDynLib in m.config.globalOptions)
  2013. genProcAux(m, dtor)
  2014. if pipelineutils.skipCodegen(m.config, n): return
  2015. if moduleHasChanged(graph, m.module):
  2016. # if the module is cached, we don't regenerate the main proc
  2017. # nor the dispatchers? But if the dispatchers changed?
  2018. # XXX emit the dispatchers into its own .c file?
  2019. if n != nil:
  2020. m.initProc.options = initProcOptions(m)
  2021. genProcBody(m.initProc, n)
  2022. if m.hcrOn:
  2023. # make sure this is pulled in (meaning hcrGetGlobal() is called for it during init)
  2024. let sym = magicsys.getCompilerProc(m.g.graph, "programResult")
  2025. # ignore when not available, could be a module imported early in `system`
  2026. if sym != nil:
  2027. cgsymImpl m, sym
  2028. if m.inHcrInitGuard:
  2029. endBlock(m.initProc)
  2030. if sfMainModule in m.module.flags:
  2031. if m.hcrOn:
  2032. # pull ("define" since they are inline when HCR is on) these functions in the main file
  2033. # so it can load the HCR runtime and later pass the library handle to the HCR runtime which
  2034. # will in turn pass it to the other modules it initializes so they can initialize the
  2035. # register/get procs so they don't have to have the definitions of these functions as well
  2036. cgsym(m, "nimLoadLibrary")
  2037. cgsym(m, "nimLoadLibraryError")
  2038. cgsym(m, "nimGetProcAddr")
  2039. cgsym(m, "procAddrError")
  2040. cgsym(m, "rawWrite")
  2041. # raise dependencies on behalf of genMainProc
  2042. if m.config.target.targetOS != osStandalone and m.config.selectedGC notin {gcNone, gcArc, gcAtomicArc, gcOrc}:
  2043. cgsym(m, "initStackBottomWith")
  2044. if emulatedThreadVars(m.config) and m.config.target.targetOS != osStandalone:
  2045. cgsym(m, "initThreadVarsEmulation")
  2046. if m.g.forwardedProcs.len == 0:
  2047. incl m.flags, objHasKidsValid
  2048. if optMultiMethods in m.g.config.globalOptions or
  2049. m.g.config.selectedGC notin {gcArc, gcOrc, gcAtomicArc} or
  2050. vtables notin m.g.config.features:
  2051. generateIfMethodDispatchers(graph, m.idgen)
  2052. let mm = m
  2053. m.g.modulesClosed.add mm
  2054. proc genForwardedProcs(g: BModuleList) =
  2055. # Forward declared proc:s lack bodies when first encountered, so they're given
  2056. # a second pass here
  2057. # Note: ``genProcNoForward`` may add to ``forwardedProcs``
  2058. while g.forwardedProcs.len > 0:
  2059. let
  2060. prc = g.forwardedProcs.pop()
  2061. m = g.modules[prc.itemId.module]
  2062. if sfForward in prc.flags:
  2063. internalError(m.config, prc.info, "still forwarded: " & prc.name.s)
  2064. genProcNoForward(m, prc)
  2065. proc cgenWriteModules*(backend: RootRef, config: ConfigRef) =
  2066. let g = BModuleList(backend)
  2067. g.config = config
  2068. # we need to process the transitive closure because recursive module
  2069. # deps are allowed (and the system module is processed in the wrong
  2070. # order anyway)
  2071. genForwardedProcs(g)
  2072. for m in cgenModules(g):
  2073. m.writeModule(pending=true)
  2074. writeMapping(config, g.mapping)
  2075. if g.generatedHeader != nil: writeHeader(g.generatedHeader)