ccgcalls.nim 31 KB

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