cbackend.nim 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. import ".."/[ast, options, lineinfos, modulegraphs, cgendata, cgen,
  21. pathutils, extccomp, msgs, modulepaths]
  22. import packed_ast, ic, dce, rodfiles
  23. proc unpackTree(g: ModuleGraph; thisModule: int;
  24. tree: PackedTree; n: NodePos): PNode =
  25. var decoder = initPackedDecoder(g.config, g.cache)
  26. result = loadNodes(decoder, g.packed, thisModule, tree, n)
  27. proc setupBackendModule(g: ModuleGraph; m: var LoadedModule) =
  28. if g.backend == nil:
  29. g.backend = cgendata.newModuleList(g)
  30. assert g.backend != nil
  31. var bmod = cgen.newModule(BModuleList(g.backend), m.module, g.config)
  32. bmod.idgen = idgenFromLoadedModule(m)
  33. proc generateCodeForModule(g: ModuleGraph; m: var LoadedModule; alive: var AliveSyms) =
  34. var bmod = BModuleList(g.backend).modules[m.module.position]
  35. assert bmod != nil
  36. bmod.flags.incl useAliveDataFromDce
  37. bmod.alive = move alive[m.module.position]
  38. for p in allNodes(m.fromDisk.topLevel):
  39. let n = unpackTree(g, m.module.position, m.fromDisk.topLevel, p)
  40. cgen.genTopLevelStmt(bmod, n)
  41. finalCodegenActions(g, bmod, newNodeI(nkStmtList, m.module.info))
  42. m.fromDisk.backendFlags = cgen.whichInitProcs(bmod)
  43. proc replayTypeInfo(g: ModuleGraph; m: var LoadedModule; origin: FileIndex) =
  44. for x in mitems(m.fromDisk.emittedTypeInfo):
  45. #echo "found type ", x, " for file ", int(origin)
  46. g.emittedTypeInfo[x] = origin
  47. proc addFileToLink(config: ConfigRef; m: PSym) =
  48. let filename = AbsoluteFile toFullPath(config, m.position.FileIndex)
  49. let ext =
  50. if config.backend == backendCpp: ".nim.cpp"
  51. elif config.backend == backendObjc: ".nim.m"
  52. else: ".nim.c"
  53. let cfile = changeFileExt(completeCfilePath(config,
  54. mangleModuleName(config, filename).AbsoluteFile), ext)
  55. let objFile = completeCfilePath(config, toObjFile(config, cfile))
  56. if fileExists(objFile):
  57. var cf = Cfile(nimname: m.name.s, cname: cfile,
  58. obj: objFile,
  59. flags: {CfileFlag.Cached})
  60. addFileToCompile(config, cf)
  61. when defined(debugDce):
  62. import os, std/packedsets
  63. proc storeAliveSymsImpl(asymFile: AbsoluteFile; s: seq[int32]) =
  64. var f = rodfiles.create(asymFile.string)
  65. f.storeHeader()
  66. f.storeSection aliveSymsSection
  67. f.storeSeq(s)
  68. close f
  69. template prepare {.dirty.} =
  70. let asymFile = toRodFile(config, AbsoluteFile toFullPath(config, position.FileIndex), ".alivesyms")
  71. var s = newSeqOfCap[int32](alive[position].len)
  72. for a in items(alive[position]): s.add int32(a)
  73. sort(s)
  74. proc storeAliveSyms(config: ConfigRef; position: int; alive: AliveSyms) =
  75. prepare()
  76. storeAliveSymsImpl(asymFile, s)
  77. proc aliveSymsChanged(config: ConfigRef; position: int; alive: AliveSyms): bool =
  78. prepare()
  79. var f2 = rodfiles.open(asymFile.string)
  80. f2.loadHeader()
  81. f2.loadSection aliveSymsSection
  82. var oldData: seq[int32]
  83. f2.loadSeq(oldData)
  84. f2.close
  85. if f2.err == ok and oldData == s:
  86. result = false
  87. else:
  88. when defined(debugDce):
  89. let oldAsSet = toPackedSet[int32](oldData)
  90. let newAsSet = toPackedSet[int32](s)
  91. echo "set of live symbols changed ", asymFile.changeFileExt("rod"), " ", position, " ", f2.err
  92. echo "in old but not in new ", oldAsSet.difference(newAsSet), " number of entries in old ", oldAsSet.len
  93. echo "in new but not in old ", newAsSet.difference(oldAsSet), " number of entries in new ", newAsSet.len
  94. #if execShellCmd(getAppFilename() & " rod " & quoteShell(asymFile.changeFileExt("rod"))) != 0:
  95. # echo "command failed"
  96. result = true
  97. storeAliveSymsImpl(asymFile, s)
  98. proc genPackedModule(g: ModuleGraph, i: int; alive: var AliveSyms) =
  99. # case statement here to enforce exhaustive checks.
  100. case g.packed[i].status
  101. of undefined:
  102. discard "nothing to do"
  103. of loading, stored:
  104. assert false
  105. of storing, outdated:
  106. storeAliveSyms(g.config, g.packed[i].module.position, alive)
  107. generateCodeForModule(g, g.packed[i], alive)
  108. closeRodFile(g, g.packed[i].module)
  109. of loaded:
  110. if g.packed[i].loadedButAliveSetChanged:
  111. generateCodeForModule(g, g.packed[i], alive)
  112. else:
  113. addFileToLink(g.config, g.packed[i].module)
  114. replayTypeInfo(g, g.packed[i], FileIndex(i))
  115. if g.backend == nil:
  116. g.backend = cgendata.newModuleList(g)
  117. registerInitProcs(BModuleList(g.backend), g.packed[i].module, g.packed[i].fromDisk.backendFlags)
  118. proc generateCode*(g: ModuleGraph) =
  119. ## The single entry point, generate C(++) code for the entire
  120. ## Nim program aka `ModuleGraph`.
  121. resetForBackend(g)
  122. var alive = computeAliveSyms(g.packed, g.config)
  123. when false:
  124. for i in 0..high(g.packed):
  125. echo i, " is of status ", g.packed[i].status, " ", toFullPath(g.config, FileIndex(i))
  126. # First pass: Setup all the backend modules for all the modules that have
  127. # changed:
  128. for i in 0..high(g.packed):
  129. # case statement here to enforce exhaustive checks.
  130. case g.packed[i].status
  131. of undefined:
  132. discard "nothing to do"
  133. of loading, stored:
  134. assert false
  135. of storing, outdated:
  136. setupBackendModule(g, g.packed[i])
  137. of loaded:
  138. # Even though this module didn't change, DCE might trigger a change.
  139. # Consider this case: Module A uses symbol S from B and B does not use
  140. # S itself. A is then edited not to use S either. Thus we have to
  141. # recompile B in order to remove S from the final result.
  142. if aliveSymsChanged(g.config, g.packed[i].module.position, alive):
  143. g.packed[i].loadedButAliveSetChanged = true
  144. setupBackendModule(g, g.packed[i])
  145. # Second pass: Code generation.
  146. let mainModuleIdx = g.config.projectMainIdx2.int
  147. # We need to generate the main module last, because only then
  148. # all init procs have been registered:
  149. for i in 0..high(g.packed):
  150. if i != mainModuleIdx:
  151. genPackedModule(g, i, alive)
  152. if mainModuleIdx >= 0:
  153. genPackedModule(g, mainModuleIdx, alive)