spawn.nim 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425
  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 threadpool's ``spawn``.
  10. import ast, types, idents, magicsys, msgs, options, modulegraphs,
  11. lowerings, liftdestructors, renderer
  12. from trees import getMagic, getRoot
  13. proc callProc(a: PNode): PNode =
  14. result = newNodeI(nkCall, a.info)
  15. result.add a
  16. result.typ = a.typ[0]
  17. # we have 4 cases to consider:
  18. # - a void proc --> nothing to do
  19. # - a proc returning GC'ed memory --> requires a flowVar
  20. # - a proc returning non GC'ed memory --> pass as hidden 'var' parameter
  21. # - not in a parallel environment --> requires a flowVar for memory safety
  22. type
  23. TSpawnResult* = enum
  24. srVoid, srFlowVar, srByVar
  25. TFlowVarKind = enum
  26. fvInvalid # invalid type T for 'FlowVar[T]'
  27. fvGC # FlowVar of a GC'ed type
  28. fvBlob # FlowVar of a blob type
  29. proc spawnResult*(t: PType; inParallel: bool): TSpawnResult =
  30. if t.isEmptyType: srVoid
  31. elif inParallel and not containsGarbageCollectedRef(t): srByVar
  32. else: srFlowVar
  33. proc flowVarKind(c: ConfigRef, t: PType): TFlowVarKind =
  34. if c.selectedGC in {gcArc, gcOrc}: fvBlob
  35. elif t.skipTypes(abstractInst).kind in {tyRef, tyString, tySequence}: fvGC
  36. elif containsGarbageCollectedRef(t): fvInvalid
  37. else: fvBlob
  38. proc typeNeedsNoDeepCopy(t: PType): bool =
  39. var t = t.skipTypes(abstractInst)
  40. # for the tconvexhull example (and others) we're a bit lax here and pretend
  41. # seqs and strings are *by value* only and 'shallow' doesn't exist!
  42. if t.kind == tyString: return true
  43. # note that seq[T] is fine, but 'var seq[T]' is not, so we need to skip 'var'
  44. # for the stricter check and likewise we can skip 'seq' for a less
  45. # strict check:
  46. if t.kind in {tyVar, tyLent, tySequence}: t = t.lastSon
  47. result = not containsGarbageCollectedRef(t)
  48. proc addLocalVar(g: ModuleGraph; varSection, varInit: PNode; owner: PSym; typ: PType;
  49. v: PNode; useShallowCopy=false): PSym =
  50. result = newSym(skTemp, getIdent(g.cache, genPrefix), owner, varSection.info,
  51. owner.options)
  52. result.typ = typ
  53. incl(result.flags, sfFromGeneric)
  54. var vpart = newNodeI(nkIdentDefs, varSection.info, 3)
  55. vpart[0] = newSymNode(result)
  56. vpart[1] = newNodeI(nkEmpty, varSection.info)
  57. vpart[2] = if varInit.isNil: v else: vpart[1]
  58. varSection.add vpart
  59. if varInit != nil:
  60. if g.config.selectedGC in {gcArc, gcOrc}:
  61. # inject destructors pass will do its own analysis
  62. varInit.add newFastMoveStmt(g, newSymNode(result), v)
  63. else:
  64. if useShallowCopy and typeNeedsNoDeepCopy(typ) or optTinyRtti in g.config.globalOptions:
  65. varInit.add newFastMoveStmt(g, newSymNode(result), v)
  66. else:
  67. let deepCopyCall = newNodeI(nkCall, varInit.info, 3)
  68. deepCopyCall[0] = newSymNode(getSysMagic(g, varSection.info, "deepCopy", mDeepCopy))
  69. deepCopyCall[1] = newSymNode(result)
  70. deepCopyCall[2] = v
  71. varInit.add deepCopyCall
  72. discard """
  73. We generate roughly this:
  74. proc f_wrapper(thread, args) =
  75. barrierEnter(args.barrier) # for parallel statement
  76. var a = args.a # thread transfer; deepCopy or shallowCopy or no copy
  77. # depending on whether we're in a 'parallel' statement
  78. var b = args.b
  79. var fv = args.fv
  80. fv.owner = thread # optional
  81. nimArgsPassingDone() # signal parent that the work is done
  82. #
  83. args.fv.blob = f(a, b, ...)
  84. nimFlowVarSignal(args.fv)
  85. # - or -
  86. f(a, b, ...)
  87. barrierLeave(args.barrier) # for parallel statement
  88. stmtList:
  89. var scratchObj
  90. scratchObj.a = a
  91. scratchObj.b = b
  92. nimSpawn(f_wrapper, addr scratchObj)
  93. scratchObj.fv # optional
  94. """
  95. proc createWrapperProc(g: ModuleGraph; f: PNode; threadParam, argsParam: PSym;
  96. varSection, varInit, call, barrier, fv: PNode;
  97. spawnKind: TSpawnResult, result: PSym) =
  98. var body = newNodeI(nkStmtList, f.info)
  99. var threadLocalBarrier: PSym
  100. if barrier != nil:
  101. var varSection2 = newNodeI(nkVarSection, barrier.info)
  102. threadLocalBarrier = addLocalVar(g, varSection2, nil, result,
  103. barrier.typ, barrier)
  104. body.add varSection2
  105. body.add callCodegenProc(g, "barrierEnter", threadLocalBarrier.info,
  106. threadLocalBarrier.newSymNode)
  107. var threadLocalProm: PSym
  108. if spawnKind == srByVar:
  109. threadLocalProm = addLocalVar(g, varSection, nil, result, fv.typ, fv)
  110. elif fv != nil:
  111. internalAssert g.config, fv.typ.kind == tyGenericInst
  112. threadLocalProm = addLocalVar(g, varSection, nil, result, fv.typ, fv)
  113. body.add varSection
  114. body.add varInit
  115. if fv != nil and spawnKind != srByVar:
  116. # generate:
  117. # fv.owner = threadParam
  118. body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
  119. "owner", fv.info, g.cache), threadParam.newSymNode)
  120. body.add callCodegenProc(g, "nimArgsPassingDone", threadParam.info,
  121. threadParam.newSymNode)
  122. if spawnKind == srByVar:
  123. body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call)
  124. elif fv != nil:
  125. let fk = flowVarKind(g.config, fv.typ[1])
  126. if fk == fvInvalid:
  127. localError(g.config, f.info, "cannot create a flowVar of type: " &
  128. typeToString(fv.typ[1]))
  129. body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
  130. if fk == fvGC: "data" else: "blob", fv.info, g.cache), call)
  131. if fk == fvGC:
  132. let incRefCall = newNodeI(nkCall, fv.info, 2)
  133. incRefCall[0] = newSymNode(getSysMagic(g, fv.info, "GCref", mGCref))
  134. incRefCall[1] = indirectAccess(threadLocalProm.newSymNode,
  135. "data", fv.info, g.cache)
  136. body.add incRefCall
  137. if barrier == nil:
  138. # by now 'fv' is shared and thus might have beeen overwritten! we need
  139. # to use the thread-local view instead:
  140. body.add callCodegenProc(g, "nimFlowVarSignal", threadLocalProm.info,
  141. threadLocalProm.newSymNode)
  142. else:
  143. body.add call
  144. if barrier != nil:
  145. body.add callCodegenProc(g, "barrierLeave", threadLocalBarrier.info,
  146. threadLocalBarrier.newSymNode)
  147. var params = newNodeI(nkFormalParams, f.info)
  148. params.add newNodeI(nkEmpty, f.info)
  149. params.add threadParam.newSymNode
  150. params.add argsParam.newSymNode
  151. var t = newType(tyProc, threadParam.owner)
  152. t.rawAddSon nil
  153. t.rawAddSon threadParam.typ
  154. t.rawAddSon argsParam.typ
  155. t.n = newNodeI(nkFormalParams, f.info)
  156. t.n.add newNodeI(nkEffectList, f.info)
  157. t.n.add threadParam.newSymNode
  158. t.n.add argsParam.newSymNode
  159. let emptyNode = newNodeI(nkEmpty, f.info)
  160. result.ast = newProcNode(nkProcDef, f.info, body = body,
  161. params = params, name = newSymNode(result), pattern = emptyNode,
  162. genericParams = emptyNode, pragmas = emptyNode,
  163. exceptions = emptyNode)
  164. result.typ = t
  165. proc createCastExpr(argsParam: PSym; objType: PType): PNode =
  166. result = newNodeI(nkCast, argsParam.info)
  167. result.add newNodeI(nkEmpty, argsParam.info)
  168. result.add newSymNode(argsParam)
  169. result.typ = newType(tyPtr, objType.owner)
  170. result.typ.rawAddSon(objType)
  171. proc setupArgsForConcurrency(g: ModuleGraph; n: PNode; objType: PType;
  172. owner: PSym; scratchObj: PSym,
  173. castExpr, call,
  174. varSection, varInit, result: PNode) =
  175. let formals = n[0].typ.n
  176. let tmpName = getIdent(g.cache, genPrefix)
  177. for i in 1..<n.len:
  178. # we pick n's type here, which hopefully is 'tyArray' and not
  179. # 'tyOpenArray':
  180. var argType = n[i].typ.skipTypes(abstractInst)
  181. if i < formals.len:
  182. if formals[i].typ.kind in {tyVar, tyLent}:
  183. localError(g.config, n[i].info, "'spawn'ed function cannot have a 'var' parameter")
  184. if formals[i].typ.kind in {tyTypeDesc, tyStatic}:
  185. continue
  186. #elif containsTyRef(argType):
  187. # localError(n[i].info, "'spawn'ed function cannot refer to 'ref'/closure")
  188. let fieldname = if i < formals.len: formals[i].sym.name else: tmpName
  189. var field = newSym(skField, fieldname, objType.owner, n.info, g.config.options)
  190. field.typ = argType
  191. objType.addField(field, g.cache)
  192. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[i])
  193. let temp = addLocalVar(g, varSection, varInit, owner, argType,
  194. indirectAccess(castExpr, field, n.info))
  195. call.add(newSymNode(temp))
  196. proc setupArgsForParallelism(g: ModuleGraph; n: PNode; objType: PType;
  197. owner: PSym; scratchObj: PSym;
  198. castExpr, call,
  199. varSection, varInit, result: PNode) =
  200. let formals = n[0].typ.n
  201. let tmpName = getIdent(g.cache, genPrefix)
  202. # we need to copy the foreign scratch object fields into local variables
  203. # for correctness: These are called 'threadLocal' here.
  204. for i in 1..<n.len:
  205. let n = n[i]
  206. if i < formals.len and formals[i].typ.kind in {tyStatic, tyTypeDesc}:
  207. continue
  208. let argType = skipTypes(if i < formals.len: formals[i].typ else: n.typ,
  209. abstractInst)
  210. #if containsTyRef(argType):
  211. # localError(n.info, "'spawn'ed function cannot refer to 'ref'/closure")
  212. let fieldname = if i < formals.len: formals[i].sym.name else: tmpName
  213. var field = newSym(skField, fieldname, objType.owner, n.info, g.config.options)
  214. if argType.kind in {tyVarargs, tyOpenArray}:
  215. # important special case: we always create a zero-copy slice:
  216. let slice = newNodeI(nkCall, n.info, 4)
  217. slice.typ = n.typ
  218. slice[0] = newSymNode(createMagic(g, "slice", mSlice))
  219. slice[0].typ = getSysType(g, n.info, tyInt) # fake type
  220. var fieldB = newSym(skField, tmpName, objType.owner, n.info, g.config.options)
  221. fieldB.typ = getSysType(g, n.info, tyInt)
  222. objType.addField(fieldB, g.cache)
  223. if getMagic(n) == mSlice:
  224. let a = genAddrOf(n[1])
  225. field.typ = a.typ
  226. objType.addField(field, g.cache)
  227. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  228. var fieldA = newSym(skField, tmpName, objType.owner, n.info, g.config.options)
  229. fieldA.typ = getSysType(g, n.info, tyInt)
  230. objType.addField(fieldA, g.cache)
  231. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldA), n[2])
  232. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), n[3])
  233. let threadLocal = addLocalVar(g, varSection,nil, owner, fieldA.typ,
  234. indirectAccess(castExpr, fieldA, n.info),
  235. useShallowCopy=true)
  236. slice[2] = threadLocal.newSymNode
  237. else:
  238. let a = genAddrOf(n)
  239. field.typ = a.typ
  240. objType.addField(field, g.cache)
  241. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  242. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), genHigh(g, n))
  243. slice[2] = newIntLit(g, n.info, 0)
  244. # the array itself does not need to go through a thread local variable:
  245. slice[1] = genDeref(indirectAccess(castExpr, field, n.info))
  246. let threadLocal = addLocalVar(g, varSection,nil, owner, fieldB.typ,
  247. indirectAccess(castExpr, fieldB, n.info),
  248. useShallowCopy=true)
  249. slice[3] = threadLocal.newSymNode
  250. call.add slice
  251. elif (let size = computeSize(g.config, argType); size < 0 or size > 16) and
  252. n.getRoot != nil:
  253. # it is more efficient to pass a pointer instead:
  254. let a = genAddrOf(n)
  255. field.typ = a.typ
  256. objType.addField(field, g.cache)
  257. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  258. let threadLocal = addLocalVar(g, varSection,nil, owner, field.typ,
  259. indirectAccess(castExpr, field, n.info),
  260. useShallowCopy=true)
  261. call.add(genDeref(threadLocal.newSymNode))
  262. else:
  263. # boring case
  264. field.typ = argType
  265. objType.addField(field, g.cache)
  266. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n)
  267. let threadLocal = addLocalVar(g, varSection, varInit,
  268. owner, field.typ,
  269. indirectAccess(castExpr, field, n.info),
  270. useShallowCopy=true)
  271. call.add(threadLocal.newSymNode)
  272. proc wrapProcForSpawn*(g: ModuleGraph; owner: PSym; spawnExpr: PNode; retType: PType;
  273. barrier, dest: PNode = nil): PNode =
  274. # if 'barrier' != nil, then it is in a 'parallel' section and we
  275. # generate quite different code
  276. let n = spawnExpr[^2]
  277. let spawnKind = spawnResult(retType, barrier!=nil)
  278. case spawnKind
  279. of srVoid:
  280. internalAssert g.config, dest == nil
  281. result = newNodeI(nkStmtList, n.info)
  282. of srFlowVar:
  283. internalAssert g.config, dest == nil
  284. result = newNodeIT(nkStmtListExpr, n.info, retType)
  285. of srByVar:
  286. if dest == nil: localError(g.config, n.info, "'spawn' must not be discarded")
  287. result = newNodeI(nkStmtList, n.info)
  288. if n.kind notin nkCallKinds:
  289. localError(g.config, n.info, "'spawn' takes a call expression; got " & $n)
  290. return
  291. if optThreadAnalysis in g.config.globalOptions:
  292. if {tfThread, tfNoSideEffect} * n[0].typ.flags == {}:
  293. localError(g.config, n.info, "'spawn' takes a GC safe call expression")
  294. var fn = n[0]
  295. let
  296. name = (if fn.kind == nkSym: fn.sym.name.s else: genPrefix) & "Wrapper"
  297. wrapperProc = newSym(skProc, getIdent(g.cache, name), owner, fn.info, g.config.options)
  298. threadParam = newSym(skParam, getIdent(g.cache, "thread"), wrapperProc, n.info, g.config.options)
  299. argsParam = newSym(skParam, getIdent(g.cache, "args"), wrapperProc, n.info, g.config.options)
  300. wrapperProc.flags.incl sfInjectDestructors
  301. block:
  302. let ptrType = getSysType(g, n.info, tyPointer)
  303. threadParam.typ = ptrType
  304. argsParam.typ = ptrType
  305. argsParam.position = 1
  306. var objType = createObj(g, owner, n.info)
  307. incl(objType.flags, tfFinal)
  308. let castExpr = createCastExpr(argsParam, objType)
  309. var scratchObj = newSym(skVar, getIdent(g.cache, "scratch"), owner, n.info, g.config.options)
  310. block:
  311. scratchObj.typ = objType
  312. incl(scratchObj.flags, sfFromGeneric)
  313. var varSectionB = newNodeI(nkVarSection, n.info)
  314. varSectionB.addVar(scratchObj.newSymNode)
  315. result.add varSectionB
  316. var call = newNodeIT(nkCall, n.info, n.typ)
  317. # templates and macros are in fact valid here due to the nature of
  318. # the transformation:
  319. if fn.kind == nkClosure or (fn.typ != nil and fn.typ.callConv == ccClosure):
  320. localError(g.config, n.info, "closure in spawn environment is not allowed")
  321. if not (fn.kind == nkSym and fn.sym.kind in {skProc, skTemplate, skMacro,
  322. skFunc, skMethod, skConverter}):
  323. # for indirect calls we pass the function pointer in the scratchObj
  324. var argType = n[0].typ.skipTypes(abstractInst)
  325. var field = newSym(skField, getIdent(g.cache, "fn"), owner, n.info, g.config.options)
  326. field.typ = argType
  327. objType.addField(field, g.cache)
  328. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[0])
  329. fn = indirectAccess(castExpr, field, n.info)
  330. elif fn.kind == nkSym and fn.sym.kind == skIterator:
  331. localError(g.config, n.info, "iterator in spawn environment is not allowed")
  332. elif fn.typ.callConv == ccClosure:
  333. localError(g.config, n.info, "closure in spawn environment is not allowed")
  334. call.add(fn)
  335. var varSection = newNodeI(nkVarSection, n.info)
  336. var varInit = newNodeI(nkStmtList, n.info)
  337. if barrier.isNil:
  338. setupArgsForConcurrency(g, n, objType, wrapperProc, scratchObj, castExpr, call,
  339. varSection, varInit, result)
  340. else:
  341. setupArgsForParallelism(g, n, objType, wrapperProc, scratchObj, castExpr, call,
  342. varSection, varInit, result)
  343. var barrierAsExpr: PNode = nil
  344. if barrier != nil:
  345. let typ = newType(tyPtr, owner)
  346. typ.rawAddSon(magicsys.getCompilerProc(g, "Barrier").typ)
  347. var field = newSym(skField, getIdent(g.cache, "barrier"), owner, n.info, g.config.options)
  348. field.typ = typ
  349. objType.addField(field, g.cache)
  350. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), barrier)
  351. barrierAsExpr = indirectAccess(castExpr, field, n.info)
  352. var fvField, fvAsExpr: PNode = nil
  353. if spawnKind == srFlowVar:
  354. var field = newSym(skField, getIdent(g.cache, "fv"), owner, n.info, g.config.options)
  355. field.typ = retType
  356. objType.addField(field, g.cache)
  357. fvField = newDotExpr(scratchObj, field)
  358. fvAsExpr = indirectAccess(castExpr, field, n.info)
  359. # create flowVar:
  360. result.add newFastAsgnStmt(fvField, callProc(spawnExpr[^1]))
  361. if barrier == nil:
  362. result.add callCodegenProc(g, "nimFlowVarCreateSemaphore", fvField.info,
  363. fvField)
  364. elif spawnKind == srByVar:
  365. var field = newSym(skField, getIdent(g.cache, "fv"), owner, n.info, g.config.options)
  366. field.typ = newType(tyPtr, objType.owner)
  367. field.typ.rawAddSon(retType)
  368. objType.addField(field, g.cache)
  369. fvAsExpr = indirectAccess(castExpr, field, n.info)
  370. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), genAddrOf(dest))
  371. createTypeBoundOps(g, nil, objType, n.info)
  372. createWrapperProc(g, fn, threadParam, argsParam,
  373. varSection, varInit, call,
  374. barrierAsExpr, fvAsExpr, spawnKind, wrapperProc)
  375. result.add callCodegenProc(g, "nimSpawn" & $spawnExpr.len, wrapperProc.info,
  376. wrapperProc.newSymNode, genAddrOf(scratchObj.newSymNode), nil, spawnExpr)
  377. if spawnKind == srFlowVar: result.add fvField