ccgcalls.nim 29 KB

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