ccgcalls.nim 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835
  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, gcAtomicArc, 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]) and
  281. (optByRef notin param.options or not p.module.compileToCpp):
  282. initLocExpr(p, n, a)
  283. if n.kind in {nkCharLit..nkNilLit}:
  284. addAddrLoc(p.config, literalsNeedsTmp(p, a), result)
  285. else:
  286. addAddrLoc(p.config, withTmpIfNeeded(p, a, needsTmp), result)
  287. elif p.module.compileToCpp and param.typ.kind in {tyVar} and
  288. n.kind == nkHiddenAddr:
  289. initLocExprSingleUse(p, n[0], a)
  290. # if the proc is 'importc'ed but not 'importcpp'ed then 'var T' still
  291. # means '*T'. See posix.nim for lots of examples that do that in the wild.
  292. let callee = call[0]
  293. if callee.kind == nkSym and
  294. {sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
  295. {lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
  296. addAddrLoc(p.config, a, result)
  297. else:
  298. addRdLoc(a, result)
  299. else:
  300. initLocExprSingleUse(p, n, a)
  301. addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
  302. #assert result != nil
  303. proc genArgNoParam(p: BProc, n: PNode; result: var Rope; needsTmp = false) =
  304. var a: TLoc
  305. if n.kind == nkStringToCString:
  306. genArgStringToCString(p, n, result, needsTmp)
  307. else:
  308. initLocExprSingleUse(p, n, a)
  309. addRdLoc(withTmpIfNeeded(p, a, needsTmp), result)
  310. import aliasanalysis
  311. proc potentialAlias(n: PNode, potentialWrites: seq[PNode]): bool =
  312. for p in potentialWrites:
  313. if p.aliases(n) != no or n.aliases(p) != no:
  314. return true
  315. proc skipTrivialIndirections(n: PNode): PNode =
  316. result = n
  317. while true:
  318. case result.kind
  319. of nkDerefExpr, nkHiddenDeref, nkAddr, nkHiddenAddr, nkObjDownConv, nkObjUpConv:
  320. result = result[0]
  321. of nkHiddenStdConv, nkHiddenSubConv:
  322. result = result[1]
  323. else: break
  324. proc getPotentialWrites(n: PNode; mutate: bool; result: var seq[PNode]) =
  325. case n.kind:
  326. of nkLiterals, nkIdent, nkFormalParams: discard
  327. of nkSym:
  328. if mutate: result.add n
  329. of nkAsgn, nkFastAsgn, nkSinkAsgn:
  330. getPotentialWrites(n[0], true, result)
  331. getPotentialWrites(n[1], mutate, result)
  332. of nkAddr, nkHiddenAddr:
  333. getPotentialWrites(n[0], true, result)
  334. of nkBracketExpr, nkDotExpr, nkCheckedFieldExpr:
  335. getPotentialWrites(n[0], mutate, result)
  336. of nkCallKinds:
  337. case n.getMagic:
  338. of mIncl, mExcl, mInc, mDec, mAppendStrCh, mAppendStrStr, mAppendSeqElem,
  339. mAddr, mNew, mNewFinalize, mWasMoved, mDestroy, mReset:
  340. getPotentialWrites(n[1], true, result)
  341. for i in 2..<n.len:
  342. getPotentialWrites(n[i], mutate, result)
  343. of mSwap:
  344. for i in 1..<n.len:
  345. getPotentialWrites(n[i], true, result)
  346. else:
  347. for i in 1..<n.len:
  348. getPotentialWrites(n[i], mutate, result)
  349. else:
  350. for s in n:
  351. getPotentialWrites(s, mutate, result)
  352. proc getPotentialReads(n: PNode; result: var seq[PNode]) =
  353. case n.kind:
  354. of nkLiterals, nkIdent, nkFormalParams: discard
  355. of nkSym: result.add n
  356. else:
  357. for s in n:
  358. getPotentialReads(s, result)
  359. proc genParams(p: BProc, ri: PNode, typ: PType; result: var Rope) =
  360. # We must generate temporaries in cases like #14396
  361. # to keep the strict Left-To-Right evaluation
  362. var needTmp = newSeq[bool](ri.len - 1)
  363. var potentialWrites: seq[PNode]
  364. for i in countdown(ri.len - 1, 1):
  365. if ri[i].skipTrivialIndirections.kind == nkSym:
  366. needTmp[i - 1] = potentialAlias(ri[i], potentialWrites)
  367. else:
  368. #if not ri[i].typ.isCompileTimeOnly:
  369. var potentialReads: seq[PNode]
  370. getPotentialReads(ri[i], potentialReads)
  371. for n in potentialReads:
  372. if not needTmp[i - 1]:
  373. needTmp[i - 1] = potentialAlias(n, potentialWrites)
  374. getPotentialWrites(ri[i], false, potentialWrites)
  375. if ri[i].kind in {nkHiddenAddr, nkAddr}:
  376. # Optimization: don't use a temp, if we would only take the address anyway
  377. needTmp[i - 1] = false
  378. var oldLen = result.len
  379. for i in 1..<ri.len:
  380. if i < typ.len:
  381. assert(typ.n[i].kind == nkSym)
  382. let paramType = typ.n[i]
  383. if not paramType.typ.isCompileTimeOnly:
  384. if oldLen != result.len:
  385. result.add(", ")
  386. oldLen = result.len
  387. genArg(p, ri[i], paramType.sym, ri, result, needTmp[i-1])
  388. else:
  389. if oldLen != result.len:
  390. result.add(", ")
  391. oldLen = result.len
  392. genArgNoParam(p, ri[i], result, needTmp[i-1])
  393. proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
  394. if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
  395. (sym.typ.callConv == ccInline or sym.owner.id == module.id):
  396. res = res & "_actual".rope
  397. proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  398. var op: TLoc
  399. # this is a hotspot in the compiler
  400. initLocExpr(p, ri[0], op)
  401. # getUniqueType() is too expensive here:
  402. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  403. assert(typ.kind == tyProc)
  404. assert(typ.len == typ.n.len)
  405. var params = newRopeAppender()
  406. genParams(p, ri, typ, params)
  407. var callee = rdLoc(op)
  408. if p.hcrOn and ri[0].kind == nkSym:
  409. callee.addActualSuffixForHCR(p.module.module, ri[0].sym)
  410. fixupCall(p, le, ri, d, callee, params)
  411. proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
  412. proc addComma(r: Rope): Rope =
  413. if r.len == 0: r else: r & ", "
  414. const PatProc = "$1.ClE_0? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2)"
  415. const PatIter = "$1.ClP_0($3$1.ClE_0)" # we know the env exists
  416. var op: TLoc
  417. initLocExpr(p, ri[0], op)
  418. # getUniqueType() is too expensive here:
  419. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  420. assert(typ.kind == tyProc)
  421. assert(typ.len == typ.n.len)
  422. var pl = newRopeAppender()
  423. genParams(p, ri, typ, pl)
  424. template genCallPattern {.dirty.} =
  425. if tfIterator in typ.flags:
  426. lineF(p, cpsStmts, PatIter & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
  427. else:
  428. lineF(p, cpsStmts, PatProc & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
  429. let rawProc = getClosureType(p.module, typ, clHalf)
  430. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  431. if typ[0] != nil:
  432. if isInvalidReturnType(p.config, typ):
  433. if ri.len > 1: pl.add(", ")
  434. # beware of 'result = p(result)'. We may need to allocate a temporary:
  435. if d.k in {locTemp, locNone} or not preventNrvo(p, d.lode, le, ri):
  436. # Great, we can use 'd':
  437. if d.k == locNone:
  438. getTemp(p, typ[0], d, needsInit=true)
  439. elif d.k notin {locTemp} and not hasNoInit(ri):
  440. # reset before pass as 'result' var:
  441. discard "resetLoc(p, d)"
  442. pl.add(addrLoc(p.config, d))
  443. genCallPattern()
  444. if canRaise: raiseExit(p)
  445. else:
  446. var tmp: TLoc
  447. getTemp(p, typ[0], tmp, needsInit=true)
  448. pl.add(addrLoc(p.config, tmp))
  449. genCallPattern()
  450. if canRaise: raiseExit(p)
  451. genAssignment(p, d, tmp, {}) # no need for deep copying
  452. elif isHarmlessStore(p, canRaise, d):
  453. if d.k == locNone: getTemp(p, typ[0], d)
  454. assert(d.t != nil) # generate an assignment to d:
  455. var list: TLoc
  456. initLoc(list, locCall, d.lode, OnUnknown)
  457. if tfIterator in typ.flags:
  458. list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
  459. else:
  460. list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
  461. genAssignment(p, d, list, {}) # no need for deep copying
  462. if canRaise: raiseExit(p)
  463. else:
  464. var tmp: TLoc
  465. getTemp(p, typ[0], tmp)
  466. assert(d.t != nil) # generate an assignment to d:
  467. var list: TLoc
  468. initLoc(list, locCall, d.lode, OnUnknown)
  469. if tfIterator in typ.flags:
  470. list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
  471. else:
  472. list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
  473. genAssignment(p, tmp, list, {})
  474. if canRaise: raiseExit(p)
  475. genAssignment(p, d, tmp, {})
  476. else:
  477. genCallPattern()
  478. if canRaise: raiseExit(p)
  479. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope;
  480. argsCounter: var int) =
  481. if i < typ.len:
  482. # 'var T' is 'T&' in C++. This means we ignore the request of
  483. # any nkHiddenAddr when it's a 'var T'.
  484. let paramType = typ.n[i]
  485. assert(paramType.kind == nkSym)
  486. if paramType.typ.isCompileTimeOnly:
  487. discard
  488. elif typ[i].kind in {tyVar} and ri[i].kind == nkHiddenAddr:
  489. if argsCounter > 0: result.add ", "
  490. genArgNoParam(p, ri[i][0], result)
  491. inc argsCounter
  492. else:
  493. if argsCounter > 0: result.add ", "
  494. genArgNoParam(p, ri[i], result) #, typ.n[i].sym)
  495. inc argsCounter
  496. else:
  497. if tfVarargs notin typ.flags:
  498. localError(p.config, ri.info, "wrong argument count")
  499. else:
  500. if argsCounter > 0: result.add ", "
  501. genArgNoParam(p, ri[i], result)
  502. inc argsCounter
  503. discard """
  504. Dot call syntax in C++
  505. ======================
  506. so c2nim translates 'this' sometimes to 'T' and sometimes to 'var T'
  507. both of which are wrong, but often more convenient to use.
  508. For manual wrappers it can also be 'ptr T'
  509. Fortunately we know which parameter is the 'this' parameter and so can fix this
  510. mess in the codegen.
  511. now ... if the *argument* is a 'ptr' the codegen shall emit -> and otherwise .
  512. but this only depends on the argument and not on how the 'this' was declared
  513. however how the 'this' was declared affects whether we end up with
  514. wrong 'addr' and '[]' ops...
  515. Since I'm tired I'll enumerate all the cases here:
  516. var
  517. x: ptr T
  518. y: T
  519. proc t(x: T)
  520. x[].t() --> (*x).t() is correct.
  521. y.t() --> y.t() is correct
  522. proc u(x: ptr T)
  523. x.u() --> needs to become x->u()
  524. (addr y).u() --> needs to become y.u()
  525. proc v(x: var T)
  526. --> first skip the implicit 'nkAddr' node
  527. x[].v() --> (*x).v() is correct, but might have been eliminated due
  528. to the nkAddr node! So for this case we need to generate '->'
  529. y.v() --> y.v() is correct
  530. """
  531. proc skipAddrDeref(node: PNode): PNode =
  532. var n = node
  533. var isAddr = false
  534. case n.kind
  535. of nkAddr, nkHiddenAddr:
  536. n = n[0]
  537. isAddr = true
  538. of nkDerefExpr, nkHiddenDeref:
  539. n = n[0]
  540. else: return n
  541. if n.kind == nkObjDownConv: n = n[0]
  542. if isAddr and n.kind in {nkDerefExpr, nkHiddenDeref}:
  543. result = n[0]
  544. elif n.kind in {nkAddr, nkHiddenAddr}:
  545. result = n[0]
  546. else:
  547. result = node
  548. proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType; result: var Rope) =
  549. # for better or worse c2nim translates the 'this' argument to a 'var T'.
  550. # However manual wrappers may also use 'ptr T'. In any case we support both
  551. # for convenience.
  552. internalAssert p.config, i < typ.len
  553. assert(typ.n[i].kind == nkSym)
  554. # if the parameter is lying (tyVar) and thus we required an additional deref,
  555. # skip the deref:
  556. var ri = ri[i]
  557. while ri.kind == nkObjDownConv: ri = ri[0]
  558. let t = typ[i].skipTypes({tyGenericInst, tyAlias, tySink})
  559. if t.kind in {tyVar}:
  560. let x = if ri.kind == nkHiddenAddr: ri[0] else: ri
  561. if x.typ.kind == tyPtr:
  562. genArgNoParam(p, x, result)
  563. result.add("->")
  564. elif x.kind in {nkHiddenDeref, nkDerefExpr} and x[0].typ.kind == tyPtr:
  565. genArgNoParam(p, x[0], result)
  566. result.add("->")
  567. else:
  568. genArgNoParam(p, x, result)
  569. result.add(".")
  570. elif t.kind == tyPtr:
  571. if ri.kind in {nkAddr, nkHiddenAddr}:
  572. genArgNoParam(p, ri[0], result)
  573. result.add(".")
  574. else:
  575. genArgNoParam(p, ri, result)
  576. result.add("->")
  577. else:
  578. ri = skipAddrDeref(ri)
  579. if ri.kind in {nkAddr, nkHiddenAddr}: ri = ri[0]
  580. genArgNoParam(p, ri, result) #, typ.n[i].sym)
  581. result.add(".")
  582. proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType; result: var Rope) =
  583. var i = 0
  584. var j = 1
  585. while i < pat.len:
  586. case pat[i]
  587. of '@':
  588. var argsCounter = 0
  589. for k in j..<ri.len:
  590. genOtherArg(p, ri, k, typ, result, argsCounter)
  591. inc i
  592. of '#':
  593. if i+1 < pat.len and pat[i+1] in {'+', '@'}:
  594. let ri = ri[j]
  595. if ri.kind in nkCallKinds:
  596. let typ = skipTypes(ri[0].typ, abstractInst)
  597. if pat[i+1] == '+': genArgNoParam(p, ri[0], result)
  598. result.add("(")
  599. if 1 < ri.len:
  600. var argsCounterB = 0
  601. genOtherArg(p, ri, 1, typ, result, argsCounterB)
  602. for k in j+1..<ri.len:
  603. var argsCounterB = 0
  604. genOtherArg(p, ri, k, typ, result, argsCounterB)
  605. result.add(")")
  606. else:
  607. localError(p.config, ri.info, "call expression expected for C++ pattern")
  608. inc i
  609. elif i+1 < pat.len and pat[i+1] == '.':
  610. genThisArg(p, ri, j, typ, result)
  611. inc i
  612. elif i+1 < pat.len and pat[i+1] == '[':
  613. var arg = ri[j].skipAddrDeref
  614. while arg.kind in {nkAddr, nkHiddenAddr, nkObjDownConv}: arg = arg[0]
  615. genArgNoParam(p, arg, result)
  616. #result.add debugTree(arg, 0, 10)
  617. else:
  618. var argsCounter = 0
  619. genOtherArg(p, ri, j, typ, result, argsCounter)
  620. inc j
  621. inc i
  622. of '\'':
  623. var idx, stars: int
  624. if scanCppGenericSlot(pat, i, idx, stars):
  625. var t = resolveStarsInCppType(typ, idx, stars)
  626. if t == nil: result.add("void")
  627. else: result.add(getTypeDesc(p.module, t))
  628. else:
  629. let start = i
  630. while i < pat.len:
  631. if pat[i] notin {'@', '#', '\''}: inc(i)
  632. else: break
  633. if i - 1 >= start:
  634. result.add(substr(pat, start, i - 1))
  635. proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  636. var op: TLoc
  637. initLocExpr(p, ri[0], op)
  638. # getUniqueType() is too expensive here:
  639. var typ = skipTypes(ri[0].typ, abstractInst)
  640. assert(typ.kind == tyProc)
  641. assert(typ.len == typ.n.len)
  642. # don't call '$' here for efficiency:
  643. let pat = $ri[0].sym.loc.r
  644. internalAssert p.config, pat.len > 0
  645. if pat.contains({'#', '(', '@', '\''}):
  646. var pl = newRopeAppender()
  647. genPatternCall(p, ri, pat, typ, pl)
  648. # simpler version of 'fixupCall' that works with the pl+params combination:
  649. var typ = skipTypes(ri[0].typ, abstractInst)
  650. if typ[0] != nil:
  651. if p.module.compileToCpp and lfSingleUse in d.flags:
  652. # do not generate spurious temporaries for C++! For C we're better off
  653. # with them to prevent undefined behaviour and because the codegen
  654. # is free to emit expressions multiple times!
  655. d.k = locCall
  656. d.r = pl
  657. excl d.flags, lfSingleUse
  658. else:
  659. if d.k == locNone: getTemp(p, typ[0], d)
  660. assert(d.t != nil) # generate an assignment to d:
  661. var list: TLoc
  662. initLoc(list, locCall, d.lode, OnUnknown)
  663. list.r = pl
  664. genAssignment(p, d, list, {}) # no need for deep copying
  665. else:
  666. pl.add(";\n")
  667. line(p, cpsStmts, pl)
  668. else:
  669. var pl = newRopeAppender()
  670. var argsCounter = 0
  671. if 1 < ri.len:
  672. genThisArg(p, ri, 1, typ, pl)
  673. pl.add(op.r)
  674. var params = newRopeAppender()
  675. for i in 2..<ri.len:
  676. assert(typ.len == typ.n.len)
  677. genOtherArg(p, ri, i, typ, params, argsCounter)
  678. fixupCall(p, le, ri, d, pl, params)
  679. proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
  680. # generates a crappy ObjC call
  681. var op: TLoc
  682. initLocExpr(p, ri[0], op)
  683. var pl = "["
  684. # getUniqueType() is too expensive here:
  685. var typ = skipTypes(ri[0].typ, abstractInst)
  686. assert(typ.kind == tyProc)
  687. assert(typ.len == typ.n.len)
  688. # don't call '$' here for efficiency:
  689. let pat = $ri[0].sym.loc.r
  690. internalAssert p.config, pat.len > 0
  691. var start = 3
  692. if ' ' in pat:
  693. start = 1
  694. pl.add(op.r)
  695. if ri.len > 1:
  696. pl.add(": ")
  697. genArg(p, ri[1], typ.n[1].sym, ri, pl)
  698. start = 2
  699. else:
  700. if ri.len > 1:
  701. genArg(p, ri[1], typ.n[1].sym, ri, pl)
  702. pl.add(" ")
  703. pl.add(op.r)
  704. if ri.len > 2:
  705. pl.add(": ")
  706. genArg(p, ri[2], typ.n[2].sym, ri, pl)
  707. for i in start..<ri.len:
  708. assert(typ.len == typ.n.len)
  709. if i >= typ.len:
  710. internalError(p.config, ri.info, "varargs for objective C method?")
  711. assert(typ.n[i].kind == nkSym)
  712. var param = typ.n[i].sym
  713. pl.add(" ")
  714. pl.add(param.name.s)
  715. pl.add(": ")
  716. genArg(p, ri[i], param, ri, pl)
  717. if typ[0] != nil:
  718. if isInvalidReturnType(p.config, typ):
  719. if ri.len > 1: pl.add(" ")
  720. # beware of 'result = p(result)'. We always allocate a temporary:
  721. if d.k in {locTemp, locNone}:
  722. # We already got a temp. Great, special case it:
  723. if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
  724. pl.add("Result: ")
  725. pl.add(addrLoc(p.config, d))
  726. pl.add("];\n")
  727. line(p, cpsStmts, pl)
  728. else:
  729. var tmp: TLoc
  730. getTemp(p, typ[0], tmp, needsInit=true)
  731. pl.add(addrLoc(p.config, tmp))
  732. pl.add("];\n")
  733. line(p, cpsStmts, pl)
  734. genAssignment(p, d, tmp, {}) # no need for deep copying
  735. else:
  736. pl.add("]")
  737. if d.k == locNone: getTemp(p, typ[0], d)
  738. assert(d.t != nil) # generate an assignment to d:
  739. var list: TLoc
  740. initLoc(list, locCall, ri, OnUnknown)
  741. list.r = pl
  742. genAssignment(p, d, list, {}) # no need for deep copying
  743. else:
  744. pl.add("];\n")
  745. line(p, cpsStmts, pl)
  746. proc notYetAlive(n: PNode): bool {.inline.} =
  747. let r = getRoot(n)
  748. result = r != nil and r.loc.lode == nil
  749. proc isInactiveDestructorCall(p: BProc, e: PNode): bool =
  750. #[ Consider this example.
  751. var :tmpD_3281815
  752. try:
  753. if true:
  754. return
  755. let args_3280013 =
  756. wasMoved_3281816(:tmpD_3281815)
  757. `=_3280036`(:tmpD_3281815, [1])
  758. :tmpD_3281815
  759. finally:
  760. `=destroy_3280027`(args_3280013)
  761. We want to return early but the 'finally' section is traversed before
  762. the 'let args = ...' statement. We exploit this to generate better
  763. code for 'return'. ]#
  764. result = e.len == 2 and e[0].kind == nkSym and
  765. e[0].sym.name.s == "=destroy" and notYetAlive(e[1].skipAddr)
  766. proc genAsgnCall(p: BProc, le, ri: PNode, d: var TLoc) =
  767. if p.withinBlockLeaveActions > 0 and isInactiveDestructorCall(p, ri):
  768. return
  769. if ri[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
  770. genClosureCall(p, le, ri, d)
  771. elif ri[0].kind == nkSym and sfInfixCall in ri[0].sym.flags:
  772. genInfixCall(p, le, ri, d)
  773. elif ri[0].kind == nkSym and sfNamedParamCall in ri[0].sym.flags:
  774. genNamedParamCall(p, ri, d)
  775. else:
  776. genPrefixCall(p, le, ri, d)
  777. proc genCall(p: BProc, e: PNode, d: var TLoc) = genAsgnCall(p, nil, e, d)