ccgthreadvars.nim 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ## Thread var support for crappy architectures that lack native support for
  10. ## thread local storage. (**Thank you Mac OS X!**)
  11. # included from cgen.nim
  12. proc emulatedThreadVars(conf: ConfigRef): bool =
  13. result = {optThreads, optTlsEmulation} <= conf.globalOptions
  14. proc accessThreadLocalVar(p: BProc, s: PSym) =
  15. if emulatedThreadVars(p.config) and not p.threadVarAccessed:
  16. p.threadVarAccessed = true
  17. incl p.module.flags, usesThreadVars
  18. addf(p.procSec(cpsLocals), "\tNimThreadVars* NimTV_;$n", [])
  19. add(p.procSec(cpsInit),
  20. ropecg(p.module, "\tNimTV_ = (NimThreadVars*) #GetThreadLocalVars();$n"))
  21. proc declareThreadVar(m: BModule, s: PSym, isExtern: bool) =
  22. if emulatedThreadVars(m.config):
  23. # we gather all thread locals var into a struct; we need to allocate
  24. # storage for that somehow, can't use the thread local storage
  25. # allocator for it :-(
  26. if not containsOrIncl(m.g.nimtvDeclared, s.id):
  27. m.g.nimtvDeps.add(s.loc.t)
  28. addf(m.g.nimtv, "$1 $2;$n", [getTypeDesc(m, s.loc.t), s.loc.r])
  29. else:
  30. if isExtern: add(m.s[cfsVars], "extern ")
  31. if optThreads in m.config.globalOptions: add(m.s[cfsVars], "NIM_THREADVAR ")
  32. add(m.s[cfsVars], getTypeDesc(m, s.loc.t))
  33. addf(m.s[cfsVars], " $1;$n", [s.loc.r])
  34. proc generateThreadLocalStorage(m: BModule) =
  35. if m.g.nimtv != nil and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
  36. for t in items(m.g.nimtvDeps): discard getTypeDesc(m, t)
  37. addf(m.s[cfsSeqTypes], "typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
  38. proc generateThreadVarsSize(m: BModule) =
  39. if m.g.nimtv != nil:
  40. let externc = if m.config.cmd == cmdCompileToCpp or
  41. sfCompileToCpp in m.module.flags: "extern \"C\" "
  42. else: ""
  43. addf(m.s[cfsProcs],
  44. "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n",
  45. [externc.rope])