spawn.nim 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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; idgen: IdGenerator; owner: PSym; typ: PType;
  49. v: PNode; useShallowCopy=false): PSym =
  50. result = newSym(skTemp, getIdent(g.cache, genPrefix), nextSymId idgen, 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. idgen: IdGenerator;
  98. spawnKind: TSpawnResult, result: PSym) =
  99. var body = newNodeI(nkStmtList, f.info)
  100. var threadLocalBarrier: PSym
  101. if barrier != nil:
  102. var varSection2 = newNodeI(nkVarSection, barrier.info)
  103. threadLocalBarrier = addLocalVar(g, varSection2, nil, idgen, result,
  104. barrier.typ, barrier)
  105. body.add varSection2
  106. body.add callCodegenProc(g, "barrierEnter", threadLocalBarrier.info,
  107. threadLocalBarrier.newSymNode)
  108. var threadLocalProm: PSym
  109. if spawnKind == srByVar:
  110. threadLocalProm = addLocalVar(g, varSection, nil, idgen, result, fv.typ, fv)
  111. elif fv != nil:
  112. internalAssert g.config, fv.typ.kind == tyGenericInst
  113. threadLocalProm = addLocalVar(g, varSection, nil, idgen, result, fv.typ, fv)
  114. body.add varSection
  115. body.add varInit
  116. if fv != nil and spawnKind != srByVar:
  117. # generate:
  118. # fv.owner = threadParam
  119. body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
  120. "owner", fv.info, g.cache), threadParam.newSymNode)
  121. body.add callCodegenProc(g, "nimArgsPassingDone", threadParam.info,
  122. threadParam.newSymNode)
  123. if spawnKind == srByVar:
  124. body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call)
  125. elif fv != nil:
  126. let fk = flowVarKind(g.config, fv.typ[1])
  127. if fk == fvInvalid:
  128. localError(g.config, f.info, "cannot create a flowVar of type: " &
  129. typeToString(fv.typ[1]))
  130. body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode,
  131. if fk == fvGC: "data" else: "blob", fv.info, g.cache), call)
  132. if fk == fvGC:
  133. let incRefCall = newNodeI(nkCall, fv.info, 2)
  134. incRefCall[0] = newSymNode(getSysMagic(g, fv.info, "GCref", mGCref))
  135. incRefCall[1] = indirectAccess(threadLocalProm.newSymNode,
  136. "data", fv.info, g.cache)
  137. body.add incRefCall
  138. if barrier == nil:
  139. # by now 'fv' is shared and thus might have beeen overwritten! we need
  140. # to use the thread-local view instead:
  141. body.add callCodegenProc(g, "nimFlowVarSignal", threadLocalProm.info,
  142. threadLocalProm.newSymNode)
  143. else:
  144. body.add call
  145. if barrier != nil:
  146. body.add callCodegenProc(g, "barrierLeave", threadLocalBarrier.info,
  147. threadLocalBarrier.newSymNode)
  148. var params = newNodeI(nkFormalParams, f.info)
  149. params.add newNodeI(nkEmpty, f.info)
  150. params.add threadParam.newSymNode
  151. params.add argsParam.newSymNode
  152. var t = newType(tyProc, nextTypeId idgen, threadParam.owner)
  153. t.rawAddSon nil
  154. t.rawAddSon threadParam.typ
  155. t.rawAddSon argsParam.typ
  156. t.n = newNodeI(nkFormalParams, f.info)
  157. t.n.add newNodeI(nkEffectList, f.info)
  158. t.n.add threadParam.newSymNode
  159. t.n.add argsParam.newSymNode
  160. let emptyNode = newNodeI(nkEmpty, f.info)
  161. result.ast = newProcNode(nkProcDef, f.info, body = body,
  162. params = params, name = newSymNode(result), pattern = emptyNode,
  163. genericParams = emptyNode, pragmas = emptyNode,
  164. exceptions = emptyNode)
  165. result.typ = t
  166. proc createCastExpr(argsParam: PSym; objType: PType; idgen: IdGenerator): PNode =
  167. result = newNodeI(nkCast, argsParam.info)
  168. result.add newNodeI(nkEmpty, argsParam.info)
  169. result.add newSymNode(argsParam)
  170. result.typ = newType(tyPtr, nextTypeId idgen, objType.owner)
  171. result.typ.rawAddSon(objType)
  172. template checkMagicProcs(g: ModuleGraph, n: PNode, formal: PNode) =
  173. if (formal.typ.kind == tyVarargs and formal.typ[0].kind in {tyTyped, tyUntyped}) or
  174. formal.typ.kind in {tyTyped, tyUntyped}:
  175. localError(g.config, n.info, "'spawn'ed function cannot have a 'typed' or 'untyped' parameter")
  176. proc setupArgsForConcurrency(g: ModuleGraph; n: PNode; objType: PType;
  177. idgen: IdGenerator; owner: PSym; scratchObj: PSym,
  178. castExpr, call,
  179. varSection, varInit, result: PNode) =
  180. let formals = n[0].typ.n
  181. let tmpName = getIdent(g.cache, genPrefix)
  182. for i in 1..<n.len:
  183. # we pick n's type here, which hopefully is 'tyArray' and not
  184. # 'tyOpenArray':
  185. var argType = n[i].typ.skipTypes(abstractInst)
  186. if i < formals.len:
  187. if formals[i].typ.kind in {tyVar, tyLent}:
  188. localError(g.config, n[i].info, "'spawn'ed function cannot have a 'var' parameter")
  189. checkMagicProcs(g, n[i], formals[i])
  190. if formals[i].typ.kind in {tyTypeDesc, tyStatic}:
  191. continue
  192. #elif containsTyRef(argType):
  193. # localError(n[i].info, "'spawn'ed function cannot refer to 'ref'/closure")
  194. let fieldname = if i < formals.len: formals[i].sym.name else: tmpName
  195. var field = newSym(skField, fieldname, nextSymId idgen, objType.owner, n.info, g.config.options)
  196. field.typ = argType
  197. discard objType.addField(field, g.cache, idgen)
  198. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[i])
  199. let temp = addLocalVar(g, varSection, varInit, idgen, owner, argType,
  200. indirectAccess(castExpr, field, n.info))
  201. call.add(newSymNode(temp))
  202. proc setupArgsForParallelism(g: ModuleGraph; n: PNode; objType: PType;
  203. idgen: IdGenerator;
  204. owner: PSym; scratchObj: PSym;
  205. castExpr, call,
  206. varSection, varInit, result: PNode) =
  207. let formals = n[0].typ.n
  208. let tmpName = getIdent(g.cache, genPrefix)
  209. # we need to copy the foreign scratch object fields into local variables
  210. # for correctness: These are called 'threadLocal' here.
  211. for i in 1..<n.len:
  212. let n = n[i]
  213. if i < formals.len and formals[i].typ.kind in {tyStatic, tyTypeDesc}:
  214. continue
  215. checkMagicProcs(g, n, formals[i])
  216. let argType = skipTypes(if i < formals.len: formals[i].typ else: n.typ,
  217. abstractInst)
  218. #if containsTyRef(argType):
  219. # localError(n.info, "'spawn'ed function cannot refer to 'ref'/closure")
  220. let fieldname = if i < formals.len: formals[i].sym.name else: tmpName
  221. var field = newSym(skField, fieldname, nextSymId idgen, objType.owner, n.info, g.config.options)
  222. if argType.kind in {tyVarargs, tyOpenArray}:
  223. # important special case: we always create a zero-copy slice:
  224. let slice = newNodeI(nkCall, n.info, 4)
  225. slice.typ = n.typ
  226. slice[0] = newSymNode(createMagic(g, idgen, "slice", mSlice))
  227. slice[0].typ = getSysType(g, n.info, tyInt) # fake type
  228. var fieldB = newSym(skField, tmpName, nextSymId idgen, objType.owner, n.info, g.config.options)
  229. fieldB.typ = getSysType(g, n.info, tyInt)
  230. discard objType.addField(fieldB, g.cache, idgen)
  231. if getMagic(n) == mSlice:
  232. let a = genAddrOf(n[1], idgen)
  233. field.typ = a.typ
  234. discard objType.addField(field, g.cache, idgen)
  235. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  236. var fieldA = newSym(skField, tmpName, nextSymId idgen, objType.owner, n.info, g.config.options)
  237. fieldA.typ = getSysType(g, n.info, tyInt)
  238. discard objType.addField(fieldA, g.cache, idgen)
  239. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldA), n[2])
  240. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), n[3])
  241. let threadLocal = addLocalVar(g, varSection, nil, idgen, owner, fieldA.typ,
  242. indirectAccess(castExpr, fieldA, n.info),
  243. useShallowCopy=true)
  244. slice[2] = threadLocal.newSymNode
  245. else:
  246. let a = genAddrOf(n, idgen)
  247. field.typ = a.typ
  248. discard objType.addField(field, g.cache, idgen)
  249. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  250. result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), genHigh(g, n))
  251. slice[2] = newIntLit(g, n.info, 0)
  252. # the array itself does not need to go through a thread local variable:
  253. slice[1] = genDeref(indirectAccess(castExpr, field, n.info))
  254. let threadLocal = addLocalVar(g, varSection, nil, idgen, owner, fieldB.typ,
  255. indirectAccess(castExpr, fieldB, n.info),
  256. useShallowCopy=true)
  257. slice[3] = threadLocal.newSymNode
  258. call.add slice
  259. elif (let size = computeSize(g.config, argType); size < 0 or size > 16) and
  260. n.getRoot != nil:
  261. # it is more efficient to pass a pointer instead:
  262. let a = genAddrOf(n, idgen)
  263. field.typ = a.typ
  264. discard objType.addField(field, g.cache, idgen)
  265. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a)
  266. let threadLocal = addLocalVar(g, varSection, nil, idgen, owner, field.typ,
  267. indirectAccess(castExpr, field, n.info),
  268. useShallowCopy=true)
  269. call.add(genDeref(threadLocal.newSymNode))
  270. else:
  271. # boring case
  272. field.typ = argType
  273. discard objType.addField(field, g.cache, idgen)
  274. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n)
  275. let threadLocal = addLocalVar(g, varSection, varInit,
  276. idgen, owner, field.typ,
  277. indirectAccess(castExpr, field, n.info),
  278. useShallowCopy=true)
  279. call.add(threadLocal.newSymNode)
  280. proc wrapProcForSpawn*(g: ModuleGraph; idgen: IdGenerator; owner: PSym; spawnExpr: PNode; retType: PType;
  281. barrier, dest: PNode = nil): PNode =
  282. # if 'barrier' != nil, then it is in a 'parallel' section and we
  283. # generate quite different code
  284. let n = spawnExpr[^2]
  285. let spawnKind = spawnResult(retType, barrier!=nil)
  286. case spawnKind
  287. of srVoid:
  288. internalAssert g.config, dest == nil
  289. result = newNodeI(nkStmtList, n.info)
  290. of srFlowVar:
  291. internalAssert g.config, dest == nil
  292. result = newNodeIT(nkStmtListExpr, n.info, retType)
  293. of srByVar:
  294. if dest == nil: localError(g.config, n.info, "'spawn' must not be discarded")
  295. result = newNodeI(nkStmtList, n.info)
  296. if n.kind notin nkCallKinds:
  297. localError(g.config, n.info, "'spawn' takes a call expression; got: " & $n)
  298. return
  299. if optThreadAnalysis in g.config.globalOptions:
  300. if {tfThread, tfNoSideEffect} * n[0].typ.flags == {}:
  301. localError(g.config, n.info, "'spawn' takes a GC safe call expression")
  302. var fn = n[0]
  303. let
  304. name = (if fn.kind == nkSym: fn.sym.name.s else: genPrefix) & "Wrapper"
  305. wrapperProc = newSym(skProc, getIdent(g.cache, name), nextSymId idgen, owner, fn.info, g.config.options)
  306. threadParam = newSym(skParam, getIdent(g.cache, "thread"), nextSymId idgen, wrapperProc, n.info, g.config.options)
  307. argsParam = newSym(skParam, getIdent(g.cache, "args"), nextSymId idgen, wrapperProc, n.info, g.config.options)
  308. wrapperProc.flags.incl sfInjectDestructors
  309. block:
  310. let ptrType = getSysType(g, n.info, tyPointer)
  311. threadParam.typ = ptrType
  312. argsParam.typ = ptrType
  313. argsParam.position = 1
  314. var objType = createObj(g, idgen, owner, n.info)
  315. incl(objType.flags, tfFinal)
  316. let castExpr = createCastExpr(argsParam, objType, idgen)
  317. var scratchObj = newSym(skVar, getIdent(g.cache, "scratch"), nextSymId idgen, owner, n.info, g.config.options)
  318. block:
  319. scratchObj.typ = objType
  320. incl(scratchObj.flags, sfFromGeneric)
  321. var varSectionB = newNodeI(nkVarSection, n.info)
  322. varSectionB.addVar(scratchObj.newSymNode)
  323. result.add varSectionB
  324. var call = newNodeIT(nkCall, n.info, n.typ)
  325. # templates and macros are in fact valid here due to the nature of
  326. # the transformation:
  327. if fn.kind == nkClosure or (fn.typ != nil and fn.typ.callConv == ccClosure):
  328. localError(g.config, n.info, "closure in spawn environment is not allowed")
  329. if not (fn.kind == nkSym and fn.sym.kind in {skProc, skTemplate, skMacro,
  330. skFunc, skMethod, skConverter}):
  331. # for indirect calls we pass the function pointer in the scratchObj
  332. var argType = n[0].typ.skipTypes(abstractInst)
  333. var field = newSym(skField, getIdent(g.cache, "fn"), nextSymId idgen, owner, n.info, g.config.options)
  334. field.typ = argType
  335. discard objType.addField(field, g.cache, idgen)
  336. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[0])
  337. fn = indirectAccess(castExpr, field, n.info)
  338. elif fn.kind == nkSym and fn.sym.kind == skIterator:
  339. localError(g.config, n.info, "iterator in spawn environment is not allowed")
  340. call.add(fn)
  341. var varSection = newNodeI(nkVarSection, n.info)
  342. var varInit = newNodeI(nkStmtList, n.info)
  343. if barrier.isNil:
  344. setupArgsForConcurrency(g, n, objType, idgen, wrapperProc, scratchObj, castExpr, call,
  345. varSection, varInit, result)
  346. else:
  347. setupArgsForParallelism(g, n, objType, idgen, wrapperProc, scratchObj, castExpr, call,
  348. varSection, varInit, result)
  349. var barrierAsExpr: PNode = nil
  350. if barrier != nil:
  351. let typ = newType(tyPtr, nextTypeId idgen, owner)
  352. typ.rawAddSon(magicsys.getCompilerProc(g, "Barrier").typ)
  353. var field = newSym(skField, getIdent(g.cache, "barrier"), nextSymId idgen, owner, n.info, g.config.options)
  354. field.typ = typ
  355. discard objType.addField(field, g.cache, idgen)
  356. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), barrier)
  357. barrierAsExpr = indirectAccess(castExpr, field, n.info)
  358. var fvField, fvAsExpr: PNode = nil
  359. if spawnKind == srFlowVar:
  360. var field = newSym(skField, getIdent(g.cache, "fv"), nextSymId idgen, owner, n.info, g.config.options)
  361. field.typ = retType
  362. discard objType.addField(field, g.cache, idgen)
  363. fvField = newDotExpr(scratchObj, field)
  364. fvAsExpr = indirectAccess(castExpr, field, n.info)
  365. # create flowVar:
  366. result.add newFastAsgnStmt(fvField, callProc(spawnExpr[^1]))
  367. if barrier == nil:
  368. result.add callCodegenProc(g, "nimFlowVarCreateSemaphore", fvField.info, fvField)
  369. elif spawnKind == srByVar:
  370. var field = newSym(skField, getIdent(g.cache, "fv"), nextSymId idgen, owner, n.info, g.config.options)
  371. field.typ = newType(tyPtr, nextTypeId idgen, objType.owner)
  372. field.typ.rawAddSon(retType)
  373. discard objType.addField(field, g.cache, idgen)
  374. fvAsExpr = indirectAccess(castExpr, field, n.info)
  375. result.add newFastAsgnStmt(newDotExpr(scratchObj, field), genAddrOf(dest, idgen))
  376. createTypeBoundOps(g, nil, objType, n.info, idgen)
  377. createWrapperProc(g, fn, threadParam, argsParam,
  378. varSection, varInit, call,
  379. barrierAsExpr, fvAsExpr, idgen, spawnKind, wrapperProc)
  380. result.add callCodegenProc(g, "nimSpawn" & $spawnExpr.len, wrapperProc.info,
  381. wrapperProc.newSymNode, genAddrOf(scratchObj.newSymNode, idgen), nil, spawnExpr)
  382. if spawnKind == srFlowVar: result.add fvField