cgen.nim 80 KB

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