cgen.nim 81 KB

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