ccgcalls.nim 26 KB

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