ccgcalls.nim 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668
  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; 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. proc hasNoInit(call: PNode): bool {.inline.} =
  55. result = call[0].kind == nkSym and sfNoInit in call[0].sym.flags
  56. proc isHarmlessStore(p: BProc; canRaise: bool; d: TLoc): bool =
  57. if d.k in {locTemp, locNone} or not canRaise:
  58. result = true
  59. elif d.k == locLocalVar and p.withinTryWithExcept == 0:
  60. # we cannot observe a store to a local variable if the current proc
  61. # has no error handler:
  62. result = true
  63. else:
  64. result = false
  65. proc fixupCall(p: BProc, le, ri: PNode, d: var TLoc,
  66. callee, params: Rope) =
  67. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  68. genLineDir(p, ri)
  69. var pl = callee & ~"(" & params
  70. # getUniqueType() is too expensive here:
  71. var typ = skipTypes(ri[0].typ, abstractInst)
  72. if typ[0] != nil:
  73. if isInvalidReturnType(p.config, typ[0]):
  74. if params != nil: pl.add(~", ")
  75. # beware of 'result = p(result)'. We may need to allocate a temporary:
  76. if d.k in {locTemp, locNone} or not preventNrvo(p, le, ri):
  77. # Great, we can use 'd':
  78. if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
  79. elif d.k notin {locTemp} and not hasNoInit(ri):
  80. # reset before pass as 'result' var:
  81. discard "resetLoc(p, d)"
  82. pl.add(addrLoc(p.config, d))
  83. pl.add(~");$n")
  84. line(p, cpsStmts, pl)
  85. else:
  86. var tmp: TLoc
  87. getTemp(p, typ[0], tmp, needsInit=true)
  88. pl.add(addrLoc(p.config, tmp))
  89. pl.add(~");$n")
  90. line(p, cpsStmts, pl)
  91. genAssignment(p, d, tmp, {}) # no need for deep copying
  92. if canRaise: raiseExit(p)
  93. else:
  94. pl.add(~")")
  95. if p.module.compileToCpp:
  96. if lfSingleUse in d.flags:
  97. # do not generate spurious temporaries for C++! For C we're better off
  98. # with them to prevent undefined behaviour and because the codegen
  99. # is free to emit expressions multiple times!
  100. d.k = locCall
  101. d.r = pl
  102. excl d.flags, lfSingleUse
  103. else:
  104. if d.k == locNone and p.splitDecls == 0:
  105. getTempCpp(p, typ[0], d, pl)
  106. else:
  107. if d.k == locNone: getTemp(p, typ[0], d)
  108. var list: TLoc
  109. initLoc(list, locCall, d.lode, OnUnknown)
  110. list.r = pl
  111. genAssignment(p, d, list, {}) # no need for deep copying
  112. if canRaise: raiseExit(p)
  113. elif isHarmlessStore(p, canRaise, d):
  114. if d.k == locNone: getTemp(p, typ[0], d)
  115. assert(d.t != nil) # generate an assignment to d:
  116. var list: TLoc
  117. initLoc(list, locCall, d.lode, OnUnknown)
  118. list.r = pl
  119. genAssignment(p, d, list, {}) # no need for deep copying
  120. if canRaise: raiseExit(p)
  121. else:
  122. var tmp: TLoc
  123. getTemp(p, typ[0], tmp, needsInit=true)
  124. var list: TLoc
  125. initLoc(list, locCall, d.lode, OnUnknown)
  126. list.r = pl
  127. genAssignment(p, tmp, list, {}) # no need for deep copying
  128. if canRaise: raiseExit(p)
  129. genAssignment(p, d, tmp, {})
  130. else:
  131. pl.add(~");$n")
  132. line(p, cpsStmts, pl)
  133. if canRaise: raiseExit(p)
  134. proc genBoundsCheck(p: BProc; arr, a, b: TLoc)
  135. proc openArrayLoc(p: BProc, formalType: PType, n: PNode): Rope =
  136. var a: TLoc
  137. var q = skipConv(n)
  138. var skipped = false
  139. while q.kind == nkStmtListExpr and q.len > 0:
  140. skipped = true
  141. q = q.lastSon
  142. if getMagic(q) == mSlice:
  143. # magic: pass slice to openArray:
  144. if skipped:
  145. q = skipConv(n)
  146. while q.kind == nkStmtListExpr and q.len > 0:
  147. for i in 0..<q.len-1:
  148. genStmts(p, q[i])
  149. q = q.lastSon
  150. var 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. let ty = skipTypes(a.t, abstractVar+{tyPtr})
  158. let dest = getTypeDesc(p.module, n.typ[0])
  159. case ty.kind
  160. of tyArray:
  161. let first = toInt64(firstOrd(p.config, ty))
  162. if first == 0:
  163. result = "($4*)(($1)+($2)), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dest]
  164. else:
  165. result = "($5*)($1)+(($2)-($4)), ($3)-($2)+1" %
  166. [rdLoc(a), rdLoc(b), rdLoc(c), intLiteral(first), dest]
  167. of tyOpenArray, tyVarargs, tyUncheckedArray, tyCString:
  168. result = "($4*)($1)+($2), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dest]
  169. of tyString, tySequence:
  170. let atyp = skipTypes(a.t, abstractInst)
  171. if formalType.skipTypes(abstractInst).kind == tyVar and atyp.kind == tyString and
  172. optSeqDestructors in p.config.globalOptions:
  173. linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
  174. if atyp.kind == tyVar and not compileToCpp(p.module):
  175. result = "($5*)(*$1)$4+($2), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dataField(p), dest]
  176. else:
  177. result = "($5*)$1$4+($2), ($3)-($2)+1" % [rdLoc(a), rdLoc(b), rdLoc(c), dataField(p), dest]
  178. else:
  179. internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  180. else:
  181. initLocExpr(p, n, a)
  182. case skipTypes(a.t, abstractVar+{tyStatic}).kind
  183. of tyOpenArray, tyVarargs:
  184. result = "$1, $1Len_0" % [rdLoc(a)]
  185. of tyString, tySequence:
  186. let ntyp = skipTypes(n.typ, abstractInst)
  187. if formalType.skipTypes(abstractInst).kind == tyVar and ntyp.kind == tyString and
  188. optSeqDestructors in p.config.globalOptions:
  189. linefmt(p, cpsStmts, "#nimPrepareStrMutationV2($1);$n", [byRefLoc(p, a)])
  190. if ntyp.kind == tyVar and not compileToCpp(p.module):
  191. var t: TLoc
  192. t.r = "(*$1)" % [a.rdLoc]
  193. result = "(*$1)$3, $2" % [a.rdLoc, lenExpr(p, t), dataField(p)]
  194. else:
  195. result = "$1$3, $2" % [a.rdLoc, lenExpr(p, a), dataField(p)]
  196. of tyArray:
  197. result = "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))]
  198. of tyPtr, tyRef:
  199. case lastSon(a.t).kind
  200. of tyString, tySequence:
  201. var t: TLoc
  202. t.r = "(*$1)" % [a.rdLoc]
  203. result = "(*$1)$3, $2" % [a.rdLoc, lenExpr(p, t), dataField(p)]
  204. of tyArray:
  205. result = "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, lastSon(a.t)))]
  206. else:
  207. internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  208. else: internalError(p.config, "openArrayLoc: " & typeToString(a.t))
  209. proc genArgStringToCString(p: BProc, n: PNode): Rope {.inline.} =
  210. var a: TLoc
  211. initLocExpr(p, n[0], a)
  212. result = ropecg(p.module, "#nimToCStringConv($1)", [a.rdLoc])
  213. proc genArg(p: BProc, n: PNode, param: PSym; call: PNode): Rope =
  214. var a: TLoc
  215. if n.kind == nkStringToCString:
  216. result = genArgStringToCString(p, n)
  217. elif skipTypes(param.typ, abstractVar).kind in {tyOpenArray, tyVarargs}:
  218. var n = if n.kind != nkHiddenAddr: n else: n[0]
  219. result = openArrayLoc(p, param.typ, n)
  220. elif ccgIntroducedPtr(p.config, param, call[0].typ[0]):
  221. initLocExpr(p, n, a)
  222. result = addrLoc(p.config, a)
  223. elif p.module.compileToCpp and param.typ.kind == tyVar and
  224. n.kind == nkHiddenAddr:
  225. initLocExprSingleUse(p, n[0], a)
  226. # if the proc is 'importc'ed but not 'importcpp'ed then 'var T' still
  227. # means '*T'. See posix.nim for lots of examples that do that in the wild.
  228. let callee = call[0]
  229. if callee.kind == nkSym and
  230. {sfImportc, sfInfixCall, sfCompilerProc} * callee.sym.flags == {sfImportc} and
  231. {lfHeader, lfNoDecl} * callee.sym.loc.flags != {}:
  232. result = addrLoc(p.config, a)
  233. else:
  234. result = rdLoc(a)
  235. else:
  236. initLocExprSingleUse(p, n, a)
  237. result = rdLoc(a)
  238. proc genArgNoParam(p: BProc, n: PNode): Rope =
  239. var a: TLoc
  240. if n.kind == nkStringToCString:
  241. result = genArgStringToCString(p, n)
  242. else:
  243. initLocExprSingleUse(p, n, a)
  244. result = rdLoc(a)
  245. template genParamLoop(params) {.dirty.} =
  246. if i < typ.len:
  247. assert(typ.n[i].kind == nkSym)
  248. let paramType = typ.n[i]
  249. if not paramType.typ.isCompileTimeOnly:
  250. if params != nil: params.add(~", ")
  251. params.add(genArg(p, ri[i], paramType.sym, ri))
  252. else:
  253. if params != nil: params.add(~", ")
  254. params.add(genArgNoParam(p, ri[i]))
  255. proc addActualSuffixForHCR(res: var Rope, module: PSym, sym: PSym) =
  256. if sym.flags * {sfImportc, sfNonReloadable} == {} and sym.loc.k == locProc and
  257. (sym.typ.callConv == ccInline or sym.owner.id == module.id):
  258. res = res & "_actual".rope
  259. proc genPrefixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  260. var op: TLoc
  261. # this is a hotspot in the compiler
  262. initLocExpr(p, ri[0], op)
  263. var params: Rope
  264. # getUniqueType() is too expensive here:
  265. var typ = skipTypes(ri[0].typ, abstractInstOwned)
  266. assert(typ.kind == tyProc)
  267. assert(typ.len == typ.n.len)
  268. for i in 1..<ri.len:
  269. genParamLoop(params)
  270. var callee = rdLoc(op)
  271. if p.hcrOn and ri[0].kind == nkSym:
  272. callee.addActualSuffixForHCR(p.module.module, ri[0].sym)
  273. fixupCall(p, le, ri, d, callee, params)
  274. proc genClosureCall(p: BProc, le, ri: PNode, d: var TLoc) =
  275. proc getRawProcType(p: BProc, t: PType): Rope =
  276. result = getClosureType(p.module, t, clHalf)
  277. proc addComma(r: Rope): Rope =
  278. result = if r == nil: r else: r & ~", "
  279. const PatProc = "$1.ClE_0? $1.ClP_0($3$1.ClE_0):(($4)($1.ClP_0))($2)"
  280. const PatIter = "$1.ClP_0($3$1.ClE_0)" # we know the env exists
  281. var op: TLoc
  282. initLocExpr(p, ri[0], op)
  283. var pl: Rope
  284. var typ = skipTypes(ri[0].typ, abstractInst)
  285. assert(typ.kind == tyProc)
  286. for i in 1..<ri.len:
  287. assert(typ.len == typ.n.len)
  288. genParamLoop(pl)
  289. template genCallPattern {.dirty.} =
  290. if tfIterator in typ.flags:
  291. lineF(p, cpsStmts, PatIter & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
  292. else:
  293. lineF(p, cpsStmts, PatProc & ";$n", [rdLoc(op), pl, pl.addComma, rawProc])
  294. let rawProc = getRawProcType(p, typ)
  295. let canRaise = p.config.exc == excGoto and canRaiseDisp(p, ri[0])
  296. if typ[0] != nil:
  297. if isInvalidReturnType(p.config, typ[0]):
  298. if ri.len > 1: pl.add(~", ")
  299. # beware of 'result = p(result)'. We may need to allocate a temporary:
  300. if d.k in {locTemp, locNone} or not preventNrvo(p, le, ri):
  301. # Great, we can use 'd':
  302. if d.k == locNone:
  303. getTemp(p, typ[0], d, needsInit=true)
  304. elif d.k notin {locTemp} and not hasNoInit(ri):
  305. # reset before pass as 'result' var:
  306. discard "resetLoc(p, d)"
  307. pl.add(addrLoc(p.config, d))
  308. genCallPattern()
  309. else:
  310. var tmp: TLoc
  311. getTemp(p, typ[0], tmp, needsInit=true)
  312. pl.add(addrLoc(p.config, tmp))
  313. genCallPattern()
  314. if canRaise: raiseExit(p)
  315. genAssignment(p, d, tmp, {}) # no need for deep copying
  316. elif isHarmlessStore(p, canRaise, d):
  317. if d.k == locNone: getTemp(p, typ[0], d)
  318. assert(d.t != nil) # generate an assignment to d:
  319. var list: TLoc
  320. initLoc(list, locCall, d.lode, OnUnknown)
  321. if tfIterator in typ.flags:
  322. list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
  323. else:
  324. list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
  325. genAssignment(p, d, list, {}) # no need for deep copying
  326. if canRaise: raiseExit(p)
  327. else:
  328. var tmp: TLoc
  329. getTemp(p, typ[0], tmp)
  330. assert(d.t != nil) # generate an assignment to d:
  331. var list: TLoc
  332. initLoc(list, locCall, d.lode, OnUnknown)
  333. if tfIterator in typ.flags:
  334. list.r = PatIter % [rdLoc(op), pl, pl.addComma, rawProc]
  335. else:
  336. list.r = PatProc % [rdLoc(op), pl, pl.addComma, rawProc]
  337. genAssignment(p, tmp, list, {})
  338. if canRaise: raiseExit(p)
  339. genAssignment(p, d, tmp, {})
  340. else:
  341. genCallPattern()
  342. if canRaise: raiseExit(p)
  343. proc genOtherArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
  344. if i < typ.len:
  345. # 'var T' is 'T&' in C++. This means we ignore the request of
  346. # any nkHiddenAddr when it's a 'var T'.
  347. let paramType = typ.n[i]
  348. assert(paramType.kind == nkSym)
  349. if paramType.typ.isCompileTimeOnly:
  350. result = nil
  351. elif typ[i].kind == tyVar and ri[i].kind == nkHiddenAddr:
  352. result = genArgNoParam(p, ri[i][0])
  353. else:
  354. result = genArgNoParam(p, ri[i]) #, typ.n[i].sym)
  355. else:
  356. if tfVarargs notin typ.flags:
  357. localError(p.config, ri.info, "wrong argument count")
  358. result = nil
  359. else:
  360. result = genArgNoParam(p, ri[i])
  361. discard """
  362. Dot call syntax in C++
  363. ======================
  364. so c2nim translates 'this' sometimes to 'T' and sometimes to 'var T'
  365. both of which are wrong, but often more convenient to use.
  366. For manual wrappers it can also be 'ptr T'
  367. Fortunately we know which parameter is the 'this' parameter and so can fix this
  368. mess in the codegen.
  369. now ... if the *argument* is a 'ptr' the codegen shall emit -> and otherwise .
  370. but this only depends on the argument and not on how the 'this' was declared
  371. however how the 'this' was declared affects whether we end up with
  372. wrong 'addr' and '[]' ops...
  373. Since I'm tired I'll enumerate all the cases here:
  374. var
  375. x: ptr T
  376. y: T
  377. proc t(x: T)
  378. x[].t() --> (*x).t() is correct.
  379. y.t() --> y.t() is correct
  380. proc u(x: ptr T)
  381. x.u() --> needs to become x->u()
  382. (addr y).u() --> needs to become y.u()
  383. proc v(x: var T)
  384. --> first skip the implicit 'nkAddr' node
  385. x[].v() --> (*x).v() is correct, but might have been eliminated due
  386. to the nkAddr node! So for this case we need to generate '->'
  387. y.v() --> y.v() is correct
  388. """
  389. proc skipAddrDeref(node: PNode): PNode =
  390. var n = node
  391. var isAddr = false
  392. case n.kind
  393. of nkAddr, nkHiddenAddr:
  394. n = n[0]
  395. isAddr = true
  396. of nkDerefExpr, nkHiddenDeref:
  397. n = n[0]
  398. else: return n
  399. if n.kind == nkObjDownConv: n = n[0]
  400. if isAddr and n.kind in {nkDerefExpr, nkHiddenDeref}:
  401. result = n[0]
  402. elif n.kind in {nkAddr, nkHiddenAddr}:
  403. result = n[0]
  404. else:
  405. result = node
  406. proc genThisArg(p: BProc; ri: PNode; i: int; typ: PType): Rope =
  407. # for better or worse c2nim translates the 'this' argument to a 'var T'.
  408. # However manual wrappers may also use 'ptr T'. In any case we support both
  409. # for convenience.
  410. internalAssert p.config, i < typ.len
  411. assert(typ.n[i].kind == nkSym)
  412. # if the parameter is lying (tyVar) and thus we required an additional deref,
  413. # skip the deref:
  414. var ri = ri[i]
  415. while ri.kind == nkObjDownConv: ri = ri[0]
  416. let t = typ[i].skipTypes({tyGenericInst, tyAlias, tySink})
  417. if t.kind == tyVar:
  418. let x = if ri.kind == nkHiddenAddr: ri[0] else: ri
  419. if x.typ.kind == tyPtr:
  420. result = genArgNoParam(p, x)
  421. result.add("->")
  422. elif x.kind in {nkHiddenDeref, nkDerefExpr} and x[0].typ.kind == tyPtr:
  423. result = genArgNoParam(p, x[0])
  424. result.add("->")
  425. else:
  426. result = genArgNoParam(p, x)
  427. result.add(".")
  428. elif t.kind == tyPtr:
  429. if ri.kind in {nkAddr, nkHiddenAddr}:
  430. result = genArgNoParam(p, ri[0])
  431. result.add(".")
  432. else:
  433. result = genArgNoParam(p, ri)
  434. result.add("->")
  435. else:
  436. ri = skipAddrDeref(ri)
  437. if ri.kind in {nkAddr, nkHiddenAddr}: ri = ri[0]
  438. result = genArgNoParam(p, ri) #, typ.n[i].sym)
  439. result.add(".")
  440. proc genPatternCall(p: BProc; ri: PNode; pat: string; typ: PType): Rope =
  441. var i = 0
  442. var j = 1
  443. while i < pat.len:
  444. case pat[i]
  445. of '@':
  446. var first = true
  447. for k in j..<ri.len:
  448. let arg = genOtherArg(p, ri, k, typ)
  449. if arg.len > 0:
  450. if not first:
  451. result.add(~", ")
  452. first = false
  453. result.add arg
  454. inc i
  455. of '#':
  456. if i+1 < pat.len and pat[i+1] in {'+', '@'}:
  457. let ri = ri[j]
  458. if ri.kind in nkCallKinds:
  459. let typ = skipTypes(ri[0].typ, abstractInst)
  460. if pat[i+1] == '+': result.add genArgNoParam(p, ri[0])
  461. result.add(~"(")
  462. if 1 < ri.len:
  463. result.add genOtherArg(p, ri, 1, typ)
  464. for k in j+1..<ri.len:
  465. result.add(~", ")
  466. result.add genOtherArg(p, ri, k, typ)
  467. result.add(~")")
  468. else:
  469. localError(p.config, ri.info, "call expression expected for C++ pattern")
  470. inc i
  471. elif i+1 < pat.len and pat[i+1] == '.':
  472. result.add genThisArg(p, ri, j, typ)
  473. inc i
  474. elif i+1 < pat.len and pat[i+1] == '[':
  475. var arg = ri[j].skipAddrDeref
  476. while arg.kind in {nkAddr, nkHiddenAddr, nkObjDownConv}: arg = arg[0]
  477. result.add genArgNoParam(p, arg)
  478. #result.add debugTree(arg, 0, 10)
  479. else:
  480. result.add genOtherArg(p, ri, j, typ)
  481. inc j
  482. inc i
  483. of '\'':
  484. var idx, stars: int
  485. if scanCppGenericSlot(pat, i, idx, stars):
  486. var t = resolveStarsInCppType(typ, idx, stars)
  487. if t == nil: result.add(~"void")
  488. else: result.add(getTypeDesc(p.module, t))
  489. else:
  490. let start = i
  491. while i < pat.len:
  492. if pat[i] notin {'@', '#', '\''}: inc(i)
  493. else: break
  494. if i - 1 >= start:
  495. result.add(substr(pat, start, i - 1))
  496. proc genInfixCall(p: BProc, le, ri: PNode, d: var TLoc) =
  497. var op: TLoc
  498. initLocExpr(p, ri[0], op)
  499. # getUniqueType() is too expensive here:
  500. var typ = skipTypes(ri[0].typ, abstractInst)
  501. assert(typ.kind == tyProc)
  502. assert(typ.len == typ.n.len)
  503. # don't call '$' here for efficiency:
  504. let pat = ri[0].sym.loc.r.data
  505. internalAssert p.config, pat.len > 0
  506. if pat.contains({'#', '(', '@', '\''}):
  507. var pl = genPatternCall(p, ri, pat, typ)
  508. # simpler version of 'fixupCall' that works with the pl+params combination:
  509. var typ = skipTypes(ri[0].typ, abstractInst)
  510. if typ[0] != nil:
  511. if p.module.compileToCpp and lfSingleUse in d.flags:
  512. # do not generate spurious temporaries for C++! For C we're better off
  513. # with them to prevent undefined behaviour and because the codegen
  514. # is free to emit expressions multiple times!
  515. d.k = locCall
  516. d.r = pl
  517. excl d.flags, lfSingleUse
  518. else:
  519. if d.k == locNone: getTemp(p, typ[0], d)
  520. assert(d.t != nil) # generate an assignment to d:
  521. var list: TLoc
  522. initLoc(list, locCall, d.lode, OnUnknown)
  523. list.r = pl
  524. genAssignment(p, d, list, {}) # no need for deep copying
  525. else:
  526. pl.add(~";$n")
  527. line(p, cpsStmts, pl)
  528. else:
  529. var pl: Rope = nil
  530. #var param = typ.n[1].sym
  531. if 1 < ri.len:
  532. pl.add(genThisArg(p, ri, 1, typ))
  533. pl.add(op.r)
  534. var params: Rope
  535. for i in 2..<ri.len:
  536. if params != nil: params.add(~", ")
  537. assert(typ.len == typ.n.len)
  538. params.add(genOtherArg(p, ri, i, typ))
  539. fixupCall(p, le, ri, d, pl, params)
  540. proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) =
  541. # generates a crappy ObjC call
  542. var op: TLoc
  543. initLocExpr(p, ri[0], op)
  544. var pl = ~"["
  545. # getUniqueType() is too expensive here:
  546. var typ = skipTypes(ri[0].typ, abstractInst)
  547. assert(typ.kind == tyProc)
  548. assert(typ.len == typ.n.len)
  549. # don't call '$' here for efficiency:
  550. let pat = ri[0].sym.loc.r.data
  551. internalAssert p.config, pat.len > 0
  552. var start = 3
  553. if ' ' in pat:
  554. start = 1
  555. pl.add(op.r)
  556. if ri.len > 1:
  557. pl.add(~": ")
  558. pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
  559. start = 2
  560. else:
  561. if ri.len > 1:
  562. pl.add(genArg(p, ri[1], typ.n[1].sym, ri))
  563. pl.add(~" ")
  564. pl.add(op.r)
  565. if ri.len > 2:
  566. pl.add(~": ")
  567. pl.add(genArg(p, ri[2], typ.n[2].sym, ri))
  568. for i in start..<ri.len:
  569. assert(typ.len == typ.n.len)
  570. if i >= typ.len:
  571. internalError(p.config, ri.info, "varargs for objective C method?")
  572. assert(typ.n[i].kind == nkSym)
  573. var param = typ.n[i].sym
  574. pl.add(~" ")
  575. pl.add(param.name.s)
  576. pl.add(~": ")
  577. pl.add(genArg(p, ri[i], param, ri))
  578. if typ[0] != nil:
  579. if isInvalidReturnType(p.config, typ[0]):
  580. if ri.len > 1: pl.add(~" ")
  581. # beware of 'result = p(result)'. We always allocate a temporary:
  582. if d.k in {locTemp, locNone}:
  583. # We already got a temp. Great, special case it:
  584. if d.k == locNone: getTemp(p, typ[0], d, needsInit=true)
  585. pl.add(~"Result: ")
  586. pl.add(addrLoc(p.config, d))
  587. pl.add(~"];$n")
  588. line(p, cpsStmts, pl)
  589. else:
  590. var tmp: TLoc
  591. getTemp(p, typ[0], tmp, needsInit=true)
  592. pl.add(addrLoc(p.config, tmp))
  593. pl.add(~"];$n")
  594. line(p, cpsStmts, pl)
  595. genAssignment(p, d, tmp, {}) # no need for deep copying
  596. else:
  597. pl.add(~"]")
  598. if d.k == locNone: getTemp(p, typ[0], d)
  599. assert(d.t != nil) # generate an assignment to d:
  600. var list: TLoc
  601. initLoc(list, locCall, ri, OnUnknown)
  602. list.r = pl
  603. genAssignment(p, d, list, {}) # no need for deep copying
  604. else:
  605. pl.add(~"];$n")
  606. line(p, cpsStmts, pl)
  607. proc genCall(p: BProc, e: PNode, d: var TLoc) =
  608. if e[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
  609. genClosureCall(p, nil, e, d)
  610. elif e[0].kind == nkSym and sfInfixCall in e[0].sym.flags:
  611. genInfixCall(p, nil, e, d)
  612. elif e[0].kind == nkSym and sfNamedParamCall in e[0].sym.flags:
  613. genNamedParamCall(p, e, d)
  614. else:
  615. genPrefixCall(p, nil, e, d)
  616. postStmtActions(p)
  617. proc genAsgnCall(p: BProc, le, ri: PNode, d: var TLoc) =
  618. if ri[0].typ.skipTypes({tyGenericInst, tyAlias, tySink, tyOwned}).callConv == ccClosure:
  619. genClosureCall(p, le, ri, d)
  620. elif ri[0].kind == nkSym and sfInfixCall in ri[0].sym.flags:
  621. genInfixCall(p, le, ri, d)
  622. elif ri[0].kind == nkSym and sfNamedParamCall in ri[0].sym.flags:
  623. genNamedParamCall(p, ri, d)
  624. else:
  625. genPrefixCall(p, le, ri, d)
  626. postStmtActions(p)