cgen.nim 77 KB

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