cbackend.nim 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2021 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## New entry point into our C/C++ code generator. Ideally
  10. ## somebody would rewrite the old backend (which is 8000 lines of crufty Nim code)
  11. ## to work on packed trees directly and produce the C code as an AST which can
  12. ## then be rendered to text in a very simple manner. Unfortunately nobody wrote
  13. ## this code. So instead we wrap the existing cgen.nim and its friends so that
  14. ## we call directly into the existing code generation logic but avoiding the
  15. ## naive, outdated `passes` design. Thus you will see some
  16. ## `useAliveDataFromDce in flags` checks in the old code -- the old code is
  17. ## also doing cross-module dependency tracking and DCE that we don't need
  18. ## anymore. DCE is now done as prepass over the entire packed module graph.
  19. import std/[packedsets, algorithm, tables]
  20. when defined(nimPreviewSlimSystem):
  21. import std/assertions
  22. import ".."/[ast, options, lineinfos, modulegraphs, cgendata, cgen,
  23. pathutils, extccomp, msgs, modulepaths]
  24. import packed_ast, ic, dce, rodfiles
  25. proc unpackTree(g: ModuleGraph; thisModule: int;
  26. tree: PackedTree; n: NodePos): PNode =
  27. var decoder = initPackedDecoder(g.config, g.cache)
  28. result = loadNodes(decoder, g.packed, thisModule, tree, n)
  29. proc setupBackendModule(g: ModuleGraph; m: var LoadedModule) =
  30. if g.backend == nil:
  31. g.backend = cgendata.newModuleList(g)
  32. assert g.backend != nil
  33. var bmod = cgen.newModule(BModuleList(g.backend), m.module, g.config)
  34. bmod.idgen = idgenFromLoadedModule(m)
  35. proc generateCodeForModule(g: ModuleGraph; m: var LoadedModule; alive: var AliveSyms) =
  36. var bmod = BModuleList(g.backend).modules[m.module.position]
  37. assert bmod != nil
  38. bmod.flags.incl useAliveDataFromDce
  39. bmod.alive = move alive[m.module.position]
  40. for p in allNodes(m.fromDisk.topLevel):
  41. let n = unpackTree(g, m.module.position, m.fromDisk.topLevel, p)
  42. cgen.genTopLevelStmt(bmod, n)
  43. finalCodegenActions(g, bmod, newNodeI(nkStmtList, m.module.info))
  44. for disp in getDispatchers(g):
  45. genProcAux(bmod, disp)
  46. m.fromDisk.backendFlags = cgen.whichInitProcs(bmod)
  47. proc replayTypeInfo(g: ModuleGraph; m: var LoadedModule; origin: FileIndex) =
  48. for x in mitems(m.fromDisk.emittedTypeInfo):
  49. #echo "found type ", x, " for file ", int(origin)
  50. g.emittedTypeInfo[x] = origin
  51. proc addFileToLink(config: ConfigRef; m: PSym) =
  52. let filename = AbsoluteFile toFullPath(config, m.position.FileIndex)
  53. let ext =
  54. if config.backend == backendCpp: ".nim.cpp"
  55. elif config.backend == backendObjc: ".nim.m"
  56. else: ".nim.c"
  57. let cfile = changeFileExt(completeCfilePath(config,
  58. mangleModuleName(config, filename).AbsoluteFile), ext)
  59. let objFile = completeCfilePath(config, toObjFile(config, cfile))
  60. if fileExists(objFile):
  61. var cf = Cfile(nimname: m.name.s, cname: cfile,
  62. obj: objFile,
  63. flags: {CfileFlag.Cached})
  64. addFileToCompile(config, cf)
  65. when defined(debugDce):
  66. import os, std/packedsets
  67. proc storeAliveSymsImpl(asymFile: AbsoluteFile; s: seq[int32]) =
  68. var f = rodfiles.create(asymFile.string)
  69. f.storeHeader()
  70. f.storeSection aliveSymsSection
  71. f.storeSeq(s)
  72. close f
  73. template prepare {.dirty.} =
  74. let asymFile = toRodFile(config, AbsoluteFile toFullPath(config, position.FileIndex), ".alivesyms")
  75. var s = newSeqOfCap[int32](alive[position].len)
  76. for a in items(alive[position]): s.add int32(a)
  77. sort(s)
  78. proc storeAliveSyms(config: ConfigRef; position: int; alive: AliveSyms) =
  79. prepare()
  80. storeAliveSymsImpl(asymFile, s)
  81. proc aliveSymsChanged(config: ConfigRef; position: int; alive: AliveSyms): bool =
  82. prepare()
  83. var f2 = rodfiles.open(asymFile.string)
  84. f2.loadHeader()
  85. f2.loadSection aliveSymsSection
  86. var oldData: seq[int32] = @[]
  87. f2.loadSeq(oldData)
  88. f2.close
  89. if f2.err == ok and oldData == s:
  90. result = false
  91. else:
  92. when defined(debugDce):
  93. let oldAsSet = toPackedSet[int32](oldData)
  94. let newAsSet = toPackedSet[int32](s)
  95. echo "set of live symbols changed ", asymFile.changeFileExt("rod"), " ", position, " ", f2.err
  96. echo "in old but not in new ", oldAsSet.difference(newAsSet), " number of entries in old ", oldAsSet.len
  97. echo "in new but not in old ", newAsSet.difference(oldAsSet), " number of entries in new ", newAsSet.len
  98. #if execShellCmd(getAppFilename() & " rod " & quoteShell(asymFile.changeFileExt("rod"))) != 0:
  99. # echo "command failed"
  100. result = true
  101. storeAliveSymsImpl(asymFile, s)
  102. proc genPackedModule(g: ModuleGraph, i: int; alive: var AliveSyms) =
  103. # case statement here to enforce exhaustive checks.
  104. case g.packed[i].status
  105. of undefined:
  106. discard "nothing to do"
  107. of loading, stored:
  108. assert false
  109. of storing, outdated:
  110. storeAliveSyms(g.config, g.packed[i].module.position, alive)
  111. generateCodeForModule(g, g.packed[i], alive)
  112. closeRodFile(g, g.packed[i].module)
  113. of loaded:
  114. if g.packed[i].loadedButAliveSetChanged:
  115. generateCodeForModule(g, g.packed[i], alive)
  116. else:
  117. addFileToLink(g.config, g.packed[i].module)
  118. replayTypeInfo(g, g.packed[i], FileIndex(i))
  119. if g.backend == nil:
  120. g.backend = cgendata.newModuleList(g)
  121. registerInitProcs(BModuleList(g.backend), g.packed[i].module, g.packed[i].fromDisk.backendFlags)
  122. proc generateCode*(g: ModuleGraph) =
  123. ## The single entry point, generate C(++) code for the entire
  124. ## Nim program aka `ModuleGraph`.
  125. resetForBackend(g)
  126. var alive = computeAliveSyms(g.packed, g.config)
  127. when false:
  128. for i in 0..<len(g.packed):
  129. echo i, " is of status ", g.packed[i].status, " ", toFullPath(g.config, FileIndex(i))
  130. # First pass: Setup all the backend modules for all the modules that have
  131. # changed:
  132. for i in 0..<len(g.packed):
  133. # case statement here to enforce exhaustive checks.
  134. case g.packed[i].status
  135. of undefined:
  136. discard "nothing to do"
  137. of loading, stored:
  138. assert false
  139. of storing, outdated:
  140. setupBackendModule(g, g.packed[i])
  141. of loaded:
  142. # Even though this module didn't change, DCE might trigger a change.
  143. # Consider this case: Module A uses symbol S from B and B does not use
  144. # S itself. A is then edited not to use S either. Thus we have to
  145. # recompile B in order to remove S from the final result.
  146. if aliveSymsChanged(g.config, g.packed[i].module.position, alive):
  147. g.packed[i].loadedButAliveSetChanged = true
  148. setupBackendModule(g, g.packed[i])
  149. # Second pass: Code generation.
  150. let mainModuleIdx = g.config.projectMainIdx2.int
  151. # We need to generate the main module last, because only then
  152. # all init procs have been registered:
  153. for i in 0..<len(g.packed):
  154. if i != mainModuleIdx:
  155. genPackedModule(g, i, alive)
  156. if mainModuleIdx >= 0:
  157. genPackedModule(g, mainModuleIdx, alive)