ccgcalls.nim 29 KB

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