ccgcalls.nim 31 KB

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