cgen.nim 90 KB

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