cgen.nim 76 KB

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