ccgcalls.nim 26 KB

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