ccgcalls.nim 29 KB

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