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