ccgcalls.nim 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925
  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. #
  10. # included from cgen.nim
  11. proc canRaiseDisp(p: BProc; n: PNode): bool =
  12. # we assume things like sysFatal cannot raise themselves
  13. if n.kind == nkSym and {sfNeverRaises, sfImportc, sfCompilerProc} * n.sym.flags != {}:
  14. result = false
  15. elif optPanics in p.config.globalOptions or
  16. (n.kind == nkSym and sfSystemModule in getModule(n.sym).flags and
  17. sfSystemRaisesDefect notin n.sym.flags):
  18. # we know we can be strict:
  19. result = canRaise(n)
  20. else:
  21. # we have to be *very* conservative:
  22. result = canRaiseConservative(n)
  23. proc preventNrvo(p: BProc; dest, le, ri: PNode): bool =
  24. proc locationEscapes(p: BProc; le: PNode; inTryStmt: bool): bool =
  25. result = false
  26. var n = le
  27. while true:
  28. # do NOT follow nkHiddenDeref here!
  29. case n.kind
  30. of nkSym:
  31. # we don't own the location so it escapes:
  32. if n.sym.owner != p.prc:
  33. return true
  34. elif inTryStmt and sfUsedInFinallyOrExcept in n.sym.flags:
  35. # it is also an observable store if the location is used
  36. # in 'except' or 'finally'
  37. return true
  38. return false
  39. of nkDotExpr, nkBracketExpr, nkObjUpConv, nkObjDownConv,
  40. nkCheckedFieldExpr:
  41. n = n[0]
  42. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  43. n = n[1]
  44. else:
  45. # cannot analyse the location; assume the worst
  46. return true
  47. result = false
  48. if le != nil:
  49. for i in 1..<ri.len:
  50. let r = ri[i]
  51. if isPartOf(le, r) != arNo: return true
  52. # we use the weaker 'canRaise' here in order to prevent too many
  53. # annoying warnings, see #14514
  54. if canRaise(ri[0]) and
  55. locationEscapes(p, le, p.nestedTryStmts.len > 0):
  56. message(p.config, le.info, warnObservableStores, $le)
  57. # bug #19613 prevent dangerous aliasing too:
  58. if dest != nil and dest != le:
  59. for i in 1..<ri.len:
  60. let r = ri[i]
  61. if isPartOf(dest, r) != arNo: return true
  62. proc hasNoInit(call: PNode): bool {.inline.} =
  63. result = call[0].kind == nkSym and sfNoInit in call[0].sym.flags
  64. proc isHarmlessStore(p: BProc; canRaise: bool; d: TLoc): bool =
  65. if d.k in {locTemp, locNone} or not canRaise:
  66. result = true
  67. elif d.k == locLocalVar and p.withinTryWithExcept == 0:
  68. # we cannot observe a store to a local variable if the current proc
  69. # has no error handler:
  70. result = true
  71. else:
  72. result = false
  73. proc cleanupTemp(p: BProc; returnType: PType, tmp: TLoc): bool =
  74. if returnType.kind in {tyVar, tyLent}:
  75. # we don't need to worry about var/lent return types
  76. result = false
  77. elif hasDestructor(returnType) and getAttachedOp(p.module.g.graph, returnType, attachedDestructor) != nil:
  78. let dtor = getAttachedOp(p.module.g.graph, returnType, attachedDestructor)
  79. var op = initLocExpr(p, newSymNode(dtor))
  80. var callee = rdLoc(op)
  81. let destroyArg =
  82. if dtor.typ.firstParamType.kind == tyVar:
  83. cAddr(rdLoc(tmp))
  84. else:
  85. rdLoc(tmp)
  86. let destroy = cCall(callee, destroyArg)
  87. raiseExitCleanup(p, destroy)
  88. result = true
  89. else:
  90. result = false
  91. proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
  92. result: var Builder, call: var CallBuilder) =
  93. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  94. genLineDir(p, ri)
  95. # getUniqueType() is too expensive here:
  96. var typ = skipTypes(ri[0].typ, abstractInst)
  97. if typ.returnType != nil:
  98. var flags: TAssignmentFlags = {}
  99. if typ.returnType.kind in {tyOpenArray, tyVarargs}:
  100. # perhaps generate no temp if the call doesn't have side effects
  101. flags.incl needTempForOpenArray
  102. if isInvalidReturnType(p.config, typ):
  103. # beware of 'result = p(result)'. We may need to allocate a temporary:
  104. if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
  105. # Great, we can use 'd':
  106. if d.k == locNone: d = getTemp(p, typ.returnType, needsInit=true)
  107. elif d.k notin {locTemp} and not hasNoInit(ri):
  108. # reset before pass as 'result' var:
  109. discard "resetLoc(p, d)"
  110. let rad = addrLoc(p.config, d)
  111. result.addArgument(call):
  112. result.add(rad)
  113. result.finishCallBuilder(call)
  114. p.s(cpsStmts).addStmt():
  115. p.s(cpsStmts).add(extract(result))
  116. else:
  117. var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
  118. let ratmp = addrLoc(p.config, tmp)
  119. result.addArgument(call):
  120. result.add(ratmp)
  121. result.finishCallBuilder(call)
  122. p.s(cpsStmts).addStmt():
  123. p.s(cpsStmts).add(extract(result))
  124. genAssignment(p, d, tmp, {}) # no need for deep copying
  125. if canRaise: raiseExit(p)
  126. else:
  127. result.finishCallBuilder(call)
  128. if p.module.compileToCpp:
  129. if lfSingleUse in d.flags:
  130. # do not generate spurious temporaries for C++! For C we're better off
  131. # with them to prevent undefined behaviour and because the codegen
  132. # is free to emit expressions multiple times!
  133. d.k = locCall
  134. d.snippet = extract(result)
  135. excl d.flags, lfSingleUse
  136. else:
  137. if d.k == locNone and p.splitDecls == 0:
  138. d = getTempCpp(p, typ.returnType, extract(result))
  139. else:
  140. if d.k == locNone: d = getTemp(p, typ.returnType)
  141. var list = initLoc(locCall, d.lode, OnUnknown)
  142. list.snippet = extract(result)
  143. genAssignment(p, d, list, {needAssignCall}) # no need for deep copying
  144. if canRaise: raiseExit(p)
  145. elif isHarmlessStore(p, canRaise, d):
  146. var useTemp = false
  147. if d.k == locNone:
  148. useTemp = true
  149. d = getTemp(p, typ.returnType)
  150. assert(d.t != nil) # generate an assignment to d:
  151. var list = initLoc(locCall, d.lode, OnUnknown)
  152. list.snippet = extract(result)
  153. genAssignment(p, d, list, flags+{needAssignCall}) # no need for deep copying
  154. if canRaise:
  155. if not (useTemp and cleanupTemp(p, typ.returnType, d)):
  156. raiseExit(p)
  157. else:
  158. var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
  159. var list = initLoc(locCall, d.lode, OnUnknown)
  160. list.snippet = extract(result)
  161. genAssignment(p, tmp, list, flags+{needAssignCall}) # no need for deep copying
  162. if canRaise:
  163. if not cleanupTemp(p, typ.returnType, tmp):
  164. raiseExit(p)
  165. genAssignment(p, d, tmp, {})
  166. else:
  167. finishCallBuilder(result, call)
  168. p.s(cpsStmts).addStmt():
  169. p.s(cpsStmts).add(extract(result))
  170. if canRaise: raiseExit(p)
  171. proc genBoundsCheck(p: BProc; arr, a, b: TLoc; arrTyp: PType)
  172. proc reifiedOpenArray(n: PNode): bool {.inline.} =
  173. var x = n
  174. while true:
  175. case x.kind
  176. of {nkAddr, nkHiddenAddr, nkHiddenDeref}:
  177. x = x[0]
  178. of nkHiddenStdConv:
  179. x = x[1]
  180. else:
  181. break
  182. if x.kind == nkSym and x.sym.kind == skParam:
  183. result = false
  184. else:
  185. result = true
  186. proc genOpenArraySlice(p: BProc; q: PNode; formalType, destType: PType; prepareForMutation = false): (Rope, Rope) =
  187. var a = initLocExpr(p, q[1])
  188. var b = initLocExpr(p, q[2])
  189. var c = initLocExpr(p, q[3])
  190. # bug #23321: In the function mapType, ptrs (tyPtr, tyVar, tyLent, tyRef)
  191. # are mapped into ctPtrToArray, the dereference of which is skipped
  192. # in the `genDeref`. We need to skip these ptrs here
  193. let ty = skipTypes(a.t, abstractVar+{tyPtr, tyRef})
  194. # but first produce the required index checks:
  195. if optBoundsCheck in p.options:
  196. genBoundsCheck(p, a, b, c, ty)
  197. if prepareForMutation:
  198. let bra = byRefLoc(p, a)
  199. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimPrepareStrMutationV2"),
  200. bra)
  201. let dest = getTypeDesc(p.module, destType)
  202. let ra = rdLoc(a)
  203. let rb = rdLoc(b)
  204. let rc = rdLoc(c)
  205. let lengthExpr = cOp(Add, NimInt, cOp(Sub, NimInt, rc, rb), cIntValue(1))
  206. case ty.kind
  207. of tyArray:
  208. let first = toInt64(firstOrd(p.config, ty))
  209. if first == 0:
  210. result = (cCast(ptrType(dest), cOp(Add, NimInt, ra, rb)), lengthExpr)
  211. else:
  212. let lit = cIntLiteral(first)
  213. result = (cCast(ptrType(dest), cOp(Add, NimInt, ra, cOp(Sub, NimInt, rb, lit))), lengthExpr)
  214. of tyOpenArray, tyVarargs:
  215. let data = if reifiedOpenArray(q[1]): dotField(ra, "Field0") else: ra
  216. result = (cCast(ptrType(dest), cOp(Add, NimInt, data, rb)), lengthExpr)
  217. of tyUncheckedArray, tyCstring:
  218. result = (cCast(ptrType(dest), cOp(Add, NimInt, ra, rb)), lengthExpr)
  219. of tyString, tySequence:
  220. let atyp = skipTypes(a.t, abstractInst)
  221. if formalType.skipTypes(abstractInst).kind in {tyVar} and atyp.kind == tyString and
  222. optSeqDestructors in p.config.globalOptions:
  223. let bra = byRefLoc(p, a)
  224. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimPrepareStrMutationV2"),
  225. bra)
  226. var val: Snippet
  227. if atyp.kind in {tyVar} and not compileToCpp(p.module):
  228. val = cDeref(ra)
  229. else:
  230. val = ra
  231. result = (
  232. cIfExpr(dataFieldAccessor(p, val),
  233. cCast(ptrType(dest), cOp(Add, NimInt, dataField(p, val), rb)),
  234. NimNil),
  235. lengthExpr)
  236. else:
  237. result = ("", "")
  238. internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  239. proc openArrayLoc(p: BProc, formalType: PType, n: PNode; result: var Builder) =
  240. var q = skipConv(n)
  241. var skipped = false
  242. while q.kind == nkStmtListExpr and q.len > 0:
  243. skipped = true
  244. q = q.lastSon
  245. if getMagic(q) == mSlice:
  246. # magic: pass slice to openArray:
  247. if skipped:
  248. q = skipConv(n)
  249. while q.kind == nkStmtListExpr and q.len > 0:
  250. for i in 0..<q.len-1:
  251. genStmts(p, q[i])
  252. q = q.lastSon
  253. let (x, y) = genOpenArraySlice(p, q, formalType, n.typ.elementType)
  254. result.add(x)
  255. result.addArgumentSeparator()
  256. result.add(y)
  257. else:
  258. var a = initLocExpr(p, if n.kind == nkHiddenStdConv: n[1] else: n)
  259. case skipTypes(a.t, abstractVar+{tyStatic}).kind
  260. of tyOpenArray, tyVarargs:
  261. let ra = rdLoc(a)
  262. if reifiedOpenArray(n):
  263. if a.t.kind in {tyVar, tyLent}:
  264. result.add(derefField(ra, "Field0"))
  265. result.addArgumentSeparator()
  266. result.add(derefField(ra, "Field1"))
  267. else:
  268. result.add(dotField(ra, "Field0"))
  269. result.addArgumentSeparator()
  270. result.add(dotField(ra, "Field1"))
  271. else:
  272. result.add(ra)
  273. result.addArgumentSeparator()
  274. result.add(ra & "Len_0")
  275. of tyString, tySequence:
  276. let ntyp = skipTypes(n.typ, abstractInst)
  277. if formalType.skipTypes(abstractInst).kind in {tyVar} and ntyp.kind == tyString and
  278. optSeqDestructors in p.config.globalOptions:
  279. let bra = byRefLoc(p, a)
  280. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimPrepareStrMutationV2"),
  281. bra)
  282. if ntyp.kind in {tyVar} and not compileToCpp(p.module):
  283. let ra = a.rdLoc
  284. var t = TLoc(snippet: cDeref(ra))
  285. let lt = lenExpr(p, t)
  286. result.add(cIfExpr(dataFieldAccessor(p, t.snippet), dataField(p, t.snippet), NimNil))
  287. result.addArgumentSeparator()
  288. result.add(lt)
  289. else:
  290. let ra = a.rdLoc
  291. let la = lenExpr(p, a)
  292. result.add(cIfExpr(dataFieldAccessor(p, ra), dataField(p, ra), NimNil))
  293. result.addArgumentSeparator()
  294. result.add(la)
  295. of tyArray:
  296. let ra = rdLoc(a)
  297. result.add(ra)
  298. result.addArgumentSeparator()
  299. result.addIntValue(lengthOrd(p.config, a.t))
  300. of tyPtr, tyRef:
  301. case elementType(a.t).kind
  302. of tyString, tySequence:
  303. let ra = a.rdLoc
  304. var t = TLoc(snippet: cDeref(ra))
  305. let lt = lenExpr(p, t)
  306. result.add(cIfExpr(dataFieldAccessor(p, t.snippet), dataField(p, t.snippet), NimNil))
  307. result.addArgumentSeparator()
  308. result.add(lt)
  309. of tyArray:
  310. let ra = rdLoc(a)
  311. result.add(ra)
  312. result.addArgumentSeparator()
  313. result.addIntValue(lengthOrd(p.config, elementType(a.t)))
  314. else:
  315. internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  316. else: internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  317. proc withTmpIfNeeded(p: BProc, a: TLoc, needsTmp: bool): TLoc =
  318. # Bug https://github.com/status-im/nimbus-eth2/issues/1549
  319. # Aliasing is preferred over stack overflows.
  320. # Also don't regress for non ARC-builds, too risky.
  321. if needsTmp and a.lode.typ != nil and p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc} and
  322. getSize(p.config, a.lode.typ) < 1024:
  323. result = getTemp(p, a.lode.typ, needsInit=false)
  324. genAssignment(p, result, a, {})
  325. else:
  326. result = a
  327. proc literalsNeedsTmp(p: BProc, a: TLoc): TLoc =
  328. result = getTemp(p, a.lode.typ, needsInit=false)
  329. genAssignment(p, result, a, {})
  330. proc genArgStringToCString(p: BProc, n: PNode; result: var Builder; needsTmp: bool) {.inline.} =
  331. var a = initLocExpr(p, n[0])
  332. let ra = withTmpIfNeeded(p, a, needsTmp).rdLoc
  333. result.addCall(cgsymValue(p.module, "nimToCStringConv"), ra)
  334. proc genArg(p: BProc, n: PNode, param: PSym; call: PNode; result: var Builder; needsTmp = false) =
  335. var a: TLoc
  336. if n.kind == nkStringToCString:
  337. genArgStringToCString(p, n, result, needsTmp)
  338. elif skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs}:
  339. var n = if n.kind != nkHiddenAddr: n else: n[0]
  340. openArrayLoc(p, param.typ, n, result)
  341. elif ccgIntroducedPtr(p.config, param, call[0].typ.returnType) and
  342. (optByRef notin param.options or not p.module.compileToCpp):
  343. a = initLocExpr(p, n)
  344. if n.kind in {nkCharLit..nkNilLit}:
  345. addAddrLoc(p.config, literalsNeedsTmp(p, a), result)
  346. else:
  347. addAddrLoc(p.config, withTmpIfNeeded(p, a, needsTmp), result)
  348. elif p.module.compileToCpp and param.typ.kind in {tyVar} and
  349. n.kind == nkHiddenAddr:
  350. # bug #23748: we need to introduce a temporary here. The expression type
  351. # will be a reference in C++ and we cannot create a temporary reference
  352. # variable. Thus, we create a temporary pointer variable instead.
  353. let needsIndirect = mapType(p.config, n[0].typ, mapTypeChooser(n[0]) == skParam) != ctArray
  354. if needsIndirect:
  355. n.typ() = n.typ.exactReplica
  356. n.typ.flags.incl tfVarIsPtr
  357. a = initLocExprSingleUse(p, n)
  358. a = withTmpIfNeeded(p, a, needsTmp)
  359. if needsIndirect: a.flags.incl lfIndirect
  360. # if the proc is 'importc'ed but not 'importcpp'ed then 'var T' still
  361. # means '*T'. See posix.nim for lots of examples that do that in the wild.
  362. let callee = call[0]
  363. if callee.kind == nkSym and
  364. {sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
  365. {lfHeader, lfNoDecl} * callee.sym.loc.flags != {} and
  366. needsIndirect:
  367. addAddrLoc(p.config, a, result)
  368. else:
  369. addRdLoc(a, result)
  370. else:
  371. a = initLocExprSingleUse(p, n)
  372. if param.typ.kind in {tyVar, tyPtr, tyRef, tySink}:
  373. let typ = skipTypes(param.typ, abstractPtrs)
  374. if not sameBackendTypePickyAliases(typ, n.typ.skipTypes(abstractPtrs)):
  375. a.snippet = cCast(getTypeDesc(p.module, param.typ), rdCharLoc(a))
  376. addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
  377. #assert result != nil
  378. proc genArgNoParam(p: BProc, n: PNode; result: var Builder; needsTmp = false) =
  379. var a: TLoc
  380. if n.kind == nkStringToCString:
  381. genArgStringToCString(p, n, result, needsTmp)
  382. else:
  383. a = initLocExprSingleUse(p, n)
  384. addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
  385. import aliasanalysis
  386. proc potentialAlias(n: PNode, potentialWrites: seq[PNode]): bool =
  387. result = false
  388. for p in potentialWrites:
  389. if p.aliases(n) != no or n.aliases(p) != no:
  390. return true
  391. proc skipTrivialIndirections(n: PNode): PNode =
  392. result = n
  393. while true:
  394. case result.kind
  395. of nkDerefExpr, nkHiddenDeref, nkAddr, nkHiddenAddr, nkObjDownConv, nkObjUpConv:
  396. result = result[0]
  397. of nkHiddenStdConv, nkHiddenSubConv:
  398. result = result[1]
  399. else: break
  400. proc getPotentialWrites(n: PNode; mutate: bool; result: var seq[PNode]) =
  401. case n.kind:
  402. of nkLiterals, nkIdent, nkFormalParams: discard
  403. of nkSym:
  404. if mutate: result.add n
  405. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  406. getPotentialWrites(n[0], true, result)
  407. getPotentialWrites(n[1], mutate, result)
  408. of nkAddr, nkHiddenAddr:
  409. getPotentialWrites(n[0], true, result)
  410. of nkBracketExpr, nkDotExpr, nkCheckedFieldExpr:
  411. getPotentialWrites(n[0], mutate, result)
  412. of nkCallKinds:
  413. case n.getMagic:
  414. of mIncl, mExcl, mInc, mDec, mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  415. mAddr, mNew, mNewFinalize, mWasMoved, mDestroy:
  416. getPotentialWrites(n[1], true, result)
  417. for i in 2..<n.len:
  418. getPotentialWrites(n[i], mutate, result)
  419. of mSwap:
  420. for i in 1..<n.len:
  421. getPotentialWrites(n[i], true, result)
  422. else:
  423. for i in 1..<n.len:
  424. getPotentialWrites(n[i], mutate, result)
  425. else:
  426. for s in n:
  427. getPotentialWrites(s, mutate, result)
  428. proc getPotentialReads(n: PNode; result: var seq[PNode]) =
  429. case n.kind:
  430. of nkLiterals, nkIdent, nkFormalParams: discard
  431. of nkSym: result.add n
  432. else:
  433. for s in n:
  434. getPotentialReads(s, result)
  435. proc genParams(p: BProc, ri: PNode, typ: PType; result: var Builder, argBuilder: var CallBuilder) =
  436. # We must generate temporaries in cases like #14396
  437. # to keep the strict Left-To-Right evaluation
  438. var needTmp = newSeq[bool](ri.len - 1)
  439. var potentialWrites: seq[PNode] = @[]
  440. for i in countdown(ri.len - 1, 1):
  441. if ri[i].skipTrivialIndirections.kind == nkSym:
  442. needTmp[i - 1] = potentialAlias(ri[i], potentialWrites)
  443. else:
  444. #if not ri[i].typ.isCompileTimeOnly:
  445. var potentialReads: seq[PNode] = @[]
  446. getPotentialReads(ri[i], potentialReads)
  447. for n in potentialReads:
  448. if not needTmp[i - 1]:
  449. needTmp[i - 1] = potentialAlias(n, potentialWrites)
  450. getPotentialWrites(ri[i], false, potentialWrites)
  451. when false:
  452. # this optimization is wrong, see bug #23748
  453. if ri[i].kind in {nkHiddenAddr, nkAddr}:
  454. # Optimization: don't use a temp, if we would only take the address anyway
  455. needTmp[i - 1] = false
  456. for i in 1..<ri.len:
  457. if i < typ.n.len:
  458. assert(typ.n[i].kind == nkSym)
  459. let paramType = typ.n[i]
  460. if not paramType.typ.isCompileTimeOnly:
  461. var arg = newBuilder("")
  462. genArg(p, ri[i], paramType.sym, ri, arg, needTmp[i-1])
  463. if arg.buf.len != 0:
  464. result.addArgument(argBuilder):
  465. result.add(extract(arg))
  466. else:
  467. var arg = newBuilder("")
  468. genArgNoParam(p, ri[i], arg, needTmp[i-1])
  469. if arg.buf.len != 0:
  470. result.addArgument(argBuilder):
  471. result.add(extract(arg))
  472. proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
  473. if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
  474. (sym.typ.callConv == ccInline or sym.owner.id == module.id):
  475. res = res & "_actual".rope
  476. proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  477. # this is a hotspot in the compiler
  478. var op = initLocExpr(p, ri[0])
  479. # getUniqueType() is too expensive here:
  480. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  481. assert(typ.kind == tyProc)
  482. var callee = rdLoc(op)
  483. if p.hcrOn and ri[0].kind == nkSym:
  484. callee.addActualSuffixForHCR(p.module.module, ri[0].sym)
  485. var res = newBuilder("")
  486. var call = initCallBuilder(res, callee)
  487. genParams(p, ri, typ, res, call)
  488. fixupCall(p, le, ri, d, res, call)
  489. proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
  490. template callProc(rp, params, pTyp: Snippet): Snippet =
  491. let e = dotField(rp, "ClE_0")
  492. let p = dotField(rp, "ClP_0")
  493. let eCall =
  494. # note `params` here is actually multiple params
  495. if params.len == 0:
  496. cCall(p, e)
  497. else:
  498. cCall(p, params, e)
  499. cIfExpr(e,
  500. eCall,
  501. cCall(cCast(pTyp, p), params))
  502. template callIter(rp, params: Snippet): Snippet =
  503. # we know the env exists
  504. let e = dotField(rp, "ClE_0")
  505. let p = dotField(rp, "ClP_0")
  506. # note `params` here is actually multiple params
  507. if params.len == 0:
  508. cCall(p, e)
  509. else:
  510. cCall(p, params, e)
  511. var op = initLocExpr(p, ri[0])
  512. # getUniqueType() is too expensive here:
  513. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  514. assert(typ.kind == tyProc)
  515. var params = newBuilder("")
  516. var argBuilder = default(CallBuilder) # not initCallBuilder, we just want the params
  517. genParams(p, ri, typ, params, argBuilder)
  518. template genCallPattern {.dirty.} =
  519. let rp = rdLoc(op)
  520. let pars = extract(params)
  521. p.s(cpsStmts).addStmt():
  522. if tfIterator in typ.flags:
  523. p.s(cpsStmts).add(callIter(rp, pars))
  524. else:
  525. p.s(cpsStmts).add(callProc(rp, pars, rawProc))
  526. let rawProc = getClosureType(p.module, typ, clHalf)
  527. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  528. if typ.returnType != nil:
  529. if isInvalidReturnType(p.config, typ):
  530. # beware of 'result = p(result)'. We may need to allocate a temporary:
  531. if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
  532. # Great, we can use 'd':
  533. if d.k == locNone:
  534. d = getTemp(p, typ.returnType, needsInit=true)
  535. elif d.k notin {locTemp} and not hasNoInit(ri):
  536. # reset before pass as 'result' var:
  537. discard "resetLoc(p, d)"
  538. params.addArgument(argBuilder):
  539. params.add(addrLoc(p.config, d))
  540. genCallPattern()
  541. if canRaise: raiseExit(p)
  542. else:
  543. var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
  544. params.addArgument(argBuilder):
  545. params.add(addrLoc(p.config, tmp))
  546. genCallPattern()
  547. if canRaise: raiseExit(p)
  548. genAssignment(p, d, tmp, {}) # no need for deep copying
  549. elif isHarmlessStore(p, canRaise, d):
  550. if d.k == locNone: d = getTemp(p, typ.returnType)
  551. assert(d.t != nil) # generate an assignment to d:
  552. var list: TLoc = initLoc(locCall, d.lode, OnUnknown)
  553. let rp = rdLoc(op)
  554. let pars = extract(params)
  555. if tfIterator in typ.flags:
  556. list.snippet = callIter(rp, pars)
  557. else:
  558. list.snippet = callProc(rp, pars, rawProc)
  559. genAssignment(p, d, list, {}) # no need for deep copying
  560. if canRaise: raiseExit(p)
  561. else:
  562. var tmp: TLoc = getTemp(p, typ.returnType)
  563. assert(d.t != nil) # generate an assignment to d:
  564. var list: TLoc = initLoc(locCall, d.lode, OnUnknown)
  565. let rp = rdLoc(op)
  566. let pars = extract(params)
  567. if tfIterator in typ.flags:
  568. list.snippet = callIter(rp, pars)
  569. else:
  570. list.snippet = callProc(rp, pars, rawProc)
  571. genAssignment(p, tmp, list, {})
  572. if canRaise: raiseExit(p)
  573. genAssignment(p, d, tmp, {})
  574. else:
  575. genCallPattern()
  576. if canRaise: raiseExit(p)
  577. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Builder;
  578. argBuilder: var CallBuilder) =
  579. if i < typ.n.len:
  580. # 'var T' is 'T&' in C++. This means we ignore the request of
  581. # any nkHiddenAddr when it's a 'var T'.
  582. let paramType = typ.n[i]
  583. assert(paramType.kind == nkSym)
  584. if paramType.typ.isCompileTimeOnly:
  585. discard
  586. elif paramType.typ.kind in {tyVar} and ri[i].kind == nkHiddenAddr:
  587. result.addArgument(argBuilder):
  588. genArgNoParam(p, ri[i][0], result)
  589. else:
  590. result.addArgument(argBuilder):
  591. genArgNoParam(p, ri[i], result) #, typ.n[i].sym)
  592. else:
  593. if tfVarargs notin typ.flags:
  594. localError(p.config, ri.info, "wrong argument count")
  595. else:
  596. result.addArgument(argBuilder):
  597. genArgNoParam(p, ri[i], result)
  598. discard """
  599. Dot call syntax in C++
  600. ======================
  601. so c2nim translates 'this' sometimes to 'T' and sometimes to 'var T'
  602. both of which are wrong, but often more convenient to use.
  603. For manual wrappers it can also be 'ptr T'
  604. Fortunately we know which parameter is the 'this' parameter and so can fix this
  605. mess in the codegen.
  606. now ... if the *argument* is a 'ptr' the codegen shall emit -> and otherwise .
  607. but this only depends on the argument and not on how the 'this' was declared
  608. however how the 'this' was declared affects whether we end up with
  609. wrong 'addr' and '[]' ops...
  610. Since I'm tired I'll enumerate all the cases here:
  611. var
  612. x: ptr T
  613. y: T
  614. proc t(x: T)
  615. x[].t() --> (*x).t() is correct.
  616. y.t() --> y.t() is correct
  617. proc u(x: ptr T)
  618. x.u() --> needs to become x->u()
  619. (addr y).u() --> needs to become y.u()
  620. proc v(x: var T)
  621. --> first skip the implicit 'nkAddr' node
  622. x[].v() --> (*x).v() is correct, but might have been eliminated due
  623. to the nkAddr node! So for this case we need to generate '->'
  624. y.v() --> y.v() is correct
  625. """
  626. proc skipAddrDeref(node: PNode): PNode =
  627. var n = node
  628. var isAddr = false
  629. case n.kind
  630. of nkAddr, nkHiddenAddr:
  631. n = n[0]
  632. isAddr = true
  633. of nkDerefExpr, nkHiddenDeref:
  634. n = n[0]
  635. else: return n
  636. if n.kind == nkObjDownConv: n = n[0]
  637. if isAddr and n.kind in {nkDerefExpr, nkHiddenDeref}:
  638. result = n[0]
  639. elif n.kind in {nkAddr, nkHiddenAddr}:
  640. result = n[0]
  641. else:
  642. result = node
  643. proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Builder) =
  644. # for better or worse c2nim translates the 'this' argument to a 'var T'.
  645. # However manual wrappers may also use 'ptr T'. In any case we support both
  646. # for convenience.
  647. internalAssert p.config, i < typ.n.len
  648. assert(typ.n[i].kind == nkSym)
  649. # if the parameter is lying (tyVar) and thus we required an additional deref,
  650. # skip the deref:
  651. var ri = ri[i]
  652. while ri.kind == nkObjDownConv: ri = ri[0]
  653. let t = typ[i].skipTypes({tyGenericInst, tyAlias, tySink})
  654. if t.kind in {tyVar}:
  655. let x = if ri.kind == nkHiddenAddr: ri[0] else: ri
  656. if x.typ.kind == tyPtr:
  657. genArgNoParam(p, x, result)
  658. result.add("->")
  659. elif x.kind in {nkHiddenDeref, nkDerefExpr} and x[0].typ.kind == tyPtr:
  660. genArgNoParam(p, x[0], result)
  661. result.add("->")
  662. else:
  663. genArgNoParam(p, x, result)
  664. result.add(".")
  665. elif t.kind == tyPtr:
  666. if ri.kind in {nkAddr, nkHiddenAddr}:
  667. genArgNoParam(p, ri[0], result)
  668. result.add(".")
  669. else:
  670. genArgNoParam(p, ri, result)
  671. result.add("->")
  672. else:
  673. ri = skipAddrDeref(ri)
  674. if ri.kind in {nkAddr, nkHiddenAddr}: ri = ri[0]
  675. genArgNoParam(p, ri, result) #, typ.n[i].sym)
  676. result.add(".")
  677. proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Builder) =
  678. var i = 0
  679. var j = 1
  680. while i < pat.len:
  681. case pat[i]
  682. of '@':
  683. var callBuilder = default(CallBuilder) # not init call builder
  684. for k in j..<ri.len:
  685. genOtherArg(p, ri, k, typ, result, callBuilder)
  686. inc i
  687. of '#':
  688. if i+1 < pat.len and pat[i+1] in {'+', '@'}:
  689. let ri = ri[j]
  690. if ri.kind in nkCallKinds:
  691. let typ = skipTypes(ri[0].typ, abstractInst)
  692. if pat[i+1] == '+': genArgNoParam(p, ri[0], result)
  693. result.add("(")
  694. if 1 < ri.len:
  695. var callBuilder: CallBuilder = default(CallBuilder)
  696. genOtherArg(p, ri, 1, typ, result, callBuilder)
  697. for k in j+1..<ri.len:
  698. var callBuilder: CallBuilder = default(CallBuilder)
  699. genOtherArg(p, ri, k, typ, result, callBuilder)
  700. result.add(")")
  701. else:
  702. localError(p.config, ri.info, "call expression expected for C++ pattern")
  703. inc i
  704. elif i+1 < pat.len and pat[i+1] == '.':
  705. genThisArg(p, ri, j, typ, result)
  706. inc i
  707. elif i+1 < pat.len and pat[i+1] == '[':
  708. var arg = ri[j].skipAddrDeref
  709. while arg.kind in {nkAddr, nkHiddenAddr, nkObjDownConv}: arg = arg[0]
  710. genArgNoParam(p, arg, result)
  711. #result.add debugTree(arg, 0, 10)
  712. else:
  713. var callBuilder = default(CallBuilder) # not init call builder
  714. genOtherArg(p, ri, j, typ, result, callBuilder)
  715. inc j
  716. inc i
  717. of '\'':
  718. var idx, stars: int = 0
  719. if scanCppGenericSlot(pat, i, idx, stars):
  720. var t = resolveStarsInCppType(typ, idx, stars)
  721. if t == nil: result.add(CVoid)
  722. else: result.add(getTypeDesc(p.module, t))
  723. else:
  724. let start = i
  725. while i < pat.len:
  726. if pat[i] notin {'@', '#', '\''}: inc(i)
  727. else: break
  728. if i - 1 >= start:
  729. result.add(substr(pat, start, i - 1))
  730. proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  731. var op = initLocExpr(p, ri[0])
  732. # getUniqueType() is too expensive here:
  733. var typ = skipTypes(ri[0].typ, abstractInst)
  734. assert(typ.kind == tyProc)
  735. # don't call '$' here for efficiency:
  736. let pat = $ri[0].sym.loc.snippet
  737. internalAssert p.config, pat.len > 0
  738. if pat.contains({'#', '(', '@', '\''}):
  739. var pl = newBuilder("")
  740. genPatternCall(p, ri, pat, typ, pl)
  741. # simpler version of 'fixupCall' that works with the pl+params combination:
  742. var typ = skipTypes(ri[0].typ, abstractInst)
  743. if typ.returnType != nil:
  744. if p.module.compileToCpp and lfSingleUse in d.flags:
  745. # do not generate spurious temporaries for C++! For C we're better off
  746. # with them to prevent undefined behaviour and because the codegen
  747. # is free to emit expressions multiple times!
  748. d.k = locCall
  749. d.snippet = extract(pl)
  750. excl d.flags, lfSingleUse
  751. else:
  752. if d.k == locNone: d = getTemp(p, typ.returnType)
  753. assert(d.t != nil) # generate an assignment to d:
  754. var list: TLoc = initLoc(locCall, d.lode, OnUnknown)
  755. list.snippet = extract(pl)
  756. genAssignment(p, d, list, {}) # no need for deep copying
  757. else:
  758. p.s(cpsStmts).addStmt():
  759. p.s(cpsStmts).add(extract(pl))
  760. else:
  761. var pl = newBuilder("")
  762. if 1 < ri.len:
  763. genThisArg(p, ri, 1, typ, pl)
  764. pl.add(op.snippet)
  765. var res = newBuilder("")
  766. var call = initCallBuilder(res, extract(pl))
  767. for i in 2..<ri.len:
  768. genOtherArg(p, ri, i, typ, res, call)
  769. fixupCall(p, le, ri, d, res, call)
  770. proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
  771. # generates a crappy ObjC call
  772. var op = initLocExpr(p, ri[0])
  773. var pl = newBuilder("[")
  774. # getUniqueType() is too expensive here:
  775. var typ = skipTypes(ri[0].typ, abstractInst)
  776. assert(typ.kind == tyProc)
  777. # don't call '$' here for efficiency:
  778. let pat = $ri[0].sym.loc.snippet
  779. internalAssert p.config, pat.len > 0
  780. var start = 3
  781. if ' ' in pat:
  782. start = 1
  783. pl.add(op.snippet)
  784. if ri.len > 1:
  785. pl.add(": ")
  786. genArg(p, ri[1], typ.n[1].sym, ri, pl)
  787. start = 2
  788. else:
  789. if ri.len > 1:
  790. genArg(p, ri[1], typ.n[1].sym, ri, pl)
  791. pl.add(" ")
  792. pl.add(op.snippet)
  793. if ri.len > 2:
  794. pl.add(": ")
  795. genArg(p, ri[2], typ.n[2].sym, ri, pl)
  796. for i in start..<ri.len:
  797. if i >= typ.n.len:
  798. internalError(p.config, ri.info, "varargs for objective C method?")
  799. assert(typ.n[i].kind == nkSym)
  800. var param = typ.n[i].sym
  801. pl.add(" ")
  802. pl.add(param.name.s)
  803. pl.add(": ")
  804. genArg(p, ri[i], param, ri, pl)
  805. if typ.returnType != nil:
  806. if isInvalidReturnType(p.config, typ):
  807. if ri.len > 1: pl.add(" ")
  808. # beware of 'result = p(result)'. We always allocate a temporary:
  809. if d.k in {locTemp, locNone}:
  810. # We already got a temp. Great, special case it:
  811. if d.k == locNone: d = getTemp(p, typ.returnType, needsInit=true)
  812. pl.add("Result: ")
  813. pl.add(addrLoc(p.config, d))
  814. pl.add("]")
  815. p.s(cpsStmts).addStmt():
  816. p.s(cpsStmts).add(extract(pl))
  817. else:
  818. var tmp: TLoc = getTemp(p, typ.returnType, needsInit=true)
  819. pl.add(addrLoc(p.config, tmp))
  820. pl.add("]")
  821. p.s(cpsStmts).addStmt():
  822. p.s(cpsStmts).add(extract(pl))
  823. genAssignment(p, d, tmp, {}) # no need for deep copying
  824. else:
  825. pl.add("]")
  826. if d.k == locNone: d = getTemp(p, typ.returnType)
  827. assert(d.t != nil) # generate an assignment to d:
  828. var list: TLoc = initLoc(locCall, ri, OnUnknown)
  829. list.snippet = extract(pl)
  830. genAssignment(p, d, list, {}) # no need for deep copying
  831. else:
  832. pl.add("]")
  833. p.s(cpsStmts).addStmt():
  834. p.s(cpsStmts).add(extract(pl))
  835. proc notYetAlive(n: PNode): bool {.inline.} =
  836. let r = getRoot(n)
  837. result = r != nil and r.loc.lode == nil
  838. proc isInactiveDestructorCall(p: BProc, e: PNode): bool =
  839. #[ Consider this example.
  840. var :tmpD_3281815
  841. try:
  842. if true:
  843. return
  844. let args_3280013 =
  845. wasMoved_3281816(:tmpD_3281815)
  846. `=_3280036`(:tmpD_3281815, [1])
  847. :tmpD_3281815
  848. finally:
  849. `=destroy_3280027`(args_3280013)
  850. We want to return early but the 'finally' section is traversed before
  851. the 'let args = ...' statement. We exploit this to generate better
  852. code for 'return'. ]#
  853. result = e.len == 2 and e[0].kind == nkSym and
  854. e[0].sym.name.s == "=destroy" and notYetAlive(e[1].skipAddr)
  855. proc genAsgnCall(p: BProc, le, ri: PNode, d: var TLoc) =
  856. if p.withinBlockLeaveActions > 0 and isInactiveDestructorCall(p, ri):
  857. return
  858. if ri[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
  859. genClosureCall(p, le, ri, d)
  860. elif ri[0].kind == nkSym and sfInfixCall in ri[0].sym.flags:
  861. genInfixCall(p, le, ri, d)
  862. elif ri[0].kind == nkSym and sfNamedParamCall in ri[0].sym.flags:
  863. genNamedParamCall(p, ri, d)
  864. else:
  865. genPrefixCall(p, le, ri, d)
  866. proc genCall(p: BProc, e: PNode, d: var TLoc) = genAsgnCall(p, nil, e, d)