ccgcalls.nim 28 KB

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