cgen.nim 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466
  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, securehash, bitsets, idents, types,
  13. ccgutils, os, ropes, math, passes, rodread, wordrecg, treetab, cgmeth,
  14. condsyms, rodutils, renderer, idgen, cgendata, ccgmerge, semfold, aliases,
  15. lowerings, semparallel, tables, sets, ndi
  16. import strutils except `%` # collides with ropes.`%`
  17. from modulegraphs import ModuleGraph
  18. import dynlib
  19. when not declared(dynlib.libCandidates):
  20. proc libCandidates(s: string, dest: var seq[string]) =
  21. ## given a library name pattern `s` write possible library names to `dest`.
  22. var le = strutils.find(s, '(')
  23. var ri = strutils.find(s, ')', le+1)
  24. if le >= 0 and ri > le:
  25. var prefix = substr(s, 0, le - 1)
  26. var suffix = substr(s, ri + 1)
  27. for middle in split(substr(s, le + 1, ri - 1), '|'):
  28. libCandidates(prefix & middle & suffix, dest)
  29. else:
  30. add(dest, s)
  31. when options.hasTinyCBackend:
  32. import tccgen
  33. # implementation
  34. proc addForwardedProc(m: BModule, prc: PSym) =
  35. m.forwardedProcs.add(prc)
  36. inc(m.g.forwardedProcsCounter)
  37. proc findPendingModule(m: BModule, s: PSym): BModule =
  38. var ms = getModule(s)
  39. result = m.g.modules[ms.position]
  40. proc initLoc(result: var TLoc, k: TLocKind, lode: PNode, s: TStorageLoc) =
  41. result.k = k
  42. result.storage = s
  43. result.lode = lode
  44. result.r = nil
  45. result.flags = {}
  46. proc fillLoc(a: var TLoc, k: TLocKind, lode: PNode, r: Rope, s: TStorageLoc) =
  47. # fills the loc if it is not already initialized
  48. if a.k == locNone:
  49. a.k = k
  50. a.lode = lode
  51. a.storage = s
  52. if a.r == nil: a.r = r
  53. proc t(a: TLoc): PType {.inline.} =
  54. if a.lode.kind == nkSym:
  55. result = a.lode.sym.typ
  56. else:
  57. result = a.lode.typ
  58. proc lodeTyp(t: PType): PNode =
  59. result = newNode(nkEmpty)
  60. result.typ = t
  61. proc isSimpleConst(typ: PType): bool =
  62. let t = skipTypes(typ, abstractVar)
  63. result = t.kind notin
  64. {tyTuple, tyObject, tyArray, tySet, tySequence} and not
  65. (t.kind == tyProc and t.callConv == ccClosure)
  66. proc useStringh(m: BModule) =
  67. if includesStringh notin m.flags:
  68. incl m.flags, includesStringh
  69. m.includeHeader("<string.h>")
  70. proc useHeader(m: BModule, sym: PSym) =
  71. if lfHeader in sym.loc.flags:
  72. assert(sym.annex != nil)
  73. let str = getStr(sym.annex.path)
  74. m.includeHeader(str)
  75. proc cgsym(m: BModule, name: string): Rope
  76. proc ropecg(m: BModule, frmt: FormatStr, args: varargs[Rope]): Rope =
  77. var i = 0
  78. var length = len(frmt)
  79. result = nil
  80. var num = 0
  81. while i < length:
  82. if frmt[i] == '$':
  83. inc(i) # skip '$'
  84. case frmt[i]
  85. of '$':
  86. add(result, "$")
  87. inc(i)
  88. of '#':
  89. inc(i)
  90. add(result, args[num])
  91. inc(num)
  92. of '0'..'9':
  93. var j = 0
  94. while true:
  95. j = (j * 10) + ord(frmt[i]) - ord('0')
  96. inc(i)
  97. if i >= length or not (frmt[i] in {'0'..'9'}): break
  98. num = j
  99. if j > high(args) + 1:
  100. internalError("ropes: invalid format string $" & $j)
  101. add(result, args[j-1])
  102. of 'n':
  103. if optLineDir notin gOptions: add(result, rnl)
  104. inc(i)
  105. of 'N':
  106. add(result, rnl)
  107. inc(i)
  108. else: internalError("ropes: invalid format string $" & frmt[i])
  109. elif frmt[i] == '#' and frmt[i+1] in IdentStartChars:
  110. inc(i)
  111. var j = i
  112. while frmt[j] in IdentChars: inc(j)
  113. var ident = substr(frmt, i, j-1)
  114. i = j
  115. add(result, cgsym(m, ident))
  116. elif frmt[i] == '#' and frmt[i+1] == '$':
  117. inc(i, 2)
  118. var j = 0
  119. while frmt[i] in Digits:
  120. j = (j * 10) + ord(frmt[i]) - ord('0')
  121. inc(i)
  122. add(result, cgsym(m, $args[j-1]))
  123. var start = i
  124. while i < length:
  125. if frmt[i] != '$' and frmt[i] != '#': inc(i)
  126. else: break
  127. if i - 1 >= start:
  128. add(result, substr(frmt, start, i - 1))
  129. template rfmt(m: BModule, fmt: string, args: varargs[Rope]): untyped =
  130. ropecg(m, fmt, args)
  131. var indent = "\t".rope
  132. proc indentLine(p: BProc, r: Rope): Rope =
  133. result = r
  134. for i in countup(0, p.blocks.len-1):
  135. prepend(result, indent)
  136. proc appcg(m: BModule, c: var Rope, frmt: FormatStr,
  137. args: varargs[Rope]) =
  138. add(c, ropecg(m, frmt, args))
  139. proc appcg(m: BModule, s: TCFileSection, frmt: FormatStr,
  140. args: varargs[Rope]) =
  141. add(m.s[s], ropecg(m, frmt, args))
  142. proc appcg(p: BProc, s: TCProcSection, frmt: FormatStr,
  143. args: varargs[Rope]) =
  144. add(p.s(s), ropecg(p.module, frmt, args))
  145. proc line(p: BProc, s: TCProcSection, r: Rope) =
  146. add(p.s(s), indentLine(p, r))
  147. proc line(p: BProc, s: TCProcSection, r: string) =
  148. add(p.s(s), indentLine(p, r.rope))
  149. proc lineF(p: BProc, s: TCProcSection, frmt: FormatStr,
  150. args: openarray[Rope]) =
  151. add(p.s(s), indentLine(p, frmt % args))
  152. proc lineCg(p: BProc, s: TCProcSection, frmt: FormatStr,
  153. args: varargs[Rope]) =
  154. add(p.s(s), indentLine(p, ropecg(p.module, frmt, args)))
  155. proc linefmt(p: BProc, s: TCProcSection, frmt: FormatStr,
  156. args: varargs[Rope]) =
  157. add(p.s(s), indentLine(p, ropecg(p.module, frmt, args)))
  158. proc safeLineNm(info: TLineInfo): int =
  159. result = toLinenumber(info)
  160. if result < 0: result = 0 # negative numbers are not allowed in #line
  161. proc genCLineDir(r: var Rope, filename: string, line: int) =
  162. assert line >= 0
  163. if optLineDir in gOptions:
  164. addf(r, "$N#line $2 $1$N",
  165. [rope(makeSingleLineCString(filename)), rope(line)])
  166. proc genCLineDir(r: var Rope, info: TLineInfo) =
  167. genCLineDir(r, info.toFullPath, info.safeLineNm)
  168. proc freshLineInfo(p: BProc; info: TLineInfo): bool =
  169. if p.lastLineInfo.line != info.line or
  170. p.lastLineInfo.fileIndex != info.fileIndex:
  171. p.lastLineInfo.line = info.line
  172. p.lastLineInfo.fileIndex = info.fileIndex
  173. result = true
  174. proc genLineDir(p: BProc, t: PNode) =
  175. var tt = t
  176. #while tt.kind in {nkStmtListExpr}+nkCallKinds:
  177. # tt = tt.lastSon
  178. if tt.kind in nkCallKinds and tt.len > 1:
  179. tt = tt.sons[1]
  180. let line = tt.info.safeLineNm
  181. if optEmbedOrigSrc in gGlobalOptions:
  182. add(p.s(cpsStmts), ~"//" & tt.info.sourceLine & rnl)
  183. genCLineDir(p.s(cpsStmts), tt.info.toFullPath, line)
  184. if ({optStackTrace, optEndb} * p.options == {optStackTrace, optEndb}) and
  185. (p.prc == nil or sfPure notin p.prc.flags):
  186. if freshLineInfo(p, tt.info):
  187. linefmt(p, cpsStmts, "#endb($1, $2);$N",
  188. line.rope, makeCString(toFilename(tt.info)))
  189. elif ({optLineTrace, optStackTrace} * p.options ==
  190. {optLineTrace, optStackTrace}) and
  191. (p.prc == nil or sfPure notin p.prc.flags) and tt.info.fileIndex >= 0:
  192. if freshLineInfo(p, tt.info):
  193. linefmt(p, cpsStmts, "nimln_($1, $2);$n",
  194. line.rope, tt.info.quotedFilename)
  195. proc postStmtActions(p: BProc) {.inline.} =
  196. add(p.s(cpsStmts), p.module.injectStmt)
  197. proc accessThreadLocalVar(p: BProc, s: PSym)
  198. proc emulatedThreadVars(): bool {.inline.}
  199. proc genProc(m: BModule, prc: PSym)
  200. template compileToCpp(m: BModule): untyped =
  201. gCmd == cmdCompileToCpp or sfCompileToCpp in m.module.flags
  202. include "ccgtypes.nim"
  203. # ------------------------------ Manager of temporaries ------------------
  204. proc rdLoc(a: TLoc): Rope =
  205. # 'read' location (deref if indirect)
  206. result = a.r
  207. if lfIndirect in a.flags: result = "(*$1)" % [result]
  208. proc addrLoc(a: TLoc): Rope =
  209. result = a.r
  210. if lfIndirect notin a.flags and mapType(a.t) != ctArray:
  211. result = "(&" & result & ")"
  212. proc rdCharLoc(a: TLoc): Rope =
  213. # read a location that may need a char-cast:
  214. result = rdLoc(a)
  215. if skipTypes(a.t, abstractRange).kind == tyChar:
  216. result = "((NU8)($1))" % [result]
  217. proc genObjectInit(p: BProc, section: TCProcSection, t: PType, a: TLoc,
  218. takeAddr: bool) =
  219. case analyseObjectWithTypeField(t)
  220. of frNone:
  221. discard
  222. of frHeader:
  223. var r = rdLoc(a)
  224. if not takeAddr: r = "(*$1)" % [r]
  225. var s = skipTypes(t, abstractInst)
  226. if not p.module.compileToCpp:
  227. while (s.kind == tyObject) and (s.sons[0] != nil):
  228. add(r, ".Sup")
  229. s = skipTypes(s.sons[0], skipPtrs)
  230. linefmt(p, section, "$1.m_type = $2;$n", r, genTypeInfo(p.module, t))
  231. of frEmbedded:
  232. # worst case for performance:
  233. var r = if takeAddr: addrLoc(a) else: rdLoc(a)
  234. linefmt(p, section, "#objectInit($1, $2);$n", r, genTypeInfo(p.module, t))
  235. type
  236. TAssignmentFlag = enum
  237. needToCopy, afDestIsNil, afDestIsNotNil, afSrcIsNil, afSrcIsNotNil
  238. TAssignmentFlags = set[TAssignmentFlag]
  239. proc genRefAssign(p: BProc, dest, src: TLoc, flags: TAssignmentFlags)
  240. proc isComplexValueType(t: PType): bool {.inline.} =
  241. let t = t.skipTypes(abstractInst)
  242. result = t.kind in {tyArray, tySet, tyTuple, tyObject} or
  243. (t.kind == tyProc and t.callConv == ccClosure)
  244. proc resetLoc(p: BProc, loc: var TLoc) =
  245. let containsGcRef = containsGarbageCollectedRef(loc.t)
  246. let typ = skipTypes(loc.t, abstractVarRange)
  247. if isImportedCppType(typ): return
  248. if not isComplexValueType(typ):
  249. if containsGcRef:
  250. var nilLoc: TLoc
  251. initLoc(nilLoc, locTemp, loc.lode, OnStack)
  252. nilLoc.r = rope("NIM_NIL")
  253. genRefAssign(p, loc, nilLoc, {afSrcIsNil})
  254. else:
  255. linefmt(p, cpsStmts, "$1 = 0;$n", rdLoc(loc))
  256. else:
  257. if optNilCheck in p.options:
  258. linefmt(p, cpsStmts, "#chckNil((void*)$1);$n", addrLoc(loc))
  259. if loc.storage != OnStack:
  260. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  261. addrLoc(loc), genTypeInfo(p.module, loc.t))
  262. # XXX: generated reset procs should not touch the m_type
  263. # field, so disabling this should be safe:
  264. genObjectInit(p, cpsStmts, loc.t, loc, true)
  265. else:
  266. useStringh(p.module)
  267. linefmt(p, cpsStmts, "memset((void*)$1, 0, sizeof($2));$n",
  268. addrLoc(loc), rdLoc(loc))
  269. # XXX: We can be extra clever here and call memset only
  270. # on the bytes following the m_type field?
  271. genObjectInit(p, cpsStmts, loc.t, loc, true)
  272. proc constructLoc(p: BProc, loc: TLoc, isTemp = false) =
  273. let typ = loc.t
  274. if not isComplexValueType(typ):
  275. linefmt(p, cpsStmts, "$1 = ($2)0;$n", rdLoc(loc),
  276. getTypeDesc(p.module, typ))
  277. else:
  278. if not isTemp or containsGarbageCollectedRef(loc.t):
  279. # don't use memset for temporary values for performance if we can
  280. # avoid it:
  281. if not isImportedCppType(typ):
  282. useStringh(p.module)
  283. linefmt(p, cpsStmts, "memset((void*)$1, 0, sizeof($2));$n",
  284. addrLoc(loc), rdLoc(loc))
  285. genObjectInit(p, cpsStmts, loc.t, loc, true)
  286. proc initLocalVar(p: BProc, v: PSym, immediateAsgn: bool) =
  287. if sfNoInit notin v.flags:
  288. # we know it is a local variable and thus on the stack!
  289. # If ``not immediateAsgn`` it is not initialized in a binding like
  290. # ``var v = X`` and thus we need to init it.
  291. # If ``v`` contains a GC-ref we may pass it to ``unsureAsgnRef`` somehow
  292. # which requires initialization. However this can really only happen if
  293. # ``var v = X()`` gets transformed into ``X(&v)``.
  294. # Nowadays the logic in ccgcalls deals with this case however.
  295. if not immediateAsgn:
  296. constructLoc(p, v.loc)
  297. proc getTemp(p: BProc, t: PType, result: var TLoc; needsInit=false) =
  298. inc(p.labels)
  299. result.r = "T" & rope(p.labels) & "_"
  300. linefmt(p, cpsLocals, "$1 $2;$n", getTypeDesc(p.module, t), result.r)
  301. result.k = locTemp
  302. result.lode = lodeTyp t
  303. result.storage = OnStack
  304. result.flags = {}
  305. constructLoc(p, result, not needsInit)
  306. proc getIntTemp(p: BProc, result: var TLoc) =
  307. inc(p.labels)
  308. result.r = "T" & rope(p.labels) & "_"
  309. linefmt(p, cpsLocals, "NI $1;$n", result.r)
  310. result.k = locTemp
  311. result.storage = OnStack
  312. result.lode = lodeTyp getSysType(tyInt)
  313. result.flags = {}
  314. proc initGCFrame(p: BProc): Rope =
  315. if p.gcFrameId > 0: result = "struct {$1} GCFRAME_;$n" % [p.gcFrameType]
  316. proc deinitGCFrame(p: BProc): Rope =
  317. if p.gcFrameId > 0:
  318. result = ropecg(p.module,
  319. "if (((NU)&GCFRAME_) < 4096) #nimGCFrame(&GCFRAME_);$n")
  320. proc localDebugInfo(p: BProc, s: PSym) =
  321. if {optStackTrace, optEndb} * p.options != {optStackTrace, optEndb}: return
  322. # XXX work around a bug: No type information for open arrays possible:
  323. if skipTypes(s.typ, abstractVar).kind in {tyOpenArray, tyVarargs}: return
  324. var a = "&" & s.loc.r
  325. if s.kind == skParam and ccgIntroducedPtr(s): a = s.loc.r
  326. lineF(p, cpsInit,
  327. "FR_.s[$1].address = (void*)$3; FR_.s[$1].typ = $4; FR_.s[$1].name = $2;$n",
  328. [p.maxFrameLen.rope, makeCString(normalize(s.name.s)), a,
  329. genTypeInfo(p.module, s.loc.t)])
  330. inc(p.maxFrameLen)
  331. inc p.blocks[p.blocks.len-1].frameLen
  332. proc localVarDecl(p: BProc; n: PNode): Rope =
  333. let s = n.sym
  334. if s.loc.k == locNone:
  335. fillLoc(s.loc, locLocalVar, n, mangleLocalName(p, s), OnStack)
  336. if s.kind == skLet: incl(s.loc.flags, lfNoDeepCopy)
  337. result = getTypeDesc(p.module, s.typ)
  338. if s.constraint.isNil:
  339. if sfRegister in s.flags: add(result, " register")
  340. #elif skipTypes(s.typ, abstractInst).kind in GcTypeKinds:
  341. # add(decl, " GC_GUARD")
  342. if sfVolatile in s.flags: add(result, " volatile")
  343. add(result, " ")
  344. add(result, s.loc.r)
  345. else:
  346. result = s.cgDeclFrmt % [result, s.loc.r]
  347. proc assignLocalVar(p: BProc, n: PNode) =
  348. #assert(s.loc.k == locNone) # not yet assigned
  349. # this need not be fulfilled for inline procs; they are regenerated
  350. # for each module that uses them!
  351. let nl = if optLineDir in gOptions: "" else: tnl
  352. let decl = localVarDecl(p, n) & ";" & nl
  353. line(p, cpsLocals, decl)
  354. localDebugInfo(p, n.sym)
  355. include ccgthreadvars
  356. proc varInDynamicLib(m: BModule, sym: PSym)
  357. proc mangleDynLibProc(sym: PSym): Rope
  358. proc assignGlobalVar(p: BProc, n: PNode) =
  359. let s = n.sym
  360. if s.loc.k == locNone:
  361. fillLoc(s.loc, locGlobalVar, n, mangleName(p.module, s), OnHeap)
  362. if lfDynamicLib in s.loc.flags:
  363. var q = findPendingModule(p.module, s)
  364. if q != nil and not containsOrIncl(q.declaredThings, s.id):
  365. varInDynamicLib(q, s)
  366. else:
  367. s.loc.r = mangleDynLibProc(s)
  368. return
  369. useHeader(p.module, s)
  370. if lfNoDecl in s.loc.flags: return
  371. if sfThread in s.flags:
  372. declareThreadVar(p.module, s, sfImportc in s.flags)
  373. else:
  374. var decl: Rope = nil
  375. var td = getTypeDesc(p.module, s.loc.t)
  376. if s.constraint.isNil:
  377. if sfImportc in s.flags: add(decl, "extern ")
  378. add(decl, td)
  379. if sfRegister in s.flags: add(decl, " register")
  380. if sfVolatile in s.flags: add(decl, " volatile")
  381. addf(decl, " $1;$n", [s.loc.r])
  382. else:
  383. decl = (s.cgDeclFrmt & ";$n") % [td, s.loc.r]
  384. add(p.module.s[cfsVars], decl)
  385. if p.withinLoop > 0:
  386. # fixes tests/run/tzeroarray:
  387. resetLoc(p, s.loc)
  388. if p.module.module.options * {optStackTrace, optEndb} ==
  389. {optStackTrace, optEndb}:
  390. appcg(p.module, p.module.s[cfsDebugInit],
  391. "#dbgRegisterGlobal($1, &$2, $3);$n",
  392. [makeCString(normalize(s.owner.name.s & '.' & s.name.s)),
  393. s.loc.r, genTypeInfo(p.module, s.typ)])
  394. proc assignParam(p: BProc, s: PSym) =
  395. assert(s.loc.r != nil)
  396. scopeMangledParam(p, s)
  397. localDebugInfo(p, s)
  398. proc fillProcLoc(m: BModule; n: PNode) =
  399. let sym = n.sym
  400. if sym.loc.k == locNone:
  401. fillLoc(sym.loc, locProc, n, mangleName(m, sym), OnStack)
  402. proc getLabel(p: BProc): TLabel =
  403. inc(p.labels)
  404. result = "LA" & rope(p.labels) & "_"
  405. proc fixLabel(p: BProc, labl: TLabel) =
  406. lineF(p, cpsStmts, "$1: ;$n", [labl])
  407. proc genVarPrototype(m: BModule, n: PNode)
  408. proc requestConstImpl(p: BProc, sym: PSym)
  409. proc genStmts(p: BProc, t: PNode)
  410. proc expr(p: BProc, n: PNode, d: var TLoc)
  411. proc genProcPrototype(m: BModule, sym: PSym)
  412. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc)
  413. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags)
  414. proc intLiteral(i: BiggestInt): Rope
  415. proc genLiteral(p: BProc, n: PNode): Rope
  416. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType): Rope
  417. proc initLocExpr(p: BProc, e: PNode, result: var TLoc) =
  418. initLoc(result, locNone, e, OnUnknown)
  419. expr(p, e, result)
  420. proc initLocExprSingleUse(p: BProc, e: PNode, result: var TLoc) =
  421. initLoc(result, locNone, e, OnUnknown)
  422. result.flags.incl lfSingleUse
  423. expr(p, e, result)
  424. proc lenField(p: BProc): Rope =
  425. result = rope(if p.module.compileToCpp: "len" else: "Sup.len")
  426. include ccgcalls, "ccgstmts.nim", "ccgexprs.nim"
  427. # ----------------------------- dynamic library handling -----------------
  428. # We don't finalize dynamic libs as the OS does this for us.
  429. proc isGetProcAddr(lib: PLib): bool =
  430. let n = lib.path
  431. result = n.kind in nkCallKinds and n.typ != nil and
  432. n.typ.kind in {tyPointer, tyProc}
  433. proc loadDynamicLib(m: BModule, lib: PLib) =
  434. assert(lib != nil)
  435. if not lib.generated:
  436. lib.generated = true
  437. var tmp = getTempName(m)
  438. assert(lib.name == nil)
  439. lib.name = tmp # BUGFIX: cgsym has awful side-effects
  440. addf(m.s[cfsVars], "static void* $1;$n", [tmp])
  441. if lib.path.kind in {nkStrLit..nkTripleStrLit}:
  442. var s: TStringSeq = @[]
  443. libCandidates(lib.path.strVal, s)
  444. rawMessage(hintDependency, lib.path.strVal)
  445. var loadlib: Rope = nil
  446. for i in countup(0, high(s)):
  447. inc(m.labels)
  448. if i > 0: add(loadlib, "||")
  449. appcg(m, loadlib, "($1 = #nimLoadLibrary((#NimStringDesc*) &$2))$n",
  450. [tmp, getStrLit(m, s[i])])
  451. appcg(m, m.s[cfsDynLibInit],
  452. "if (!($1)) #nimLoadLibraryError((#NimStringDesc*) &$2);$n",
  453. [loadlib, getStrLit(m, lib.path.strVal)])
  454. else:
  455. var p = newProc(nil, m)
  456. p.options = p.options - {optStackTrace, optEndb}
  457. var dest: TLoc
  458. initLocExpr(p, lib.path, dest)
  459. add(m.s[cfsVars], p.s(cpsLocals))
  460. add(m.s[cfsDynLibInit], p.s(cpsInit))
  461. add(m.s[cfsDynLibInit], p.s(cpsStmts))
  462. appcg(m, m.s[cfsDynLibInit],
  463. "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n",
  464. [tmp, rdLoc(dest)])
  465. if lib.name == nil: internalError("loadDynamicLib")
  466. proc mangleDynLibProc(sym: PSym): Rope =
  467. if sfCompilerProc in sym.flags:
  468. # NOTE: sym.loc.r is the external name!
  469. result = rope(sym.name.s)
  470. else:
  471. result = "Dl_$1_" % [rope(sym.id)]
  472. proc symInDynamicLib(m: BModule, sym: PSym) =
  473. var lib = sym.annex
  474. let isCall = isGetProcAddr(lib)
  475. var extname = sym.loc.r
  476. if not isCall: loadDynamicLib(m, lib)
  477. var tmp = mangleDynLibProc(sym)
  478. sym.loc.r = tmp # from now on we only need the internal name
  479. sym.typ.sym = nil # generate a new name
  480. inc(m.labels, 2)
  481. if isCall:
  482. let n = lib.path
  483. var a: TLoc
  484. initLocExpr(m.initProc, n[0], a)
  485. var params = rdLoc(a) & "("
  486. for i in 1 .. n.len-2:
  487. initLocExpr(m.initProc, n[i], a)
  488. params.add(rdLoc(a))
  489. params.add(", ")
  490. let load = "\t$1 = ($2) ($3$4));$n" %
  491. [tmp, getTypeDesc(m, sym.typ), params, makeCString($extname)]
  492. var last = lastSon(n)
  493. if last.kind == nkHiddenStdConv: last = last.sons[1]
  494. internalAssert(last.kind == nkStrLit)
  495. let idx = last.strVal
  496. if idx.len == 0:
  497. add(m.initProc.s(cpsStmts), load)
  498. elif idx.len == 1 and idx[0] in {'0'..'9'}:
  499. add(m.extensionLoaders[idx[0]], load)
  500. else:
  501. internalError(sym.info, "wrong index: " & idx)
  502. else:
  503. appcg(m, m.s[cfsDynLibInit],
  504. "\t$1 = ($2) #nimGetProcAddr($3, $4);$n",
  505. [tmp, getTypeDesc(m, sym.typ), lib.name, makeCString($extname)])
  506. addf(m.s[cfsVars], "$2 $1;$n", [sym.loc.r, getTypeDesc(m, sym.loc.t)])
  507. proc varInDynamicLib(m: BModule, sym: PSym) =
  508. var lib = sym.annex
  509. var extname = sym.loc.r
  510. loadDynamicLib(m, lib)
  511. incl(sym.loc.flags, lfIndirect)
  512. var tmp = mangleDynLibProc(sym)
  513. sym.loc.r = tmp # from now on we only need the internal name
  514. inc(m.labels, 2)
  515. appcg(m, m.s[cfsDynLibInit],
  516. "$1 = ($2*) #nimGetProcAddr($3, $4);$n",
  517. [tmp, getTypeDesc(m, sym.typ), lib.name, makeCString($extname)])
  518. addf(m.s[cfsVars], "$2* $1;$n",
  519. [sym.loc.r, getTypeDesc(m, sym.loc.t)])
  520. proc symInDynamicLibPartial(m: BModule, sym: PSym) =
  521. sym.loc.r = mangleDynLibProc(sym)
  522. sym.typ.sym = nil # generate a new name
  523. proc cgsym(m: BModule, name: string): Rope =
  524. var sym = magicsys.getCompilerProc(name)
  525. if sym != nil:
  526. case sym.kind
  527. of skProc, skFunc, skMethod, skConverter, skIterator: genProc(m, sym)
  528. of skVar, skResult, skLet: genVarPrototype(m, newSymNode sym)
  529. of skType: discard getTypeDesc(m, sym.typ)
  530. else: internalError("cgsym: " & name & ": " & $sym.kind)
  531. else:
  532. # we used to exclude the system module from this check, but for DLL
  533. # generation support this sloppyness leads to hard to detect bugs, so
  534. # we're picky here for the system module too:
  535. rawMessage(errSystemNeeds, name)
  536. result = sym.loc.r
  537. proc generateHeaders(m: BModule) =
  538. add(m.s[cfsHeaders], tnl & "#include \"nimbase.h\"" & tnl)
  539. for it in m.headerFiles:
  540. if it[0] == '#':
  541. add(m.s[cfsHeaders], rope(it.replace('`', '"') & tnl))
  542. elif it[0] notin {'\"', '<'}:
  543. addf(m.s[cfsHeaders], "#include \"$1\"$N", [rope(it)])
  544. else:
  545. addf(m.s[cfsHeaders], "#include $1$N", [rope(it)])
  546. add(m.s[cfsHeaders], "#undef LANGUAGE_C" & tnl)
  547. add(m.s[cfsHeaders], "#undef MIPSEB" & tnl)
  548. add(m.s[cfsHeaders], "#undef MIPSEL" & tnl)
  549. add(m.s[cfsHeaders], "#undef PPC" & tnl)
  550. add(m.s[cfsHeaders], "#undef R3000" & tnl)
  551. add(m.s[cfsHeaders], "#undef R4000" & tnl)
  552. add(m.s[cfsHeaders], "#undef i386" & tnl)
  553. add(m.s[cfsHeaders], "#undef linux" & tnl)
  554. add(m.s[cfsHeaders], "#undef mips" & tnl)
  555. add(m.s[cfsHeaders], "#undef near" & tnl)
  556. add(m.s[cfsHeaders], "#undef powerpc" & tnl)
  557. add(m.s[cfsHeaders], "#undef unix" & tnl)
  558. proc initFrame(p: BProc, procname, filename: Rope): Rope =
  559. discard cgsym(p.module, "nimFrame")
  560. if p.maxFrameLen > 0:
  561. discard cgsym(p.module, "VarSlot")
  562. result = rfmt(nil, "\tnimfrs_($1, $2, $3, $4);$n",
  563. procname, filename, p.maxFrameLen.rope,
  564. p.blocks[0].frameLen.rope)
  565. else:
  566. result = rfmt(nil, "\tnimfr_($1, $2);$n", procname, filename)
  567. proc deinitFrame(p: BProc): Rope =
  568. result = rfmt(p.module, "\t#popFrame();$n")
  569. proc closureSetup(p: BProc, prc: PSym) =
  570. if tfCapturesEnv notin prc.typ.flags: return
  571. # prc.ast[paramsPos].last contains the type we're after:
  572. var ls = lastSon(prc.ast[paramsPos])
  573. if ls.kind != nkSym:
  574. internalError(prc.info, "closure generation failed")
  575. var env = ls.sym
  576. #echo "created environment: ", env.id, " for ", prc.name.s
  577. assignLocalVar(p, ls)
  578. # generate cast assignment:
  579. linefmt(p, cpsStmts, "$1 = ($2) ClE_0;$n",
  580. rdLoc(env.loc), getTypeDesc(p.module, env.typ))
  581. proc containsResult(n: PNode): bool =
  582. if n.kind == nkSym and n.sym.kind == skResult:
  583. result = true
  584. else:
  585. for i in 0..<n.safeLen:
  586. if containsResult(n[i]): return true
  587. proc easyResultAsgn(n: PNode): PNode =
  588. const harmless = {nkConstSection, nkTypeSection, nkEmpty, nkCommentStmt} +
  589. declarativeDefs
  590. case n.kind
  591. of nkStmtList, nkStmtListExpr:
  592. var i = 0
  593. while i < n.len and n[i].kind in harmless: inc i
  594. if i < n.len: result = easyResultAsgn(n[i])
  595. of nkAsgn, nkFastAsgn:
  596. if n[0].kind == nkSym and n[0].sym.kind == skResult and not containsResult(n[1]):
  597. incl n.flags, nfPreventCg
  598. return n[1]
  599. of nkReturnStmt:
  600. if n.len > 0:
  601. result = easyResultAsgn(n[0])
  602. if result != nil: incl n.flags, nfPreventCg
  603. else: discard
  604. proc genProcAux(m: BModule, prc: PSym) =
  605. var p = newProc(prc, m)
  606. var header = genProcHeader(m, prc)
  607. var returnStmt: Rope = nil
  608. assert(prc.ast != nil)
  609. if sfPure notin prc.flags and prc.typ.sons[0] != nil:
  610. if resultPos >= prc.ast.len:
  611. internalError(prc.info, "proc has no result symbol")
  612. let resNode = prc.ast.sons[resultPos]
  613. let res = resNode.sym # get result symbol
  614. if not isInvalidReturnType(prc.typ.sons[0]):
  615. if sfNoInit in prc.flags: incl(res.flags, sfNoInit)
  616. if sfNoInit in prc.flags and p.module.compileToCpp and (let val = easyResultAsgn(prc.getBody); val != nil):
  617. var decl = localVarDecl(p, resNode)
  618. var a: TLoc
  619. initLocExprSingleUse(p, val, a)
  620. linefmt(p, cpsStmts, "$1 = $2;$n", decl, rdLoc(a))
  621. else:
  622. # declare the result symbol:
  623. assignLocalVar(p, resNode)
  624. assert(res.loc.r != nil)
  625. initLocalVar(p, res, immediateAsgn=false)
  626. returnStmt = rfmt(nil, "\treturn $1;$n", rdLoc(res.loc))
  627. else:
  628. fillResult(resNode)
  629. assignParam(p, res)
  630. if skipTypes(res.typ, abstractInst).kind == tyArray:
  631. #incl(res.loc.flags, lfIndirect)
  632. res.loc.storage = OnUnknown
  633. for i in countup(1, sonsLen(prc.typ.n) - 1):
  634. let param = prc.typ.n.sons[i].sym
  635. if param.typ.isCompileTimeOnly: continue
  636. assignParam(p, param)
  637. closureSetup(p, prc)
  638. genStmts(p, prc.getBody) # modifies p.locals, p.init, etc.
  639. var generatedProc: Rope
  640. if sfNoReturn in prc.flags:
  641. if hasDeclspec in extccomp.CC[extccomp.cCompiler].props:
  642. header = "__declspec(noreturn) " & header
  643. if sfPure in prc.flags:
  644. if hasDeclspec in extccomp.CC[extccomp.cCompiler].props:
  645. header = "__declspec(naked) " & header
  646. generatedProc = rfmt(nil, "$N$1 {$n$2$3$4}$N$N",
  647. header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts))
  648. else:
  649. generatedProc = rfmt(nil, "$N$1 {$N", header)
  650. add(generatedProc, initGCFrame(p))
  651. if optStackTrace in prc.options:
  652. add(generatedProc, p.s(cpsLocals))
  653. var procname = makeCString(prc.name.s)
  654. add(generatedProc, initFrame(p, procname, prc.info.quotedFilename))
  655. else:
  656. add(generatedProc, p.s(cpsLocals))
  657. if optProfiler in prc.options:
  658. # invoke at proc entry for recursion:
  659. appcg(p, cpsInit, "\t#nimProfile();$n", [])
  660. if p.beforeRetNeeded: add(generatedProc, "{")
  661. add(generatedProc, p.s(cpsInit))
  662. add(generatedProc, p.s(cpsStmts))
  663. if p.beforeRetNeeded: add(generatedProc, ~"\t}BeforeRet_: ;$n")
  664. add(generatedProc, deinitGCFrame(p))
  665. if optStackTrace in prc.options: add(generatedProc, deinitFrame(p))
  666. add(generatedProc, returnStmt)
  667. add(generatedProc, ~"}$N")
  668. add(m.s[cfsProcs], generatedProc)
  669. proc requiresExternC(m: BModule; sym: PSym): bool {.inline.} =
  670. result = (sfCompileToCpp in m.module.flags and
  671. sfCompileToCpp notin sym.getModule().flags and
  672. gCmd != cmdCompileToCpp) or (
  673. sym.flags * {sfImportc, sfInfixCall, sfCompilerProc} == {sfImportc} and
  674. sym.magic == mNone and
  675. gCmd == cmdCompileToCpp)
  676. proc genProcPrototype(m: BModule, sym: PSym) =
  677. useHeader(m, sym)
  678. if lfNoDecl in sym.loc.flags: return
  679. if lfDynamicLib in sym.loc.flags:
  680. if getModule(sym).id != m.module.id and
  681. not containsOrIncl(m.declaredThings, sym.id):
  682. add(m.s[cfsVars], rfmt(nil, "extern $1 $2;$n",
  683. getTypeDesc(m, sym.loc.t), mangleDynLibProc(sym)))
  684. elif not containsOrIncl(m.declaredProtos, sym.id):
  685. var header = genProcHeader(m, sym)
  686. if sfNoReturn in sym.flags and hasDeclspec in extccomp.CC[cCompiler].props:
  687. header = "__declspec(noreturn) " & header
  688. if sym.typ.callConv != ccInline and requiresExternC(m, sym):
  689. header = "extern \"C\" " & header
  690. if sfPure in sym.flags and hasAttribute in CC[cCompiler].props:
  691. header.add(" __attribute__((naked))")
  692. if sfNoReturn in sym.flags and hasAttribute in CC[cCompiler].props:
  693. header.add(" __attribute__((noreturn))")
  694. add(m.s[cfsProcHeaders], rfmt(nil, "$1;$n", header))
  695. proc genProcNoForward(m: BModule, prc: PSym) =
  696. if lfImportCompilerProc in prc.loc.flags:
  697. fillProcLoc(m, prc.ast[namePos])
  698. useHeader(m, prc)
  699. # dependency to a compilerproc:
  700. discard cgsym(m, prc.name.s)
  701. return
  702. if lfNoDecl in prc.loc.flags:
  703. fillProcLoc(m, prc.ast[namePos])
  704. useHeader(m, prc)
  705. genProcPrototype(m, prc)
  706. elif prc.typ.callConv == ccInline:
  707. # We add inline procs to the calling module to enable C based inlining.
  708. # This also means that a check with ``q.declaredThings`` is wrong, we need
  709. # a check for ``m.declaredThings``.
  710. if not containsOrIncl(m.declaredThings, prc.id):
  711. #if prc.loc.k == locNone:
  712. fillProcLoc(m, prc.ast[namePos])
  713. #elif {sfExportc, sfImportc} * prc.flags == {}:
  714. # # reset name to restore consistency in case of hashing collisions:
  715. # echo "resetting ", prc.id, " by ", m.module.name.s
  716. # prc.loc.r = nil
  717. # prc.loc.r = mangleName(m, prc)
  718. useHeader(m, prc)
  719. genProcPrototype(m, prc)
  720. genProcAux(m, prc)
  721. elif lfDynamicLib in prc.loc.flags:
  722. var q = findPendingModule(m, prc)
  723. fillProcLoc(q, prc.ast[namePos])
  724. useHeader(m, prc)
  725. genProcPrototype(m, prc)
  726. if q != nil and not containsOrIncl(q.declaredThings, prc.id):
  727. symInDynamicLib(q, prc)
  728. else:
  729. symInDynamicLibPartial(m, prc)
  730. elif sfImportc notin prc.flags:
  731. var q = findPendingModule(m, prc)
  732. fillProcLoc(q, prc.ast[namePos])
  733. useHeader(m, prc)
  734. genProcPrototype(m, prc)
  735. if q != nil and not containsOrIncl(q.declaredThings, prc.id):
  736. genProcAux(q, prc)
  737. else:
  738. fillProcLoc(m, prc.ast[namePos])
  739. useHeader(m, prc)
  740. if sfInfixCall notin prc.flags: genProcPrototype(m, prc)
  741. proc requestConstImpl(p: BProc, sym: PSym) =
  742. var m = p.module
  743. useHeader(m, sym)
  744. if sym.loc.k == locNone:
  745. fillLoc(sym.loc, locData, sym.ast, mangleName(p.module, sym), OnStatic)
  746. if lfNoDecl in sym.loc.flags: return
  747. # declare implementation:
  748. var q = findPendingModule(m, sym)
  749. if q != nil and not containsOrIncl(q.declaredThings, sym.id):
  750. assert q.initProc.module == q
  751. addf(q.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  752. [getTypeDesc(q, sym.typ), sym.loc.r, genConstExpr(q.initProc, sym.ast)])
  753. # declare header:
  754. if q != m and not containsOrIncl(m.declaredThings, sym.id):
  755. assert(sym.loc.r != nil)
  756. let headerDecl = "extern NIM_CONST $1 $2;$n" %
  757. [getTypeDesc(m, sym.loc.t), sym.loc.r]
  758. add(m.s[cfsData], headerDecl)
  759. if sfExportc in sym.flags and p.module.g.generatedHeader != nil:
  760. add(p.module.g.generatedHeader.s[cfsData], headerDecl)
  761. proc isActivated(prc: PSym): bool = prc.typ != nil
  762. proc genProc(m: BModule, prc: PSym) =
  763. if sfBorrow in prc.flags or not isActivated(prc): return
  764. if sfForward in prc.flags:
  765. addForwardedProc(m, prc)
  766. fillProcLoc(m, prc.ast[namePos])
  767. else:
  768. genProcNoForward(m, prc)
  769. if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and
  770. m.g.generatedHeader != nil and lfNoDecl notin prc.loc.flags:
  771. genProcPrototype(m.g.generatedHeader, prc)
  772. if prc.typ.callConv == ccInline:
  773. if not containsOrIncl(m.g.generatedHeader.declaredThings, prc.id):
  774. genProcAux(m.g.generatedHeader, prc)
  775. proc genVarPrototypeAux(m: BModule, n: PNode) =
  776. #assert(sfGlobal in sym.flags)
  777. let sym = n.sym
  778. useHeader(m, sym)
  779. fillLoc(sym.loc, locGlobalVar, n, mangleName(m, sym), OnHeap)
  780. if (lfNoDecl in sym.loc.flags) or containsOrIncl(m.declaredThings, sym.id):
  781. return
  782. if sym.owner.id != m.module.id:
  783. # else we already have the symbol generated!
  784. assert(sym.loc.r != nil)
  785. if sfThread in sym.flags:
  786. declareThreadVar(m, sym, true)
  787. else:
  788. add(m.s[cfsVars], "extern ")
  789. add(m.s[cfsVars], getTypeDesc(m, sym.loc.t))
  790. if lfDynamicLib in sym.loc.flags: add(m.s[cfsVars], "*")
  791. if sfRegister in sym.flags: add(m.s[cfsVars], " register")
  792. if sfVolatile in sym.flags: add(m.s[cfsVars], " volatile")
  793. addf(m.s[cfsVars], " $1;$n", [sym.loc.r])
  794. proc genVarPrototype(m: BModule, n: PNode) =
  795. genVarPrototypeAux(m, n)
  796. proc addIntTypes(result: var Rope) {.inline.} =
  797. addf(result, "#define NIM_NEW_MANGLING_RULES" & tnl &
  798. "#define NIM_INTBITS $1" & tnl, [
  799. platform.CPU[targetCPU].intSize.rope])
  800. proc getCopyright(cfile: Cfile): Rope =
  801. if optCompileOnly in gGlobalOptions:
  802. result = ("/* Generated by Nim Compiler v$1 */$N" &
  803. "/* (c) " & CompileDate.substr(0, 3) & " Andreas Rumpf */$N" &
  804. "/* The generated code is subject to the original license. */$N") %
  805. [rope(VersionAsString)]
  806. else:
  807. result = ("/* Generated by Nim Compiler v$1 */$N" &
  808. "/* (c) " & CompileDate.substr(0, 3) & " Andreas Rumpf */$N" &
  809. "/* The generated code is subject to the original license. */$N" &
  810. "/* Compiled for: $2, $3, $4 */$N" &
  811. "/* Command for C compiler:$n $5 */$N") %
  812. [rope(VersionAsString),
  813. rope(platform.OS[targetOS].name),
  814. rope(platform.CPU[targetCPU].name),
  815. rope(extccomp.CC[extccomp.cCompiler].name),
  816. rope(getCompileCFileCmd(cfile))]
  817. proc getFileHeader(cfile: Cfile): Rope =
  818. result = getCopyright(cfile)
  819. addIntTypes(result)
  820. proc genFilenames(m: BModule): Rope =
  821. discard cgsym(m, "dbgRegisterFilename")
  822. result = nil
  823. for i in 0.. <fileInfos.len:
  824. result.addf("dbgRegisterFilename($1);$N", [fileInfos[i].projPath.makeCString])
  825. proc genMainProc(m: BModule) =
  826. const
  827. # The use of a volatile function pointer to call Pre/NimMainInner
  828. # prevents inlining of the NimMainInner function and dependent
  829. # functions, which might otherwise merge their stack frames.
  830. PreMainBody =
  831. "void PreMainInner(void) {$N" &
  832. "\tsystemInit000();$N" &
  833. "$1" &
  834. "$2" &
  835. "$3" &
  836. "}$N$N" &
  837. "void PreMain(void) {$N" &
  838. "\tvoid (*volatile inner)(void);$N" &
  839. "\tsystemDatInit000();$N" &
  840. "\tinner = PreMainInner;$N" &
  841. "$4$5" &
  842. "\t(*inner)();$N" &
  843. "}$N$N"
  844. MainProcs =
  845. "\tNimMain();$N"
  846. MainProcsWithResult =
  847. MainProcs & "\treturn nim_program_result;$N"
  848. NimMainInner = "N_CDECL(void, NimMainInner)(void) {$N" &
  849. "$1" &
  850. "}$N$N"
  851. NimMainProc =
  852. "N_CDECL(void, NimMain)(void) {$N" &
  853. "\tvoid (*volatile inner)(void);$N" &
  854. "\tPreMain();$N" &
  855. "\tinner = NimMainInner;$N" &
  856. "$2" &
  857. "\t(*inner)();$N" &
  858. "}$N$N"
  859. NimMainBody = NimMainInner & NimMainProc
  860. PosixNimMain =
  861. "int cmdCount;$N" &
  862. "char** cmdLine;$N" &
  863. "char** gEnv;$N" &
  864. NimMainBody
  865. PosixCMain =
  866. "int main(int argc, char** args, char** env) {$N" &
  867. "\tcmdLine = args;$N" &
  868. "\tcmdCount = argc;$N" &
  869. "\tgEnv = env;$N" &
  870. MainProcsWithResult &
  871. "}$N$N"
  872. StandaloneCMain =
  873. "int main(void) {$N" &
  874. MainProcs &
  875. "\treturn 0;$N" &
  876. "}$N$N"
  877. WinNimMain = NimMainBody
  878. WinCMain = "N_STDCALL(int, WinMain)(HINSTANCE hCurInstance, $N" &
  879. " HINSTANCE hPrevInstance, $N" &
  880. " LPSTR lpCmdLine, int nCmdShow) {$N" &
  881. MainProcsWithResult & "}$N$N"
  882. WinNimDllMain = NimMainInner & "N_LIB_EXPORT " & NimMainProc
  883. WinCDllMain =
  884. "BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fwdreason, $N" &
  885. " LPVOID lpvReserved) {$N" &
  886. "\tif(fwdreason == DLL_PROCESS_ATTACH) {$N" & MainProcs & "}$N" &
  887. "\treturn 1;$N}$N$N"
  888. PosixNimDllMain = WinNimDllMain
  889. PosixCDllMain =
  890. "void NIM_POSIX_INIT NimMainInit(void) {$N" &
  891. MainProcs &
  892. "}$N$N"
  893. GenodeNimMain =
  894. "Libc::Env *genodeEnv;$N" &
  895. NimMainBody
  896. ComponentConstruct =
  897. "void Libc::Component::construct(Libc::Env &env) {$N" &
  898. "\tgenodeEnv = &env;$N" &
  899. "\tLibc::with_libc([&] () {$N\t" &
  900. MainProcs &
  901. "\t});$N" &
  902. "}$N$N"
  903. var nimMain, otherMain: FormatStr
  904. if platform.targetOS == osWindows and
  905. gGlobalOptions * {optGenGuiApp, optGenDynLib} != {}:
  906. if optGenGuiApp in gGlobalOptions:
  907. nimMain = WinNimMain
  908. otherMain = WinCMain
  909. else:
  910. nimMain = WinNimDllMain
  911. otherMain = WinCDllMain
  912. m.includeHeader("<windows.h>")
  913. elif platform.targetOS == osGenode:
  914. nimMain = GenodeNimMain
  915. otherMain = ComponentConstruct
  916. elif optGenDynLib in gGlobalOptions:
  917. nimMain = PosixNimDllMain
  918. otherMain = PosixCDllMain
  919. elif platform.targetOS == osStandalone:
  920. nimMain = PosixNimMain
  921. otherMain = StandaloneCMain
  922. else:
  923. nimMain = PosixNimMain
  924. otherMain = PosixCMain
  925. if m.g.breakpoints != nil: discard cgsym(m, "dbgRegisterBreakpoint")
  926. if optEndb in gOptions:
  927. m.g.breakpoints.add(m.genFilenames)
  928. let initStackBottomCall =
  929. if platform.targetOS == osStandalone or gSelectedGC == gcNone: "".rope
  930. else: ropecg(m, "\t#initStackBottomWith((void *)&inner);$N")
  931. inc(m.labels)
  932. appcg(m, m.s[cfsProcs], PreMainBody, [
  933. m.g.mainDatInit, m.g.breakpoints, m.g.otherModsInit,
  934. if emulatedThreadVars() and platform.targetOS != osStandalone:
  935. ropecg(m, "\t#initThreadVarsEmulation();$N")
  936. else:
  937. "".rope,
  938. initStackBottomCall])
  939. appcg(m, m.s[cfsProcs], nimMain,
  940. [m.g.mainModInit, initStackBottomCall, rope(m.labels)])
  941. if optNoMain notin gGlobalOptions:
  942. appcg(m, m.s[cfsProcs], otherMain, [])
  943. proc getSomeInitName(m: PSym, suffix: string): Rope =
  944. assert m.kind == skModule
  945. assert m.owner.kind == skPackage
  946. if {sfSystemModule, sfMainModule} * m.flags == {}:
  947. result = m.owner.name.s.mangle.rope
  948. result.add "_"
  949. result.add m.name.s
  950. result.add suffix
  951. proc getInitName(m: PSym): Rope =
  952. if sfMainModule in m.flags:
  953. # generate constant name for main module, for "easy" debugging.
  954. result = rope"NimMainModule"
  955. else:
  956. result = getSomeInitName(m, "Init000")
  957. proc getDatInitName(m: PSym): Rope = getSomeInitName(m, "DatInit000")
  958. proc registerModuleToMain(g: BModuleList; m: PSym) =
  959. var
  960. init = m.getInitName
  961. datInit = m.getDatInitName
  962. addf(g.mainModProcs, "NIM_EXTERNC N_NOINLINE(void, $1)(void);$N", [init])
  963. addf(g.mainModProcs, "NIM_EXTERNC N_NOINLINE(void, $1)(void);$N", [datInit])
  964. if sfSystemModule notin m.flags:
  965. addf(g.mainDatInit, "\t$1();$N", [datInit])
  966. let initCall = "\t$1();$N" % [init]
  967. if sfMainModule in m.flags:
  968. add(g.mainModInit, initCall)
  969. else:
  970. add(g.otherModsInit, initCall)
  971. proc genInitCode(m: BModule) =
  972. var initname = getInitName(m.module)
  973. var prc = "NIM_EXTERNC N_NOINLINE(void, $1)(void) {$N" % [initname]
  974. if m.typeNodes > 0:
  975. appcg(m, m.s[cfsTypeInit1], "static #TNimNode $1[$2];$n",
  976. [m.typeNodesName, rope(m.typeNodes)])
  977. if m.nimTypes > 0:
  978. appcg(m, m.s[cfsTypeInit1], "static #TNimType $1[$2];$n",
  979. [m.nimTypesName, rope(m.nimTypes)])
  980. add(prc, initGCFrame(m.initProc))
  981. add(prc, genSectionStart(cpsLocals))
  982. add(prc, m.preInitProc.s(cpsLocals))
  983. add(prc, m.initProc.s(cpsLocals))
  984. add(prc, m.postInitProc.s(cpsLocals))
  985. add(prc, genSectionEnd(cpsLocals))
  986. if optStackTrace in m.initProc.options and frameDeclared notin m.flags:
  987. # BUT: the generated init code might depend on a current frame, so
  988. # declare it nevertheless:
  989. incl m.flags, frameDeclared
  990. if preventStackTrace notin m.flags:
  991. var procname = makeCString(m.module.name.s)
  992. add(prc, initFrame(m.initProc, procname, m.module.info.quotedFilename))
  993. else:
  994. add(prc, ~"\tTFrame FR_; FR_.len = 0;$N")
  995. add(prc, genSectionStart(cpsInit))
  996. add(prc, m.preInitProc.s(cpsInit))
  997. add(prc, m.initProc.s(cpsInit))
  998. add(prc, m.postInitProc.s(cpsInit))
  999. add(prc, genSectionEnd(cpsInit))
  1000. add(prc, genSectionStart(cpsStmts))
  1001. add(prc, m.preInitProc.s(cpsStmts))
  1002. add(prc, m.initProc.s(cpsStmts))
  1003. add(prc, m.postInitProc.s(cpsStmts))
  1004. add(prc, genSectionEnd(cpsStmts))
  1005. if optStackTrace in m.initProc.options and preventStackTrace notin m.flags:
  1006. add(prc, deinitFrame(m.initProc))
  1007. add(prc, deinitGCFrame(m.initProc))
  1008. addf(prc, "}$N$N", [])
  1009. prc.addf("NIM_EXTERNC N_NOINLINE(void, $1)(void) {$N",
  1010. [getDatInitName(m.module)])
  1011. for i in cfsTypeInit1..cfsDynLibInit:
  1012. add(prc, genSectionStart(i))
  1013. add(prc, m.s[i])
  1014. add(prc, genSectionEnd(i))
  1015. addf(prc, "}$N$N", [])
  1016. # we cannot simply add the init proc to ``m.s[cfsProcs]`` anymore because
  1017. # that would lead to a *nesting* of merge sections which the merger does
  1018. # not support. So we add it to another special section: ``cfsInitProc``
  1019. add(m.s[cfsInitProc], prc)
  1020. for i, el in pairs(m.extensionLoaders):
  1021. if el != nil:
  1022. let ex = "N_NIMCALL(void, nimLoadProcs$1)(void) {$2}$N$N" %
  1023. [(i.ord - '0'.ord).rope, el]
  1024. add(m.s[cfsInitProc], ex)
  1025. proc genModule(m: BModule, cfile: Cfile): Rope =
  1026. result = getFileHeader(cfile)
  1027. result.add(genMergeInfo(m))
  1028. generateThreadLocalStorage(m)
  1029. generateHeaders(m)
  1030. for i in countup(cfsHeaders, cfsProcs):
  1031. add(result, genSectionStart(i))
  1032. add(result, m.s[i])
  1033. add(result, genSectionEnd(i))
  1034. add(result, m.s[cfsInitProc])
  1035. proc newPreInitProc(m: BModule): BProc =
  1036. result = newProc(nil, m)
  1037. # little hack so that unique temporaries are generated:
  1038. result.labels = 100_000
  1039. proc newPostInitProc(m: BModule): BProc =
  1040. result = newProc(nil, m)
  1041. # little hack so that unique temporaries are generated:
  1042. result.labels = 200_000
  1043. proc initProcOptions(m: BModule): TOptions =
  1044. if sfSystemModule in m.module.flags: gOptions-{optStackTrace} else: gOptions
  1045. proc rawNewModule(g: BModuleList; module: PSym, filename: string): BModule =
  1046. new(result)
  1047. result.tmpBase = rope("TM" & $hashOwner(module) & "_")
  1048. result.headerFiles = @[]
  1049. result.declaredThings = initIntSet()
  1050. result.declaredProtos = initIntSet()
  1051. result.cfilename = filename
  1052. result.filename = filename
  1053. result.typeCache = initTable[SigHash, Rope]()
  1054. result.forwTypeCache = initTable[SigHash, Rope]()
  1055. result.module = module
  1056. result.typeInfoMarker = initTable[SigHash, Rope]()
  1057. result.sigConflicts = initCountTable[SigHash]()
  1058. result.initProc = newProc(nil, result)
  1059. result.initProc.options = initProcOptions(result)
  1060. result.preInitProc = newPreInitProc(result)
  1061. result.postInitProc = newPostInitProc(result)
  1062. initNodeTable(result.dataCache)
  1063. result.typeStack = @[]
  1064. result.forwardedProcs = @[]
  1065. result.typeNodesName = getTempName(result)
  1066. result.nimTypesName = getTempName(result)
  1067. result.g = g
  1068. # no line tracing for the init sections of the system module so that we
  1069. # don't generate a TFrame which can confuse the stack botton initialization:
  1070. if sfSystemModule in module.flags:
  1071. incl result.flags, preventStackTrace
  1072. excl(result.preInitProc.options, optStackTrace)
  1073. excl(result.postInitProc.options, optStackTrace)
  1074. let ndiName = if optCDebug in gGlobalOptions: changeFileExt(completeCFilePath(filename), "ndi")
  1075. else: ""
  1076. open(result.ndi, ndiName)
  1077. proc nullify[T](arr: var T) =
  1078. for i in low(arr)..high(arr):
  1079. arr[i] = Rope(nil)
  1080. proc resetModule*(m: BModule) =
  1081. # between two compilations in CAAS mode, we can throw
  1082. # away all the data that was written to disk
  1083. m.headerFiles = @[]
  1084. m.declaredProtos = initIntSet()
  1085. m.forwTypeCache = initTable[SigHash, Rope]()
  1086. m.initProc = newProc(nil, m)
  1087. m.initProc.options = initProcOptions(m)
  1088. m.preInitProc = newPreInitProc(m)
  1089. m.postInitProc = newPostInitProc(m)
  1090. initNodeTable(m.dataCache)
  1091. m.typeStack = @[]
  1092. m.forwardedProcs = @[]
  1093. m.typeNodesName = getTempName(m)
  1094. m.nimTypesName = getTempName(m)
  1095. if sfSystemModule in m.module.flags:
  1096. incl m.flags, preventStackTrace
  1097. else:
  1098. excl m.flags, preventStackTrace
  1099. nullify m.s
  1100. m.typeNodes = 0
  1101. m.nimTypes = 0
  1102. nullify m.extensionLoaders
  1103. # indicate that this is now cached module
  1104. # the cache will be invalidated by nullifying gModules
  1105. m.fromCache = true
  1106. m.g = nil
  1107. # we keep only the "merge info" information for the module
  1108. # and the properties that can't change:
  1109. # m.filename
  1110. # m.cfilename
  1111. # m.isHeaderFile
  1112. # m.module ?
  1113. # m.typeCache
  1114. # m.declaredThings
  1115. # m.typeInfoMarker
  1116. # m.labels
  1117. # m.FrameDeclared
  1118. proc resetCgenModules*(g: BModuleList) =
  1119. for m in cgenModules(g): resetModule(m)
  1120. proc rawNewModule(g: BModuleList; module: PSym): BModule =
  1121. result = rawNewModule(g, module, module.position.int32.toFullPath)
  1122. proc newModule(g: BModuleList; module: PSym): BModule =
  1123. # we should create only one cgen module for each module sym
  1124. result = rawNewModule(g, module)
  1125. growCache g.modules, module.position
  1126. g.modules[module.position] = result
  1127. if (optDeadCodeElim in gGlobalOptions):
  1128. if (sfDeadCodeElim in module.flags):
  1129. internalError("added pending module twice: " & module.filename)
  1130. template injectG(config) {.dirty.} =
  1131. if graph.backend == nil:
  1132. graph.backend = newModuleList(config)
  1133. let g = BModuleList(graph.backend)
  1134. proc myOpen(graph: ModuleGraph; module: PSym; cache: IdentCache): PPassContext =
  1135. injectG(graph.config)
  1136. result = newModule(g, module)
  1137. if optGenIndex in gGlobalOptions and g.generatedHeader == nil:
  1138. let f = if graph.config.headerFile.len > 0: graph.config.headerFile else: gProjectFull
  1139. g.generatedHeader = rawNewModule(g, module,
  1140. changeFileExt(completeCFilePath(f), hExt))
  1141. incl g.generatedHeader.flags, isHeaderFile
  1142. proc writeHeader(m: BModule) =
  1143. var result = ("/* Generated by Nim Compiler v$1 */$N" &
  1144. "/* (c) " & CompileDate.substr(0, 3) & " Andreas Rumpf */$N" &
  1145. "/* The generated code is subject to the original license. */$N") %
  1146. [rope(VersionAsString)]
  1147. var guard = "__$1__" % [m.filename.splitFile.name.rope]
  1148. result.addf("#ifndef $1$n#define $1$n", [guard])
  1149. addIntTypes(result)
  1150. generateHeaders(m)
  1151. generateThreadLocalStorage(m)
  1152. for i in countup(cfsHeaders, cfsProcs):
  1153. add(result, genSectionStart(i))
  1154. add(result, m.s[i])
  1155. add(result, genSectionEnd(i))
  1156. add(result, m.s[cfsInitProc])
  1157. if optGenDynLib in gGlobalOptions:
  1158. result.add("N_LIB_IMPORT ")
  1159. result.addf("N_CDECL(void, NimMain)(void);$n", [])
  1160. result.addf("#endif /* $1 */$n", [guard])
  1161. writeRope(result, m.filename)
  1162. proc getCFile(m: BModule): string =
  1163. let ext =
  1164. if m.compileToCpp: ".cpp"
  1165. elif gCmd == cmdCompileToOC or sfCompileToObjC in m.module.flags: ".m"
  1166. else: ".c"
  1167. result = changeFileExt(completeCFilePath(m.cfilename.withPackageName), ext)
  1168. proc myOpenCached(graph: ModuleGraph; module: PSym, rd: PRodReader): PPassContext =
  1169. injectG(graph.config)
  1170. assert optSymbolFiles in gGlobalOptions
  1171. var m = newModule(g, module)
  1172. readMergeInfo(getCFile(m), m)
  1173. result = m
  1174. proc myProcess(b: PPassContext, n: PNode): PNode =
  1175. result = n
  1176. if b == nil or passes.skipCodegen(n): return
  1177. var m = BModule(b)
  1178. m.initProc.options = initProcOptions(m)
  1179. softRnl = if optLineDir in gOptions: noRnl else: rnl
  1180. genStmts(m.initProc, n)
  1181. proc finishModule(m: BModule) =
  1182. var i = 0
  1183. while i <= high(m.forwardedProcs):
  1184. # Note: ``genProc`` may add to ``m.forwardedProcs``, so we cannot use
  1185. # a ``for`` loop here
  1186. var prc = m.forwardedProcs[i]
  1187. if sfForward in prc.flags:
  1188. internalError(prc.info, "still forwarded: " & prc.name.s)
  1189. genProcNoForward(m, prc)
  1190. inc(i)
  1191. assert(m.g.forwardedProcsCounter >= i)
  1192. dec(m.g.forwardedProcsCounter, i)
  1193. setLen(m.forwardedProcs, 0)
  1194. proc shouldRecompile(code: Rope, cfile: Cfile): bool =
  1195. result = true
  1196. if optForceFullMake notin gGlobalOptions:
  1197. if not equalsFile(code, cfile.cname):
  1198. if isDefined("nimdiff"):
  1199. if fileExists(cfile.cname):
  1200. copyFile(cfile.cname, cfile.cname & ".backup")
  1201. echo "diff ", cfile.cname, ".backup ", cfile.cname
  1202. else:
  1203. echo "new file ", cfile.cname
  1204. writeRope(code, cfile.cname)
  1205. return
  1206. if existsFile(cfile.obj) and os.fileNewer(cfile.obj, cfile.cname):
  1207. result = false
  1208. else:
  1209. writeRope(code, cfile.cname)
  1210. # We need 2 different logics here: pending modules (including
  1211. # 'nim__dat') may require file merging for the combination of dead code
  1212. # elimination and incremental compilation! Non pending modules need no
  1213. # such logic and in fact the logic hurts for the main module at least;
  1214. # it would generate multiple 'main' procs, for instance.
  1215. proc writeModule(m: BModule, pending: bool) =
  1216. # generate code for the init statements of the module:
  1217. let cfile = getCFile(m)
  1218. if not m.fromCache or optForceFullMake in gGlobalOptions:
  1219. genInitCode(m)
  1220. finishTypeDescriptions(m)
  1221. if sfMainModule in m.module.flags:
  1222. # generate main file:
  1223. add(m.s[cfsProcHeaders], m.g.mainModProcs)
  1224. generateThreadVarsSize(m)
  1225. var cf = Cfile(cname: cfile, obj: completeCFilePath(toObjFile(cfile)), flags: {})
  1226. var code = genModule(m, cf)
  1227. when hasTinyCBackend:
  1228. if gCmd == cmdRun:
  1229. tccgen.compileCCode($code)
  1230. return
  1231. if not shouldRecompile(code, cf): cf.flags = {CfileFlag.Cached}
  1232. addFileToCompile(cf)
  1233. elif pending and mergeRequired(m) and sfMainModule notin m.module.flags:
  1234. let cf = Cfile(cname: cfile, obj: completeCFilePath(toObjFile(cfile)), flags: {})
  1235. mergeFiles(cfile, m)
  1236. genInitCode(m)
  1237. finishTypeDescriptions(m)
  1238. var code = genModule(m, cf)
  1239. writeRope(code, cfile)
  1240. addFileToCompile(cf)
  1241. else:
  1242. # Consider: first compilation compiles ``system.nim`` and produces
  1243. # ``system.c`` but then compilation fails due to an error. This means
  1244. # that ``system.o`` is missing, so we need to call the C compiler for it:
  1245. var cf = Cfile(cname: cfile, obj: completeCFilePath(toObjFile(cfile)), flags: {})
  1246. if not existsFile(cf.obj): cf.flags = {CfileFlag.Cached}
  1247. addFileToCompile(cf)
  1248. close(m.ndi)
  1249. proc updateCachedModule(m: BModule) =
  1250. let cfile = getCFile(m)
  1251. var cf = Cfile(cname: cfile, obj: completeCFilePath(toObjFile(cfile)), flags: {})
  1252. if mergeRequired(m) and sfMainModule notin m.module.flags:
  1253. mergeFiles(cfile, m)
  1254. genInitCode(m)
  1255. finishTypeDescriptions(m)
  1256. var code = genModule(m, cf)
  1257. writeRope(code, cfile)
  1258. else:
  1259. cf.flags = {CfileFlag.Cached}
  1260. addFileToCompile(cf)
  1261. proc myClose(graph: ModuleGraph; b: PPassContext, n: PNode): PNode =
  1262. result = n
  1263. if b == nil or passes.skipCodegen(n): return
  1264. var m = BModule(b)
  1265. if n != nil:
  1266. m.initProc.options = initProcOptions(m)
  1267. genStmts(m.initProc, n)
  1268. # cached modules need to registered too:
  1269. registerModuleToMain(m.g, m.module)
  1270. if sfMainModule in m.module.flags:
  1271. if m.g.forwardedProcsCounter == 0:
  1272. incl m.flags, objHasKidsValid
  1273. let disp = generateMethodDispatchers(graph)
  1274. for x in disp: genProcAux(m, x.sym)
  1275. genMainProc(m)
  1276. proc cgenWriteModules*(backend: RootRef, config: ConfigRef) =
  1277. let g = BModuleList(backend)
  1278. # we need to process the transitive closure because recursive module
  1279. # deps are allowed (and the system module is processed in the wrong
  1280. # order anyway)
  1281. g.config = config
  1282. if g.generatedHeader != nil: finishModule(g.generatedHeader)
  1283. while g.forwardedProcsCounter > 0:
  1284. for m in cgenModules(g):
  1285. if not m.fromCache:
  1286. finishModule(m)
  1287. for m in cgenModules(g):
  1288. if m.fromCache:
  1289. m.updateCachedModule
  1290. else:
  1291. m.writeModule(pending=true)
  1292. writeMapping(g.mapping)
  1293. if g.generatedHeader != nil: writeHeader(g.generatedHeader)
  1294. const cgenPass* = makePass(myOpen, myOpenCached, myProcess, myClose)