ccgthreadvars.nim 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  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 threadVarAccessed notin p.flags:
  16. p.flags.incl threadVarAccessed
  17. incl p.module.flags, usesThreadVars
  18. p.procSec(cpsLocals).addf("\tNimThreadVars* NimTV_;$n", [])
  19. p.procSec(cpsInit).add(
  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. m.g.nimtv.addf("$1 $2;$n", [getTypeDesc(m, s.loc.t), s.loc.r])
  29. else:
  30. if isExtern: m.s[cfsVars].add("extern ")
  31. elif lfExportLib in s.loc.flags: m.s[cfsVars].add("N_LIB_EXPORT_VAR ")
  32. else: m.s[cfsVars].add("N_LIB_PRIVATE ")
  33. if optThreads in m.config.globalOptions: m.s[cfsVars].add("NIM_THREADVAR ")
  34. m.s[cfsVars].add(getTypeDesc(m, s.loc.t))
  35. m.s[cfsVars].addf(" $1;$n", [s.loc.r])
  36. proc generateThreadLocalStorage(m: BModule) =
  37. if m.g.nimtv != nil and (usesThreadVars in m.flags or sfMainModule in m.module.flags):
  38. for t in items(m.g.nimtvDeps): discard getTypeDesc(m, t)
  39. finishTypeDescriptions(m)
  40. m.s[cfsSeqTypes].addf("typedef struct {$1} NimThreadVars;$n", [m.g.nimtv])
  41. proc generateThreadVarsSize(m: BModule) =
  42. if m.g.nimtv != nil:
  43. let externc = if m.config.backend == backendCpp or
  44. sfCompileToCpp in m.module.flags: "extern \"C\" "
  45. else: ""
  46. m.s[cfsProcs].addf(
  47. "$#NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}$n",
  48. [externc.rope])