cgen.nim 89 KB

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