vmgen.nim 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285
  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. ## This module implements the code generator for the VM.
  10. # Important things to remember:
  11. # - The VM does not distinguish between definitions ('var x = y') and
  12. # assignments ('x = y'). For simple data types that fit into a register
  13. # this doesn't matter. However it matters for strings and other complex
  14. # types that use the 'node' field; the reason is that slots are
  15. # re-used in a register based VM. Example:
  16. # ```nim
  17. # let s = a & b # no matter what, create fresh node
  18. # s = a & b # no matter what, keep the node
  19. # ```
  20. # Also *stores* into non-temporary memory need to perform deep copies:
  21. # a.b = x.y
  22. # We used to generate opcAsgn for the *load* of 'x.y' but this is clearly
  23. # wrong! We need to produce opcAsgn (the copy) for the *store*. This also
  24. # solves the opcLdConst vs opcAsgnConst issue. Of course whether we need
  25. # this copy depends on the involved types.
  26. import tables
  27. when defined(nimPreviewSlimSystem):
  28. import std/assertions
  29. import
  30. strutils, ast, types, msgs, renderer, vmdef,
  31. intsets, magicsys, options, lowerings, lineinfos, transf, astmsgs
  32. from modulegraphs import getBody
  33. when defined(nimCompilerStacktraceHints):
  34. import std/stackframes
  35. const
  36. debugEchoCode* = defined(nimVMDebug)
  37. when debugEchoCode:
  38. import std/private/asciitables
  39. when hasFFI:
  40. import evalffi
  41. type
  42. TGenFlag = enum
  43. gfNode # Affects how variables are loaded - always loads as rkNode
  44. gfNodeAddr # Affects how variables are loaded - always loads as rkNodeAddr
  45. gfIsParam # do not deepcopy parameters, they are immutable
  46. TGenFlags = set[TGenFlag]
  47. proc debugInfo(c: PCtx; info: TLineInfo): string =
  48. result = toFileLineCol(c.config, info)
  49. proc codeListing(c: PCtx, result: var string, start=0; last = -1) =
  50. ## for debugging purposes
  51. # first iteration: compute all necessary labels:
  52. var jumpTargets = initIntSet()
  53. let last = if last < 0: c.code.len-1 else: min(last, c.code.len-1)
  54. for i in start..last:
  55. let x = c.code[i]
  56. if x.opcode in relativeJumps:
  57. jumpTargets.incl(i+x.regBx-wordExcess)
  58. template toStr(opc: TOpcode): string = ($opc).substr(3)
  59. result.add "code listing:\n"
  60. var i = start
  61. while i <= last:
  62. if i in jumpTargets: result.addf("L$1:\n", i)
  63. let x = c.code[i]
  64. result.add($i)
  65. let opc = opcode(x)
  66. if opc in {opcIndCall, opcIndCallAsgn}:
  67. result.addf("\t$#\tr$#, r$#, nargs:$#", opc.toStr, x.regA,
  68. x.regB, x.regC)
  69. elif opc in {opcConv, opcCast}:
  70. let y = c.code[i+1]
  71. let z = c.code[i+2]
  72. result.addf("\t$#\tr$#, r$#, $#, $#", opc.toStr, x.regA, x.regB,
  73. c.types[y.regBx-wordExcess].typeToString,
  74. c.types[z.regBx-wordExcess].typeToString)
  75. inc i, 2
  76. elif opc < firstABxInstr:
  77. result.addf("\t$#\tr$#, r$#, r$#", opc.toStr, x.regA,
  78. x.regB, x.regC)
  79. elif opc in relativeJumps + {opcTry}:
  80. result.addf("\t$#\tr$#, L$#", opc.toStr, x.regA,
  81. i+x.regBx-wordExcess)
  82. elif opc in {opcExcept}:
  83. let idx = x.regBx-wordExcess
  84. result.addf("\t$#\t$#, $#", opc.toStr, x.regA, $idx)
  85. elif opc in {opcLdConst, opcAsgnConst}:
  86. let idx = x.regBx-wordExcess
  87. result.addf("\t$#\tr$#, $# ($#)", opc.toStr, x.regA,
  88. c.constants[idx].renderTree, $idx)
  89. else:
  90. result.addf("\t$#\tr$#, $#", opc.toStr, x.regA, x.regBx-wordExcess)
  91. result.add("\t# ")
  92. result.add(debugInfo(c, c.debug[i]))
  93. result.add("\n")
  94. inc i
  95. when debugEchoCode:
  96. result = result.alignTable
  97. proc echoCode*(c: PCtx; start=0; last = -1) {.deprecated.} =
  98. var buf = ""
  99. codeListing(c, buf, start, last)
  100. echo buf
  101. proc gABC(ctx: PCtx; n: PNode; opc: TOpcode; a, b, c: TRegister = 0) =
  102. ## Takes the registers `b` and `c`, applies the operation `opc` to them, and
  103. ## stores the result into register `a`
  104. ## The node is needed for debug information
  105. assert opc.ord < 255
  106. let ins = (opc.TInstrType or (a.TInstrType shl regAShift) or
  107. (b.TInstrType shl regBShift) or
  108. (c.TInstrType shl regCShift)).TInstr
  109. when false:
  110. if ctx.code.len == 43:
  111. writeStackTrace()
  112. echo "generating ", opc
  113. ctx.code.add(ins)
  114. ctx.debug.add(n.info)
  115. proc gABI(c: PCtx; n: PNode; opc: TOpcode; a, b: TRegister; imm: BiggestInt) =
  116. # Takes the `b` register and the immediate `imm`, applies the operation `opc`,
  117. # and stores the output value into `a`.
  118. # `imm` is signed and must be within [-128, 127]
  119. if imm >= -128 and imm <= 127:
  120. let ins = (opc.TInstrType or (a.TInstrType shl regAShift) or
  121. (b.TInstrType shl regBShift) or
  122. (imm+byteExcess).TInstrType shl regCShift).TInstr
  123. c.code.add(ins)
  124. c.debug.add(n.info)
  125. else:
  126. localError(c.config, n.info,
  127. "VM: immediate value does not fit into an int8")
  128. proc gABx(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0; bx: int) =
  129. # Applies `opc` to `bx` and stores it into register `a`
  130. # `bx` must be signed and in the range [regBxMin, regBxMax]
  131. when false:
  132. if c.code.len == 43:
  133. writeStackTrace()
  134. echo "generating ", opc
  135. if bx >= regBxMin-1 and bx <= regBxMax:
  136. let ins = (opc.TInstrType or a.TInstrType shl regAShift or
  137. (bx+wordExcess).TInstrType shl regBxShift).TInstr
  138. c.code.add(ins)
  139. c.debug.add(n.info)
  140. else:
  141. localError(c.config, n.info,
  142. "VM: immediate value does not fit into regBx")
  143. proc xjmp(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0): TPosition =
  144. #assert opc in {opcJmp, opcFJmp, opcTJmp}
  145. result = TPosition(c.code.len)
  146. gABx(c, n, opc, a, 0)
  147. proc genLabel(c: PCtx): TPosition =
  148. result = TPosition(c.code.len)
  149. #c.jumpTargets.incl(c.code.len)
  150. proc jmpBack(c: PCtx, n: PNode, p = TPosition(0)) =
  151. let dist = p.int - c.code.len
  152. internalAssert(c.config, regBxMin < dist and dist < regBxMax)
  153. gABx(c, n, opcJmpBack, 0, dist)
  154. proc patch(c: PCtx, p: TPosition) =
  155. # patch with current index
  156. let p = p.int
  157. let diff = c.code.len - p
  158. #c.jumpTargets.incl(c.code.len)
  159. internalAssert(c.config, regBxMin < diff and diff < regBxMax)
  160. let oldInstr = c.code[p]
  161. # opcode and regA stay the same:
  162. c.code[p] = ((oldInstr.TInstrType and regBxMask).TInstrType or
  163. TInstrType(diff+wordExcess) shl regBxShift).TInstr
  164. proc getSlotKind(t: PType): TSlotKind =
  165. case t.skipTypes(abstractRange-{tyTypeDesc}).kind
  166. of tyBool, tyChar, tyEnum, tyOrdinal, tyInt..tyInt64, tyUInt..tyUInt64:
  167. slotTempInt
  168. of tyString, tyCstring:
  169. slotTempStr
  170. of tyFloat..tyFloat128:
  171. slotTempFloat
  172. else:
  173. slotTempComplex
  174. const
  175. HighRegisterPressure = 40
  176. proc bestEffort(c: PCtx): TLineInfo =
  177. if c.prc != nil and c.prc.sym != nil:
  178. c.prc.sym.info
  179. else:
  180. c.module.info
  181. proc getFreeRegister(cc: PCtx; k: TSlotKind; start: int): TRegister =
  182. let c = cc.prc
  183. # we prefer the same slot kind here for efficiency. Unfortunately for
  184. # discardable return types we may not know the desired type. This can happen
  185. # for e.g. mNAdd[Multiple]:
  186. for i in start..c.regInfo.len-1:
  187. if c.regInfo[i].kind == k and not c.regInfo[i].inUse:
  188. c.regInfo[i].inUse = true
  189. return TRegister(i)
  190. # if register pressure is high, we re-use more aggressively:
  191. if c.regInfo.len >= high(TRegister):
  192. for i in start..c.regInfo.len-1:
  193. if not c.regInfo[i].inUse:
  194. c.regInfo[i] = (inUse: true, kind: k)
  195. return TRegister(i)
  196. if c.regInfo.len >= high(TRegister):
  197. globalError(cc.config, cc.bestEffort, "VM problem: too many registers required")
  198. result = TRegister(max(c.regInfo.len, start))
  199. c.regInfo.setLen int(result)+1
  200. c.regInfo[result] = (inUse: true, kind: k)
  201. proc getTemp(cc: PCtx; tt: PType): TRegister =
  202. let typ = tt.skipTypesOrNil({tyStatic})
  203. # we prefer the same slot kind here for efficiency. Unfortunately for
  204. # discardable return types we may not know the desired type. This can happen
  205. # for e.g. mNAdd[Multiple]:
  206. let k = if typ.isNil: slotTempComplex else: typ.getSlotKind
  207. result = getFreeRegister(cc, k, start = 0)
  208. when false:
  209. # enable this to find "register" leaks:
  210. if result == 4:
  211. echo "begin ---------------"
  212. writeStackTrace()
  213. echo "end ----------------"
  214. proc freeTemp(c: PCtx; r: TRegister) =
  215. let c = c.prc
  216. if c.regInfo[r].kind in {slotSomeTemp..slotTempComplex}:
  217. # this seems to cause https://github.com/nim-lang/Nim/issues/10647
  218. c.regInfo[r].inUse = false
  219. proc getTempRange(cc: PCtx; n: int; kind: TSlotKind): TRegister =
  220. # if register pressure is high, we re-use more aggressively:
  221. let c = cc.prc
  222. # we could also customize via the following (with proper caching in ConfigRef):
  223. # let highRegisterPressure = cc.config.getConfigVar("vm.highRegisterPressure", "40").parseInt
  224. if c.regInfo.len >= HighRegisterPressure or c.regInfo.len+n >= high(TRegister):
  225. for i in 0..c.regInfo.len-n:
  226. if not c.regInfo[i].inUse:
  227. block search:
  228. for j in i+1..i+n-1:
  229. if c.regInfo[j].inUse: break search
  230. result = TRegister(i)
  231. for k in result..result+n-1: c.regInfo[k] = (inUse: true, kind: kind)
  232. return
  233. if c.regInfo.len+n >= high(TRegister):
  234. globalError(cc.config, cc.bestEffort, "VM problem: too many registers required")
  235. result = TRegister(c.regInfo.len)
  236. setLen c.regInfo, c.regInfo.len+n
  237. for k in result..result+n-1: c.regInfo[k] = (inUse: true, kind: kind)
  238. proc freeTempRange(c: PCtx; start: TRegister, n: int) =
  239. for i in start..start+n-1: c.freeTemp(TRegister(i))
  240. template withTemp(tmp, typ, body: untyped) {.dirty.} =
  241. var tmp = getTemp(c, typ)
  242. body
  243. c.freeTemp(tmp)
  244. proc popBlock(c: PCtx; oldLen: int) =
  245. for f in c.prc.blocks[oldLen].fixups:
  246. c.patch(f)
  247. c.prc.blocks.setLen(oldLen)
  248. template withBlock(labl: PSym; body: untyped) {.dirty.} =
  249. var oldLen {.gensym.} = c.prc.blocks.len
  250. c.prc.blocks.add TBlock(label: labl, fixups: @[])
  251. body
  252. popBlock(c, oldLen)
  253. proc gen(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags = {})
  254. proc gen(c: PCtx; n: PNode; dest: TRegister; flags: TGenFlags = {}) =
  255. var d: TDest = dest
  256. gen(c, n, d, flags)
  257. #internalAssert c.config, d == dest # issue #7407
  258. proc gen(c: PCtx; n: PNode; flags: TGenFlags = {}) =
  259. var tmp: TDest = -1
  260. gen(c, n, tmp, flags)
  261. if tmp >= 0:
  262. freeTemp(c, tmp)
  263. #if n.typ.isEmptyType: internalAssert tmp < 0
  264. proc genx(c: PCtx; n: PNode; flags: TGenFlags = {}): TRegister =
  265. var tmp: TDest = -1
  266. gen(c, n, tmp, flags)
  267. #internalAssert c.config, tmp >= 0 # 'nim check' does not like this internalAssert.
  268. if tmp >= 0:
  269. result = TRegister(tmp)
  270. proc clearDest(c: PCtx; n: PNode; dest: var TDest) {.inline.} =
  271. # stmt is different from 'void' in meta programming contexts.
  272. # So we only set dest to -1 if 'void':
  273. if dest >= 0 and (n.typ.isNil or n.typ.kind == tyVoid):
  274. c.freeTemp(dest)
  275. dest = -1
  276. proc isNotOpr(n: PNode): bool =
  277. n.kind in nkCallKinds and n[0].kind == nkSym and
  278. n[0].sym.magic == mNot
  279. proc isTrue(n: PNode): bool =
  280. n.kind == nkSym and n.sym.kind == skEnumField and n.sym.position != 0 or
  281. n.kind == nkIntLit and n.intVal != 0
  282. proc genWhile(c: PCtx; n: PNode) =
  283. # lab1:
  284. # cond, tmp
  285. # fjmp tmp, lab2
  286. # body
  287. # jmp lab1
  288. # lab2:
  289. let lab1 = c.genLabel
  290. withBlock(nil):
  291. if isTrue(n[0]):
  292. c.gen(n[1])
  293. c.jmpBack(n, lab1)
  294. elif isNotOpr(n[0]):
  295. var tmp = c.genx(n[0][1])
  296. let lab2 = c.xjmp(n, opcTJmp, tmp)
  297. c.freeTemp(tmp)
  298. c.gen(n[1])
  299. c.jmpBack(n, lab1)
  300. c.patch(lab2)
  301. else:
  302. var tmp = c.genx(n[0])
  303. let lab2 = c.xjmp(n, opcFJmp, tmp)
  304. c.freeTemp(tmp)
  305. c.gen(n[1])
  306. c.jmpBack(n, lab1)
  307. c.patch(lab2)
  308. proc genBlock(c: PCtx; n: PNode; dest: var TDest) =
  309. let oldRegisterCount = c.prc.regInfo.len
  310. withBlock(n[0].sym):
  311. c.gen(n[1], dest)
  312. for i in oldRegisterCount..<c.prc.regInfo.len:
  313. #if c.prc.regInfo[i].kind in {slotFixedVar, slotFixedLet}:
  314. if i != dest:
  315. when not defined(release):
  316. if c.prc.regInfo[i].inUse and c.prc.regInfo[i].kind in {slotTempUnknown,
  317. slotTempInt,
  318. slotTempFloat,
  319. slotTempStr,
  320. slotTempComplex}:
  321. doAssert false, "leaking temporary " & $i & " " & $c.prc.regInfo[i].kind
  322. c.prc.regInfo[i] = (inUse: false, kind: slotEmpty)
  323. c.clearDest(n, dest)
  324. proc genBreak(c: PCtx; n: PNode) =
  325. let lab1 = c.xjmp(n, opcJmp)
  326. if n[0].kind == nkSym:
  327. #echo cast[int](n[0].sym)
  328. for i in countdown(c.prc.blocks.len-1, 0):
  329. if c.prc.blocks[i].label == n[0].sym:
  330. c.prc.blocks[i].fixups.add lab1
  331. return
  332. globalError(c.config, n.info, "VM problem: cannot find 'break' target")
  333. else:
  334. c.prc.blocks[c.prc.blocks.high].fixups.add lab1
  335. proc genIf(c: PCtx, n: PNode; dest: var TDest) =
  336. # if (!expr1) goto lab1;
  337. # thenPart
  338. # goto LEnd
  339. # lab1:
  340. # if (!expr2) goto lab2;
  341. # thenPart2
  342. # goto LEnd
  343. # lab2:
  344. # elsePart
  345. # Lend:
  346. if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
  347. var endings: seq[TPosition] = @[]
  348. for i in 0..<n.len:
  349. var it = n[i]
  350. if it.len == 2:
  351. withTemp(tmp, it[0].typ):
  352. var elsePos: TPosition
  353. if isNotOpr(it[0]):
  354. c.gen(it[0][1], tmp)
  355. elsePos = c.xjmp(it[0][1], opcTJmp, tmp) # if true
  356. else:
  357. c.gen(it[0], tmp)
  358. elsePos = c.xjmp(it[0], opcFJmp, tmp) # if false
  359. c.clearDest(n, dest)
  360. c.gen(it[1], dest) # then part
  361. if i < n.len-1:
  362. endings.add(c.xjmp(it[1], opcJmp, 0))
  363. c.patch(elsePos)
  364. else:
  365. c.clearDest(n, dest)
  366. c.gen(it[0], dest)
  367. for endPos in endings: c.patch(endPos)
  368. c.clearDest(n, dest)
  369. proc isTemp(c: PCtx; dest: TDest): bool =
  370. result = dest >= 0 and c.prc.regInfo[dest].kind >= slotTempUnknown
  371. proc genAndOr(c: PCtx; n: PNode; opc: TOpcode; dest: var TDest) =
  372. # asgn dest, a
  373. # tjmp|fjmp lab1
  374. # asgn dest, b
  375. # lab1:
  376. let copyBack = dest < 0 or not isTemp(c, dest)
  377. let tmp = if copyBack:
  378. getTemp(c, n.typ)
  379. else:
  380. TRegister dest
  381. c.gen(n[1], tmp)
  382. let lab1 = c.xjmp(n, opc, tmp)
  383. c.gen(n[2], tmp)
  384. c.patch(lab1)
  385. if dest < 0:
  386. dest = tmp
  387. elif copyBack:
  388. c.gABC(n, opcAsgnInt, dest, tmp)
  389. freeTemp(c, tmp)
  390. proc rawGenLiteral(c: PCtx; n: PNode): int =
  391. result = c.constants.len
  392. #assert(n.kind != nkCall)
  393. n.flags.incl nfAllConst
  394. c.constants.add n
  395. internalAssert c.config, result < regBxMax
  396. proc sameConstant*(a, b: PNode): bool =
  397. result = false
  398. if a == b:
  399. result = true
  400. elif a != nil and b != nil and a.kind == b.kind:
  401. case a.kind
  402. of nkSym: result = a.sym == b.sym
  403. of nkIdent: result = a.ident.id == b.ident.id
  404. of nkCharLit..nkUInt64Lit: result = a.intVal == b.intVal
  405. of nkFloatLit..nkFloat64Lit:
  406. result = cast[uint64](a.floatVal) == cast[uint64](b.floatVal)
  407. # refs bug #16469
  408. # if we wanted to only distinguish 0.0 vs -0.0:
  409. # if a.floatVal == 0.0: result = cast[uint64](a.floatVal) == cast[uint64](b.floatVal)
  410. # else: result = a.floatVal == b.floatVal
  411. of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal
  412. of nkType, nkNilLit: result = a.typ == b.typ
  413. of nkEmpty: result = true
  414. else:
  415. if a.len == b.len:
  416. for i in 0..<a.len:
  417. if not sameConstant(a[i], b[i]): return
  418. result = true
  419. proc genLiteral(c: PCtx; n: PNode): int =
  420. # types do not matter here:
  421. for i in 0..<c.constants.len:
  422. if sameConstant(c.constants[i], n): return i
  423. result = rawGenLiteral(c, n)
  424. proc unused(c: PCtx; n: PNode; x: TDest) {.inline.} =
  425. if x >= 0:
  426. #debug(n)
  427. globalError(c.config, n.info, "not unused")
  428. proc genCase(c: PCtx; n: PNode; dest: var TDest) =
  429. # if (!expr1) goto lab1;
  430. # thenPart
  431. # goto LEnd
  432. # lab1:
  433. # if (!expr2) goto lab2;
  434. # thenPart2
  435. # goto LEnd
  436. # lab2:
  437. # elsePart
  438. # Lend:
  439. if not isEmptyType(n.typ):
  440. if dest < 0: dest = getTemp(c, n.typ)
  441. else:
  442. unused(c, n, dest)
  443. var endings: seq[TPosition] = @[]
  444. withTemp(tmp, n[0].typ):
  445. c.gen(n[0], tmp)
  446. # branch tmp, codeIdx
  447. # fjmp elseLabel
  448. for i in 1..<n.len:
  449. let it = n[i]
  450. if it.len == 1:
  451. # else stmt:
  452. if it[0].kind != nkNilLit or it[0].typ != nil:
  453. # an nkNilLit with nil for typ implies there is no else branch, this
  454. # avoids unused related errors as we've already consumed the dest
  455. c.gen(it[0], dest)
  456. else:
  457. let b = rawGenLiteral(c, it)
  458. c.gABx(it, opcBranch, tmp, b)
  459. let elsePos = c.xjmp(it.lastSon, opcFJmp, tmp)
  460. c.gen(it.lastSon, dest)
  461. if i < n.len-1:
  462. endings.add(c.xjmp(it.lastSon, opcJmp, 0))
  463. c.patch(elsePos)
  464. c.clearDest(n, dest)
  465. for endPos in endings: c.patch(endPos)
  466. proc genType(c: PCtx; typ: PType): int =
  467. for i, t in c.types:
  468. if sameType(t, typ): return i
  469. result = c.types.len
  470. c.types.add(typ)
  471. internalAssert(c.config, result <= regBxMax)
  472. proc genTry(c: PCtx; n: PNode; dest: var TDest) =
  473. if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
  474. var endings: seq[TPosition] = @[]
  475. let ehPos = c.xjmp(n, opcTry, 0)
  476. c.gen(n[0], dest)
  477. c.clearDest(n, dest)
  478. # Add a jump past the exception handling code
  479. let jumpToFinally = c.xjmp(n, opcJmp, 0)
  480. # This signals where the body ends and where the exception handling begins
  481. c.patch(ehPos)
  482. for i in 1..<n.len:
  483. let it = n[i]
  484. if it.kind != nkFinally:
  485. # first opcExcept contains the end label of the 'except' block:
  486. let endExcept = c.xjmp(it, opcExcept, 0)
  487. for j in 0..<it.len - 1:
  488. assert(it[j].kind == nkType)
  489. let typ = it[j].typ.skipTypes(abstractPtrs-{tyTypeDesc})
  490. c.gABx(it, opcExcept, 0, c.genType(typ))
  491. if it.len == 1:
  492. # general except section:
  493. c.gABx(it, opcExcept, 0, 0)
  494. c.gen(it.lastSon, dest)
  495. c.clearDest(n, dest)
  496. if i < n.len:
  497. endings.add(c.xjmp(it, opcJmp, 0))
  498. c.patch(endExcept)
  499. let fin = lastSon(n)
  500. # we always generate an 'opcFinally' as that pops the safepoint
  501. # from the stack if no exception is raised in the body.
  502. c.patch(jumpToFinally)
  503. c.gABx(fin, opcFinally, 0, 0)
  504. for endPos in endings: c.patch(endPos)
  505. if fin.kind == nkFinally:
  506. c.gen(fin[0])
  507. c.clearDest(n, dest)
  508. c.gABx(fin, opcFinallyEnd, 0, 0)
  509. proc genRaise(c: PCtx; n: PNode) =
  510. let dest = genx(c, n[0])
  511. c.gABC(n, opcRaise, dest)
  512. c.freeTemp(dest)
  513. proc genReturn(c: PCtx; n: PNode) =
  514. if n[0].kind != nkEmpty:
  515. gen(c, n[0])
  516. c.gABC(n, opcRet)
  517. proc genLit(c: PCtx; n: PNode; dest: var TDest) =
  518. # opcLdConst is now always valid. We produce the necessary copy in the
  519. # assignments now:
  520. #var opc = opcLdConst
  521. if dest < 0: dest = c.getTemp(n.typ)
  522. #elif c.prc.regInfo[dest].kind == slotFixedVar: opc = opcAsgnConst
  523. let lit = genLiteral(c, n)
  524. c.gABx(n, opcLdConst, dest, lit)
  525. proc genCall(c: PCtx; n: PNode; dest: var TDest) =
  526. # it can happen that due to inlining we have a 'n' that should be
  527. # treated as a constant (see issue #537).
  528. #if n.typ != nil and n.typ.sym != nil and n.typ.sym.magic == mPNimrodNode:
  529. # genLit(c, n, dest)
  530. # return
  531. # bug #10901: do not produce code for wrong call expressions:
  532. if n.len == 0 or n[0].typ.isNil: return
  533. if dest < 0 and not isEmptyType(n.typ): dest = getTemp(c, n.typ)
  534. let x = c.getTempRange(n.len, slotTempUnknown)
  535. # varargs need 'opcSetType' for the FFI support:
  536. let fntyp = skipTypes(n[0].typ, abstractInst)
  537. for i in 0..<n.len:
  538. var r: TRegister = x+i
  539. c.gen(n[i], r, {gfIsParam})
  540. if i >= fntyp.len:
  541. internalAssert c.config, tfVarargs in fntyp.flags
  542. c.gABx(n, opcSetType, r, c.genType(n[i].typ))
  543. if dest < 0:
  544. c.gABC(n, opcIndCall, 0, x, n.len)
  545. else:
  546. c.gABC(n, opcIndCallAsgn, dest, x, n.len)
  547. c.freeTempRange(x, n.len)
  548. template isGlobal(s: PSym): bool = sfGlobal in s.flags and s.kind != skForVar
  549. proc isGlobal(n: PNode): bool = n.kind == nkSym and isGlobal(n.sym)
  550. proc needsAsgnPatch(n: PNode): bool =
  551. n.kind in {nkBracketExpr, nkDotExpr, nkCheckedFieldExpr,
  552. nkDerefExpr, nkHiddenDeref} or (n.kind == nkSym and n.sym.isGlobal)
  553. proc genField(c: PCtx; n: PNode): TRegister =
  554. if n.kind != nkSym or n.sym.kind != skField:
  555. globalError(c.config, n.info, "no field symbol")
  556. let s = n.sym
  557. if s.position > high(typeof(result)):
  558. globalError(c.config, n.info,
  559. "too large offset! cannot generate code for: " & s.name.s)
  560. result = s.position
  561. proc genIndex(c: PCtx; n: PNode; arr: PType): TRegister =
  562. if arr.skipTypes(abstractInst).kind == tyArray and (let x = firstOrd(c.config, arr);
  563. x != Zero):
  564. let tmp = c.genx(n)
  565. # freeing the temporary here means we can produce: regA = regA - Imm
  566. c.freeTemp(tmp)
  567. result = c.getTemp(n.typ)
  568. c.gABI(n, opcSubImmInt, result, tmp, toInt(x))
  569. else:
  570. result = c.genx(n)
  571. proc genCheckedObjAccessAux(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags)
  572. proc genAsgnPatch(c: PCtx; le: PNode, value: TRegister) =
  573. case le.kind
  574. of nkBracketExpr:
  575. let dest = c.genx(le[0], {gfNode})
  576. let idx = c.genIndex(le[1], le[0].typ)
  577. c.gABC(le, opcWrArr, dest, idx, value)
  578. c.freeTemp(dest)
  579. c.freeTemp(idx)
  580. of nkCheckedFieldExpr:
  581. var objR: TDest = -1
  582. genCheckedObjAccessAux(c, le, objR, {gfNode})
  583. let idx = genField(c, le[0][1])
  584. c.gABC(le[0], opcWrObj, objR, idx, value)
  585. c.freeTemp(objR)
  586. of nkDotExpr:
  587. let dest = c.genx(le[0], {gfNode})
  588. let idx = genField(c, le[1])
  589. c.gABC(le, opcWrObj, dest, idx, value)
  590. c.freeTemp(dest)
  591. of nkDerefExpr, nkHiddenDeref:
  592. let dest = c.genx(le[0], {gfNode})
  593. c.gABC(le, opcWrDeref, dest, 0, value)
  594. c.freeTemp(dest)
  595. of nkSym:
  596. if le.sym.isGlobal:
  597. let dest = c.genx(le, {gfNodeAddr})
  598. c.gABC(le, opcWrDeref, dest, 0, value)
  599. c.freeTemp(dest)
  600. else:
  601. discard
  602. proc genNew(c: PCtx; n: PNode) =
  603. let dest = if needsAsgnPatch(n[1]): c.getTemp(n[1].typ)
  604. else: c.genx(n[1])
  605. # we use the ref's base type here as the VM conflates 'ref object'
  606. # and 'object' since internally we already have a pointer.
  607. c.gABx(n, opcNew, dest,
  608. c.genType(n[1].typ.skipTypes(abstractVar-{tyTypeDesc})[0]))
  609. c.genAsgnPatch(n[1], dest)
  610. c.freeTemp(dest)
  611. proc genNewSeq(c: PCtx; n: PNode) =
  612. let t = n[1].typ
  613. let dest = if needsAsgnPatch(n[1]): c.getTemp(t)
  614. else: c.genx(n[1])
  615. let tmp = c.genx(n[2])
  616. c.gABx(n, opcNewSeq, dest, c.genType(t.skipTypes(
  617. abstractVar-{tyTypeDesc})))
  618. c.gABx(n, opcNewSeq, tmp, 0)
  619. c.freeTemp(tmp)
  620. c.genAsgnPatch(n[1], dest)
  621. c.freeTemp(dest)
  622. proc genNewSeqOfCap(c: PCtx; n: PNode; dest: var TDest) =
  623. let t = n.typ
  624. if dest < 0:
  625. dest = c.getTemp(n.typ)
  626. let tmp = c.getTemp(n[1].typ)
  627. c.gABx(n, opcLdNull, dest, c.genType(t))
  628. c.gABx(n, opcLdImmInt, tmp, 0)
  629. c.gABx(n, opcNewSeq, dest, c.genType(t.skipTypes(
  630. abstractVar-{tyTypeDesc})))
  631. c.gABx(n, opcNewSeq, tmp, 0)
  632. c.freeTemp(tmp)
  633. proc genUnaryABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  634. let tmp = c.genx(n[1])
  635. if dest < 0: dest = c.getTemp(n.typ)
  636. c.gABC(n, opc, dest, tmp)
  637. c.freeTemp(tmp)
  638. proc genUnaryABI(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode; imm: BiggestInt=0) =
  639. let tmp = c.genx(n[1])
  640. if dest < 0: dest = c.getTemp(n.typ)
  641. c.gABI(n, opc, dest, tmp, imm)
  642. c.freeTemp(tmp)
  643. proc genBinaryABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  644. let
  645. tmp = c.genx(n[1])
  646. tmp2 = c.genx(n[2])
  647. if dest < 0: dest = c.getTemp(n.typ)
  648. c.gABC(n, opc, dest, tmp, tmp2)
  649. c.freeTemp(tmp)
  650. c.freeTemp(tmp2)
  651. proc genBinaryABCD(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  652. let
  653. tmp = c.genx(n[1])
  654. tmp2 = c.genx(n[2])
  655. tmp3 = c.genx(n[3])
  656. if dest < 0: dest = c.getTemp(n.typ)
  657. c.gABC(n, opc, dest, tmp, tmp2)
  658. c.gABC(n, opc, tmp3)
  659. c.freeTemp(tmp)
  660. c.freeTemp(tmp2)
  661. c.freeTemp(tmp3)
  662. template sizeOfLikeMsg(name): string =
  663. "'$1' requires '.importc' types to be '.completeStruct'" % [name]
  664. proc genNarrow(c: PCtx; n: PNode; dest: TDest) =
  665. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  666. # uint is uint64 in the VM, we we only need to mask the result for
  667. # other unsigned types:
  668. let size = getSize(c.config, t)
  669. if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
  670. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  671. elif t.kind in {tyInt8..tyInt32} or (t.kind == tyInt and size < 8):
  672. c.gABC(n, opcNarrowS, dest, TRegister(size*8))
  673. proc genNarrowU(c: PCtx; n: PNode; dest: TDest) =
  674. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  675. # uint is uint64 in the VM, we we only need to mask the result for
  676. # other unsigned types:
  677. let size = getSize(c.config, t)
  678. if t.kind in {tyUInt8..tyUInt32, tyInt8..tyInt32} or
  679. (t.kind in {tyUInt, tyInt} and size < 8):
  680. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  681. proc genBinaryABCnarrow(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  682. genBinaryABC(c, n, dest, opc)
  683. genNarrow(c, n, dest)
  684. proc genBinaryABCnarrowU(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  685. genBinaryABC(c, n, dest, opc)
  686. genNarrowU(c, n, dest)
  687. proc genSetType(c: PCtx; n: PNode; dest: TRegister) =
  688. let t = skipTypes(n.typ, abstractInst-{tyTypeDesc})
  689. if t.kind == tySet:
  690. c.gABx(n, opcSetType, dest, c.genType(t))
  691. proc genBinarySet(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  692. let
  693. tmp = c.genx(n[1])
  694. tmp2 = c.genx(n[2])
  695. if dest < 0: dest = c.getTemp(n.typ)
  696. c.genSetType(n[1], tmp)
  697. c.genSetType(n[2], tmp2)
  698. c.gABC(n, opc, dest, tmp, tmp2)
  699. c.freeTemp(tmp)
  700. c.freeTemp(tmp2)
  701. proc genBinaryStmt(c: PCtx; n: PNode; opc: TOpcode) =
  702. let
  703. dest = c.genx(n[1])
  704. tmp = c.genx(n[2])
  705. c.gABC(n, opc, dest, tmp, 0)
  706. c.freeTemp(tmp)
  707. c.freeTemp(dest)
  708. proc genBinaryStmtVar(c: PCtx; n: PNode; opc: TOpcode) =
  709. var x = n[1]
  710. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  711. let
  712. dest = c.genx(x)
  713. tmp = c.genx(n[2])
  714. c.gABC(n, opc, dest, tmp, 0)
  715. #c.genAsgnPatch(n[1], dest)
  716. c.freeTemp(tmp)
  717. c.freeTemp(dest)
  718. proc genUnaryStmt(c: PCtx; n: PNode; opc: TOpcode) =
  719. let tmp = c.genx(n[1])
  720. c.gABC(n, opc, tmp, 0, 0)
  721. c.freeTemp(tmp)
  722. proc genVarargsABC(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  723. if dest < 0: dest = getTemp(c, n.typ)
  724. var x = c.getTempRange(n.len-1, slotTempStr)
  725. for i in 1..<n.len:
  726. var r: TRegister = x+i-1
  727. c.gen(n[i], r)
  728. c.gABC(n, opc, dest, x, n.len-1)
  729. c.freeTempRange(x, n.len-1)
  730. proc isInt8Lit(n: PNode): bool =
  731. if n.kind in {nkCharLit..nkUInt64Lit}:
  732. result = n.intVal >= low(int8) and n.intVal <= high(int8)
  733. proc isInt16Lit(n: PNode): bool =
  734. if n.kind in {nkCharLit..nkUInt64Lit}:
  735. result = n.intVal >= low(int16) and n.intVal <= high(int16)
  736. proc genAddSubInt(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode) =
  737. if n[2].isInt8Lit:
  738. let tmp = c.genx(n[1])
  739. if dest < 0: dest = c.getTemp(n.typ)
  740. c.gABI(n, succ(opc), dest, tmp, n[2].intVal)
  741. c.freeTemp(tmp)
  742. else:
  743. genBinaryABC(c, n, dest, opc)
  744. c.genNarrow(n, dest)
  745. proc genConv(c: PCtx; n, arg: PNode; dest: var TDest; opc=opcConv) =
  746. let t2 = n.typ.skipTypes({tyDistinct})
  747. let targ2 = arg.typ.skipTypes({tyDistinct})
  748. proc implicitConv(): bool =
  749. if sameType(t2, targ2): return true
  750. # xxx consider whether to use t2 and targ2 here
  751. if n.typ.kind == arg.typ.kind and arg.typ.kind == tyProc:
  752. # don't do anything for lambda lifting conversions:
  753. return true
  754. if implicitConv():
  755. gen(c, arg, dest)
  756. return
  757. let tmp = c.genx(arg)
  758. if dest < 0: dest = c.getTemp(n.typ)
  759. c.gABC(n, opc, dest, tmp)
  760. c.gABx(n, opc, 0, genType(c, n.typ.skipTypes({tyStatic})))
  761. c.gABx(n, opc, 0, genType(c, arg.typ.skipTypes({tyStatic})))
  762. c.freeTemp(tmp)
  763. proc genCard(c: PCtx; n: PNode; dest: var TDest) =
  764. let tmp = c.genx(n[1])
  765. if dest < 0: dest = c.getTemp(n.typ)
  766. c.genSetType(n[1], tmp)
  767. c.gABC(n, opcCard, dest, tmp)
  768. c.freeTemp(tmp)
  769. proc genCastIntFloat(c: PCtx; n: PNode; dest: var TDest) =
  770. const allowedIntegers = {tyInt..tyInt64, tyUInt..tyUInt64, tyChar}
  771. var signedIntegers = {tyInt..tyInt64}
  772. var unsignedIntegers = {tyUInt..tyUInt64, tyChar}
  773. let src = n[1].typ.skipTypes(abstractRange)#.kind
  774. let dst = n[0].typ.skipTypes(abstractRange)#.kind
  775. let srcSize = getSize(c.config, src)
  776. let dstSize = getSize(c.config, dst)
  777. if src.kind in allowedIntegers and dst.kind in allowedIntegers:
  778. let tmp = c.genx(n[1])
  779. if dest < 0: dest = c.getTemp(n[0].typ)
  780. c.gABC(n, opcAsgnInt, dest, tmp)
  781. if dstSize != sizeof(BiggestInt): # don't do anything on biggest int types
  782. if dst.kind in signedIntegers: # we need to do sign extensions
  783. if dstSize <= srcSize:
  784. # Sign extension can be omitted when the size increases.
  785. c.gABC(n, opcSignExtend, dest, TRegister(dstSize*8))
  786. elif dst.kind in unsignedIntegers:
  787. if src.kind in signedIntegers or dstSize < srcSize:
  788. # Cast from signed to unsigned always needs narrowing. Cast
  789. # from unsigned to unsigned only needs narrowing when target
  790. # is smaller than source.
  791. c.gABC(n, opcNarrowU, dest, TRegister(dstSize*8))
  792. c.freeTemp(tmp)
  793. elif srcSize == dstSize and src.kind in allowedIntegers and
  794. dst.kind in {tyFloat, tyFloat32, tyFloat64}:
  795. let tmp = c.genx(n[1])
  796. if dest < 0: dest = c.getTemp(n[0].typ)
  797. if dst.kind == tyFloat32:
  798. c.gABC(n, opcCastIntToFloat32, dest, tmp)
  799. else:
  800. c.gABC(n, opcCastIntToFloat64, dest, tmp)
  801. c.freeTemp(tmp)
  802. elif srcSize == dstSize and src.kind in {tyFloat, tyFloat32, tyFloat64} and
  803. dst.kind in allowedIntegers:
  804. let tmp = c.genx(n[1])
  805. if dest < 0: dest = c.getTemp(n[0].typ)
  806. if src.kind == tyFloat32:
  807. c.gABC(n, opcCastFloatToInt32, dest, tmp)
  808. if dst.kind in unsignedIntegers:
  809. # integers are sign extended by default.
  810. # since there is no opcCastFloatToUInt32, narrowing should do the trick.
  811. c.gABC(n, opcNarrowU, dest, TRegister(32))
  812. else:
  813. c.gABC(n, opcCastFloatToInt64, dest, tmp)
  814. # narrowing for 64 bits not needed (no extended sign bits available).
  815. c.freeTemp(tmp)
  816. elif src.kind in PtrLikeKinds + {tyRef} and dst.kind == tyInt:
  817. let tmp = c.genx(n[1])
  818. if dest < 0: dest = c.getTemp(n[0].typ)
  819. var imm: BiggestInt = if src.kind in PtrLikeKinds: 1 else: 2
  820. c.gABI(n, opcCastPtrToInt, dest, tmp, imm)
  821. c.freeTemp(tmp)
  822. elif src.kind in PtrLikeKinds + {tyInt} and dst.kind in PtrLikeKinds:
  823. let tmp = c.genx(n[1])
  824. if dest < 0: dest = c.getTemp(n[0].typ)
  825. c.gABx(n, opcSetType, dest, c.genType(dst))
  826. c.gABC(n, opcCastIntToPtr, dest, tmp)
  827. c.freeTemp(tmp)
  828. elif src.kind == tyNil and dst.kind in NilableTypes:
  829. # supports casting nil literals to NilableTypes in VM
  830. # see #16024
  831. if dest < 0: dest = c.getTemp(n[0].typ)
  832. genLit(c, n[1], dest)
  833. else:
  834. # todo: support cast from tyInt to tyRef
  835. globalError(c.config, n.info, "VM does not support 'cast' from " & $src.kind & " to " & $dst.kind)
  836. proc genVoidABC(c: PCtx, n: PNode, dest: TDest, opcode: TOpcode) =
  837. unused(c, n, dest)
  838. var
  839. tmp1 = c.genx(n[1])
  840. tmp2 = c.genx(n[2])
  841. tmp3 = c.genx(n[3])
  842. c.gABC(n, opcode, tmp1, tmp2, tmp3)
  843. c.freeTemp(tmp1)
  844. c.freeTemp(tmp2)
  845. c.freeTemp(tmp3)
  846. proc genBindSym(c: PCtx; n: PNode; dest: var TDest) =
  847. # nah, cannot use c.config.features because sempass context
  848. # can have local experimental switch
  849. # if dynamicBindSym notin c.config.features:
  850. if n.len == 2: # hmm, reliable?
  851. # bindSym with static input
  852. if n[1].kind in {nkClosedSymChoice, nkOpenSymChoice, nkSym}:
  853. let idx = c.genLiteral(n[1])
  854. if dest < 0: dest = c.getTemp(n.typ)
  855. c.gABx(n, opcNBindSym, dest, idx)
  856. else:
  857. localError(c.config, n.info, "invalid bindSym usage")
  858. else:
  859. # experimental bindSym
  860. if dest < 0: dest = c.getTemp(n.typ)
  861. let x = c.getTempRange(n.len, slotTempUnknown)
  862. # callee symbol
  863. var tmp0 = TDest(x)
  864. c.genLit(n[0], tmp0)
  865. # original parameters
  866. for i in 1..<n.len-2:
  867. var r = TRegister(x+i)
  868. c.gen(n[i], r)
  869. # info node
  870. var tmp1 = TDest(x+n.len-2)
  871. c.genLit(n[^2], tmp1)
  872. # payload idx
  873. var tmp2 = TDest(x+n.len-1)
  874. c.genLit(n[^1], tmp2)
  875. c.gABC(n, opcNDynBindSym, dest, x, n.len)
  876. c.freeTempRange(x, n.len)
  877. proc fitsRegister*(t: PType): bool =
  878. assert t != nil
  879. t.skipTypes(abstractInst + {tyStatic} - {tyTypeDesc}).kind in {
  880. tyRange, tyEnum, tyBool, tyInt..tyUInt64, tyChar}
  881. proc ldNullOpcode(t: PType): TOpcode =
  882. assert t != nil
  883. if fitsRegister(t): opcLdNullReg else: opcLdNull
  884. proc whichAsgnOpc(n: PNode; requiresCopy = true): TOpcode =
  885. case n.typ.skipTypes(abstractRange+{tyOwned}-{tyTypeDesc}).kind
  886. of tyBool, tyChar, tyEnum, tyOrdinal, tyInt..tyInt64, tyUInt..tyUInt64:
  887. opcAsgnInt
  888. of tyFloat..tyFloat128:
  889. opcAsgnFloat
  890. of tyRef, tyNil, tyVar, tyLent, tyPtr:
  891. opcAsgnRef
  892. else:
  893. (if requiresCopy: opcAsgnComplex else: opcFastAsgnComplex)
  894. proc genMagic(c: PCtx; n: PNode; dest: var TDest; m: TMagic) =
  895. case m
  896. of mAnd: c.genAndOr(n, opcFJmp, dest)
  897. of mOr: c.genAndOr(n, opcTJmp, dest)
  898. of mPred, mSubI:
  899. c.genAddSubInt(n, dest, opcSubInt)
  900. of mSucc, mAddI:
  901. c.genAddSubInt(n, dest, opcAddInt)
  902. of mInc, mDec:
  903. unused(c, n, dest)
  904. let isUnsigned = n[1].typ.skipTypes(abstractVarRange).kind in {tyUInt..tyUInt64}
  905. let opc = if not isUnsigned:
  906. if m == mInc: opcAddInt else: opcSubInt
  907. else:
  908. if m == mInc: opcAddu else: opcSubu
  909. let d = c.genx(n[1])
  910. if n[2].isInt8Lit and not isUnsigned:
  911. c.gABI(n, succ(opc), d, d, n[2].intVal)
  912. else:
  913. let tmp = c.genx(n[2])
  914. c.gABC(n, opc, d, d, tmp)
  915. c.freeTemp(tmp)
  916. c.genNarrow(n[1], d)
  917. c.genAsgnPatch(n[1], d)
  918. c.freeTemp(d)
  919. of mOrd, mChr, mArrToSeq, mUnown: c.gen(n[1], dest)
  920. of generatedMagics:
  921. genCall(c, n, dest)
  922. of mNew, mNewFinalize:
  923. unused(c, n, dest)
  924. c.genNew(n)
  925. of mNewSeq:
  926. unused(c, n, dest)
  927. c.genNewSeq(n)
  928. of mNewSeqOfCap: c.genNewSeqOfCap(n, dest)
  929. of mNewString:
  930. genUnaryABC(c, n, dest, opcNewStr)
  931. # XXX buggy
  932. of mNewStringOfCap:
  933. # we ignore the 'cap' argument and translate it as 'newString(0)'.
  934. # eval n[1] for possible side effects:
  935. c.freeTemp(c.genx(n[1]))
  936. var tmp = c.getTemp(n[1].typ)
  937. c.gABx(n, opcLdImmInt, tmp, 0)
  938. if dest < 0: dest = c.getTemp(n.typ)
  939. c.gABC(n, opcNewStr, dest, tmp)
  940. c.freeTemp(tmp)
  941. # XXX buggy
  942. of mLengthOpenArray, mLengthArray, mLengthSeq:
  943. genUnaryABI(c, n, dest, opcLenSeq)
  944. of mLengthStr:
  945. case n[1].typ.kind
  946. of tyString: genUnaryABI(c, n, dest, opcLenStr)
  947. of tyCstring: genUnaryABI(c, n, dest, opcLenCstring)
  948. else: doAssert false, $n[1].typ.kind
  949. of mIncl, mExcl:
  950. unused(c, n, dest)
  951. var d = c.genx(n[1])
  952. var tmp = c.genx(n[2])
  953. c.genSetType(n[1], d)
  954. c.gABC(n, if m == mIncl: opcIncl else: opcExcl, d, tmp)
  955. c.freeTemp(d)
  956. c.freeTemp(tmp)
  957. of mCard: genCard(c, n, dest)
  958. of mMulI: genBinaryABCnarrow(c, n, dest, opcMulInt)
  959. of mDivI: genBinaryABCnarrow(c, n, dest, opcDivInt)
  960. of mModI: genBinaryABCnarrow(c, n, dest, opcModInt)
  961. of mAddF64: genBinaryABC(c, n, dest, opcAddFloat)
  962. of mSubF64: genBinaryABC(c, n, dest, opcSubFloat)
  963. of mMulF64: genBinaryABC(c, n, dest, opcMulFloat)
  964. of mDivF64: genBinaryABC(c, n, dest, opcDivFloat)
  965. of mShrI:
  966. # modified: genBinaryABC(c, n, dest, opcShrInt)
  967. # narrowU is applied to the left operandthe idea here is to narrow the left operand
  968. let tmp = c.genx(n[1])
  969. c.genNarrowU(n, tmp)
  970. let tmp2 = c.genx(n[2])
  971. if dest < 0: dest = c.getTemp(n.typ)
  972. c.gABC(n, opcShrInt, dest, tmp, tmp2)
  973. c.freeTemp(tmp)
  974. c.freeTemp(tmp2)
  975. of mShlI:
  976. genBinaryABC(c, n, dest, opcShlInt)
  977. # genNarrowU modified
  978. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  979. let size = getSize(c.config, t)
  980. if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
  981. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  982. elif t.kind in {tyInt8..tyInt32} or (t.kind == tyInt and size < 8):
  983. c.gABC(n, opcSignExtend, dest, TRegister(size*8))
  984. of mAshrI: genBinaryABC(c, n, dest, opcAshrInt)
  985. of mBitandI: genBinaryABC(c, n, dest, opcBitandInt)
  986. of mBitorI: genBinaryABC(c, n, dest, opcBitorInt)
  987. of mBitxorI: genBinaryABC(c, n, dest, opcBitxorInt)
  988. of mAddU: genBinaryABCnarrowU(c, n, dest, opcAddu)
  989. of mSubU: genBinaryABCnarrowU(c, n, dest, opcSubu)
  990. of mMulU: genBinaryABCnarrowU(c, n, dest, opcMulu)
  991. of mDivU: genBinaryABCnarrowU(c, n, dest, opcDivu)
  992. of mModU: genBinaryABCnarrowU(c, n, dest, opcModu)
  993. of mEqI, mEqB, mEqEnum, mEqCh:
  994. genBinaryABC(c, n, dest, opcEqInt)
  995. of mLeI, mLeEnum, mLeCh, mLeB:
  996. genBinaryABC(c, n, dest, opcLeInt)
  997. of mLtI, mLtEnum, mLtCh, mLtB:
  998. genBinaryABC(c, n, dest, opcLtInt)
  999. of mEqF64: genBinaryABC(c, n, dest, opcEqFloat)
  1000. of mLeF64: genBinaryABC(c, n, dest, opcLeFloat)
  1001. of mLtF64: genBinaryABC(c, n, dest, opcLtFloat)
  1002. of mLePtr, mLeU: genBinaryABC(c, n, dest, opcLeu)
  1003. of mLtPtr, mLtU: genBinaryABC(c, n, dest, opcLtu)
  1004. of mEqProc, mEqRef:
  1005. genBinaryABC(c, n, dest, opcEqRef)
  1006. of mXor: genBinaryABC(c, n, dest, opcXor)
  1007. of mNot: genUnaryABC(c, n, dest, opcNot)
  1008. of mUnaryMinusI, mUnaryMinusI64:
  1009. genUnaryABC(c, n, dest, opcUnaryMinusInt)
  1010. genNarrow(c, n, dest)
  1011. of mUnaryMinusF64: genUnaryABC(c, n, dest, opcUnaryMinusFloat)
  1012. of mUnaryPlusI, mUnaryPlusF64: gen(c, n[1], dest)
  1013. of mBitnotI:
  1014. genUnaryABC(c, n, dest, opcBitnotInt)
  1015. #genNarrowU modified, do not narrow signed types
  1016. let t = skipTypes(n.typ, abstractVar-{tyTypeDesc})
  1017. let size = getSize(c.config, t)
  1018. if t.kind in {tyUInt8..tyUInt32} or (t.kind == tyUInt and size < 8):
  1019. c.gABC(n, opcNarrowU, dest, TRegister(size*8))
  1020. of mCharToStr, mBoolToStr, mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr, mStrToStr, mEnumToStr:
  1021. genConv(c, n, n[1], dest)
  1022. of mEqStr, mEqCString: genBinaryABC(c, n, dest, opcEqStr)
  1023. of mLeStr: genBinaryABC(c, n, dest, opcLeStr)
  1024. of mLtStr: genBinaryABC(c, n, dest, opcLtStr)
  1025. of mEqSet: genBinarySet(c, n, dest, opcEqSet)
  1026. of mLeSet: genBinarySet(c, n, dest, opcLeSet)
  1027. of mLtSet: genBinarySet(c, n, dest, opcLtSet)
  1028. of mMulSet: genBinarySet(c, n, dest, opcMulSet)
  1029. of mPlusSet: genBinarySet(c, n, dest, opcPlusSet)
  1030. of mMinusSet: genBinarySet(c, n, dest, opcMinusSet)
  1031. of mConStrStr: genVarargsABC(c, n, dest, opcConcatStr)
  1032. of mInSet: genBinarySet(c, n, dest, opcContainsSet)
  1033. of mRepr: genUnaryABC(c, n, dest, opcRepr)
  1034. of mExit:
  1035. unused(c, n, dest)
  1036. var tmp = c.genx(n[1])
  1037. c.gABC(n, opcQuit, tmp)
  1038. c.freeTemp(tmp)
  1039. of mSetLengthStr, mSetLengthSeq:
  1040. unused(c, n, dest)
  1041. var d = c.genx(n[1])
  1042. var tmp = c.genx(n[2])
  1043. c.gABC(n, if m == mSetLengthStr: opcSetLenStr else: opcSetLenSeq, d, tmp)
  1044. c.genAsgnPatch(n[1], d)
  1045. c.freeTemp(tmp)
  1046. c.freeTemp(d)
  1047. of mSwap:
  1048. unused(c, n, dest)
  1049. c.gen(lowerSwap(c.graph, n, c.idgen, if c.prc == nil or c.prc.sym == nil: c.module else: c.prc.sym))
  1050. of mIsNil: genUnaryABC(c, n, dest, opcIsNil)
  1051. of mParseBiggestFloat:
  1052. if dest < 0: dest = c.getTemp(n.typ)
  1053. var d2: TRegister
  1054. # skip 'nkHiddenAddr':
  1055. let d2AsNode = n[2][0]
  1056. if needsAsgnPatch(d2AsNode):
  1057. d2 = c.getTemp(getSysType(c.graph, n.info, tyFloat))
  1058. else:
  1059. d2 = c.genx(d2AsNode)
  1060. var
  1061. tmp1 = c.genx(n[1])
  1062. tmp3 = c.genx(n[3])
  1063. c.gABC(n, opcParseFloat, dest, tmp1, d2)
  1064. c.gABC(n, opcParseFloat, tmp3)
  1065. c.freeTemp(tmp1)
  1066. c.freeTemp(tmp3)
  1067. c.genAsgnPatch(d2AsNode, d2)
  1068. c.freeTemp(d2)
  1069. of mReset:
  1070. unused(c, n, dest)
  1071. var d = c.genx(n[1])
  1072. # XXX use ldNullOpcode() here?
  1073. c.gABx(n, opcLdNull, d, c.genType(n[1].typ))
  1074. c.gABx(n, opcNodeToReg, d, d)
  1075. c.genAsgnPatch(n[1], d)
  1076. of mDefault, mZeroDefault:
  1077. if dest < 0: dest = c.getTemp(n.typ)
  1078. c.gABx(n, ldNullOpcode(n.typ), dest, c.genType(n.typ))
  1079. of mOf, mIs:
  1080. if dest < 0: dest = c.getTemp(n.typ)
  1081. var tmp = c.genx(n[1])
  1082. var idx = c.getTemp(getSysType(c.graph, n.info, tyInt))
  1083. var typ = n[2].typ
  1084. if m == mOf: typ = typ.skipTypes(abstractPtrs)
  1085. c.gABx(n, opcLdImmInt, idx, c.genType(typ))
  1086. c.gABC(n, if m == mOf: opcOf else: opcIs, dest, tmp, idx)
  1087. c.freeTemp(tmp)
  1088. c.freeTemp(idx)
  1089. of mHigh:
  1090. if dest < 0: dest = c.getTemp(n.typ)
  1091. let tmp = c.genx(n[1])
  1092. case n[1].typ.skipTypes(abstractVar-{tyTypeDesc}).kind:
  1093. of tyString: c.gABI(n, opcLenStr, dest, tmp, 1)
  1094. of tyCstring: c.gABI(n, opcLenCstring, dest, tmp, 1)
  1095. else: c.gABI(n, opcLenSeq, dest, tmp, 1)
  1096. c.freeTemp(tmp)
  1097. of mEcho:
  1098. unused(c, n, dest)
  1099. let n = n[1].skipConv
  1100. if n.kind == nkBracket:
  1101. # can happen for nim check, see bug #9609
  1102. let x = c.getTempRange(n.len, slotTempUnknown)
  1103. for i in 0..<n.len:
  1104. var r: TRegister = x+i
  1105. c.gen(n[i], r)
  1106. c.gABC(n, opcEcho, x, n.len)
  1107. c.freeTempRange(x, n.len)
  1108. of mAppendStrCh:
  1109. unused(c, n, dest)
  1110. genBinaryStmtVar(c, n, opcAddStrCh)
  1111. of mAppendStrStr:
  1112. unused(c, n, dest)
  1113. genBinaryStmtVar(c, n, opcAddStrStr)
  1114. of mAppendSeqElem:
  1115. unused(c, n, dest)
  1116. genBinaryStmtVar(c, n, opcAddSeqElem)
  1117. of mParseExprToAst:
  1118. genBinaryABC(c, n, dest, opcParseExprToAst)
  1119. of mParseStmtToAst:
  1120. genBinaryABC(c, n, dest, opcParseStmtToAst)
  1121. of mTypeTrait:
  1122. let tmp = c.genx(n[1])
  1123. if dest < 0: dest = c.getTemp(n.typ)
  1124. c.gABx(n, opcSetType, tmp, c.genType(n[1].typ))
  1125. c.gABC(n, opcTypeTrait, dest, tmp)
  1126. c.freeTemp(tmp)
  1127. of mSlurp: genUnaryABC(c, n, dest, opcSlurp)
  1128. of mStaticExec: genBinaryABCD(c, n, dest, opcGorge)
  1129. of mNLen: genUnaryABI(c, n, dest, opcLenSeq, nimNodeFlag)
  1130. of mGetImpl: genUnaryABC(c, n, dest, opcGetImpl)
  1131. of mGetImplTransf: genUnaryABC(c, n, dest, opcGetImplTransf)
  1132. of mSymOwner: genUnaryABC(c, n, dest, opcSymOwner)
  1133. of mSymIsInstantiationOf: genBinaryABC(c, n, dest, opcSymIsInstantiationOf)
  1134. of mNChild: genBinaryABC(c, n, dest, opcNChild)
  1135. of mNSetChild: genVoidABC(c, n, dest, opcNSetChild)
  1136. of mNDel: genVoidABC(c, n, dest, opcNDel)
  1137. of mNAdd: genBinaryABC(c, n, dest, opcNAdd)
  1138. of mNAddMultiple: genBinaryABC(c, n, dest, opcNAddMultiple)
  1139. of mNKind: genUnaryABC(c, n, dest, opcNKind)
  1140. of mNSymKind: genUnaryABC(c, n, dest, opcNSymKind)
  1141. of mNccValue: genUnaryABC(c, n, dest, opcNccValue)
  1142. of mNccInc: genBinaryABC(c, n, dest, opcNccInc)
  1143. of mNcsAdd: genBinaryABC(c, n, dest, opcNcsAdd)
  1144. of mNcsIncl: genBinaryABC(c, n, dest, opcNcsIncl)
  1145. of mNcsLen: genUnaryABC(c, n, dest, opcNcsLen)
  1146. of mNcsAt: genBinaryABC(c, n, dest, opcNcsAt)
  1147. of mNctPut: genVoidABC(c, n, dest, opcNctPut)
  1148. of mNctLen: genUnaryABC(c, n, dest, opcNctLen)
  1149. of mNctGet: genBinaryABC(c, n, dest, opcNctGet)
  1150. of mNctHasNext: genBinaryABC(c, n, dest, opcNctHasNext)
  1151. of mNctNext: genBinaryABC(c, n, dest, opcNctNext)
  1152. of mNIntVal: genUnaryABC(c, n, dest, opcNIntVal)
  1153. of mNFloatVal: genUnaryABC(c, n, dest, opcNFloatVal)
  1154. of mNSymbol: genUnaryABC(c, n, dest, opcNSymbol)
  1155. of mNIdent: genUnaryABC(c, n, dest, opcNIdent)
  1156. of mNGetType:
  1157. let tmp = c.genx(n[1])
  1158. if dest < 0: dest = c.getTemp(n.typ)
  1159. let rc = case n[0].sym.name.s:
  1160. of "getType": 0
  1161. of "typeKind": 1
  1162. of "getTypeInst": 2
  1163. else: 3 # "getTypeImpl"
  1164. c.gABC(n, opcNGetType, dest, tmp, rc)
  1165. c.freeTemp(tmp)
  1166. #genUnaryABC(c, n, dest, opcNGetType)
  1167. of mNSizeOf:
  1168. let imm = case n[0].sym.name.s:
  1169. of "getSize": 0
  1170. of "getAlign": 1
  1171. else: 2 # "getOffset"
  1172. c.genUnaryABI(n, dest, opcNGetSize, imm)
  1173. of mNStrVal: genUnaryABC(c, n, dest, opcNStrVal)
  1174. of mNSigHash: genUnaryABC(c, n , dest, opcNSigHash)
  1175. of mNSetIntVal:
  1176. unused(c, n, dest)
  1177. genBinaryStmt(c, n, opcNSetIntVal)
  1178. of mNSetFloatVal:
  1179. unused(c, n, dest)
  1180. genBinaryStmt(c, n, opcNSetFloatVal)
  1181. of mNSetSymbol:
  1182. unused(c, n, dest)
  1183. genBinaryStmt(c, n, opcNSetSymbol)
  1184. of mNSetIdent:
  1185. unused(c, n, dest)
  1186. genBinaryStmt(c, n, opcNSetIdent)
  1187. of mNSetType:
  1188. unused(c, n, dest)
  1189. genBinaryStmt(c, n, opcNSetType)
  1190. of mNSetStrVal:
  1191. unused(c, n, dest)
  1192. genBinaryStmt(c, n, opcNSetStrVal)
  1193. of mNNewNimNode: genBinaryABC(c, n, dest, opcNNewNimNode)
  1194. of mNCopyNimNode: genUnaryABC(c, n, dest, opcNCopyNimNode)
  1195. of mNCopyNimTree: genUnaryABC(c, n, dest, opcNCopyNimTree)
  1196. of mNBindSym: genBindSym(c, n, dest)
  1197. of mStrToIdent: genUnaryABC(c, n, dest, opcStrToIdent)
  1198. of mEqIdent: genBinaryABC(c, n, dest, opcEqIdent)
  1199. of mEqNimrodNode: genBinaryABC(c, n, dest, opcEqNimNode)
  1200. of mSameNodeType: genBinaryABC(c, n, dest, opcSameNodeType)
  1201. of mNLineInfo:
  1202. case n[0].sym.name.s
  1203. of "getFile": genUnaryABI(c, n, dest, opcNGetLineInfo, 0)
  1204. of "getLine": genUnaryABI(c, n, dest, opcNGetLineInfo, 1)
  1205. of "getColumn": genUnaryABI(c, n, dest, opcNGetLineInfo, 2)
  1206. of "copyLineInfo":
  1207. internalAssert c.config, n.len == 3
  1208. unused(c, n, dest)
  1209. genBinaryStmt(c, n, opcNSetLineInfo)
  1210. else: internalAssert c.config, false
  1211. of mNHint:
  1212. unused(c, n, dest)
  1213. genBinaryStmt(c, n, opcNHint)
  1214. of mNWarning:
  1215. unused(c, n, dest)
  1216. genBinaryStmt(c, n, opcNWarning)
  1217. of mNError:
  1218. if n.len <= 1:
  1219. # query error condition:
  1220. c.gABC(n, opcQueryErrorFlag, dest)
  1221. else:
  1222. # setter
  1223. unused(c, n, dest)
  1224. genBinaryStmt(c, n, opcNError)
  1225. of mNCallSite:
  1226. if dest < 0: dest = c.getTemp(n.typ)
  1227. c.gABC(n, opcCallSite, dest)
  1228. of mNGenSym: genBinaryABC(c, n, dest, opcGenSym)
  1229. of mMinI, mMaxI, mAbsI, mDotDot:
  1230. c.genCall(n, dest)
  1231. of mExpandToAst:
  1232. if n.len != 2:
  1233. globalError(c.config, n.info, "expandToAst requires 1 argument")
  1234. let arg = n[1]
  1235. if arg.kind in nkCallKinds:
  1236. #if arg[0].kind != nkSym or arg[0].sym.kind notin {skTemplate, skMacro}:
  1237. # "ExpandToAst: expanded symbol is no macro or template"
  1238. if dest < 0: dest = c.getTemp(n.typ)
  1239. c.genCall(arg, dest)
  1240. # do not call clearDest(n, dest) here as getAst has a meta-type as such
  1241. # produces a value
  1242. else:
  1243. globalError(c.config, n.info, "expandToAst requires a call expression")
  1244. of mSizeOf:
  1245. globalError(c.config, n.info, sizeOfLikeMsg("sizeof"))
  1246. of mAlignOf:
  1247. globalError(c.config, n.info, sizeOfLikeMsg("alignof"))
  1248. of mOffsetOf:
  1249. globalError(c.config, n.info, sizeOfLikeMsg("offsetof"))
  1250. of mRunnableExamples:
  1251. discard "just ignore any call to runnableExamples"
  1252. of mDestroy, mTrace: discard "ignore calls to the default destructor"
  1253. of mMove:
  1254. let arg = n[1]
  1255. let a = c.genx(arg)
  1256. if dest < 0: dest = c.getTemp(arg.typ)
  1257. gABC(c, arg, whichAsgnOpc(arg, requiresCopy=false), dest, a)
  1258. # XXX use ldNullOpcode() here?
  1259. # Don't zero out the arg for now #17199
  1260. # c.gABx(n, opcLdNull, a, c.genType(arg.typ))
  1261. # c.gABx(n, opcNodeToReg, a, a)
  1262. # c.genAsgnPatch(arg, a)
  1263. c.freeTemp(a)
  1264. of mNodeId:
  1265. c.genUnaryABC(n, dest, opcNodeId)
  1266. else:
  1267. # mGCref, mGCunref,
  1268. globalError(c.config, n.info, "cannot generate code for: " & $m)
  1269. proc unneededIndirection(n: PNode): bool =
  1270. n.typ.skipTypes(abstractInstOwned-{tyTypeDesc}).kind == tyRef
  1271. proc canElimAddr(n: PNode): PNode =
  1272. case n[0].kind
  1273. of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
  1274. var m = n[0][0]
  1275. if m.kind in {nkDerefExpr, nkHiddenDeref}:
  1276. # addr ( nkConv ( deref ( x ) ) ) --> nkConv(x)
  1277. result = copyNode(n[0])
  1278. result.add m[0]
  1279. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  1280. var m = n[0][1]
  1281. if m.kind in {nkDerefExpr, nkHiddenDeref}:
  1282. # addr ( nkConv ( deref ( x ) ) ) --> nkConv(x)
  1283. result = copyNode(n[0])
  1284. result.add m[0]
  1285. else:
  1286. if n[0].kind in {nkDerefExpr, nkHiddenDeref}:
  1287. # addr ( deref ( x )) --> x
  1288. result = n[0][0]
  1289. proc genAddr(c: PCtx, n: PNode, dest: var TDest, flags: TGenFlags) =
  1290. if (let m = canElimAddr(n); m != nil):
  1291. gen(c, m, dest, flags)
  1292. return
  1293. let newflags = flags-{gfNode}+{gfNodeAddr}
  1294. if isGlobal(n[0]) or n[0].kind in {nkDotExpr, nkCheckedFieldExpr, nkBracketExpr}:
  1295. # checking for this pattern: addr(obj.field) / addr(array[i])
  1296. gen(c, n[0], dest, newflags)
  1297. else:
  1298. let tmp = c.genx(n[0], newflags)
  1299. if dest < 0: dest = c.getTemp(n.typ)
  1300. if c.prc.regInfo[tmp].kind >= slotTempUnknown:
  1301. gABC(c, n, opcAddrNode, dest, tmp)
  1302. # hack ahead; in order to fix bug #1781 we mark the temporary as
  1303. # permanent, so that it's not used for anything else:
  1304. c.prc.regInfo[tmp].kind = slotTempPerm
  1305. # XXX this is still a hack
  1306. #message(c.congig, n.info, warnUser, "suspicious opcode used")
  1307. else:
  1308. gABC(c, n, opcAddrReg, dest, tmp)
  1309. c.freeTemp(tmp)
  1310. proc genDeref(c: PCtx, n: PNode, dest: var TDest, flags: TGenFlags) =
  1311. if unneededIndirection(n[0]):
  1312. gen(c, n[0], dest, flags)
  1313. if {gfNodeAddr, gfNode} * flags == {} and fitsRegister(n.typ):
  1314. c.gABC(n, opcNodeToReg, dest, dest)
  1315. else:
  1316. let tmp = c.genx(n[0], flags)
  1317. if dest < 0: dest = c.getTemp(n.typ)
  1318. gABC(c, n, opcLdDeref, dest, tmp)
  1319. assert n.typ != nil
  1320. if {gfNodeAddr, gfNode} * flags == {} and fitsRegister(n.typ):
  1321. c.gABC(n, opcNodeToReg, dest, dest)
  1322. c.freeTemp(tmp)
  1323. proc genAsgn(c: PCtx; dest: TDest; ri: PNode; requiresCopy: bool) =
  1324. let tmp = c.genx(ri)
  1325. assert dest >= 0
  1326. gABC(c, ri, whichAsgnOpc(ri, requiresCopy), dest, tmp)
  1327. c.freeTemp(tmp)
  1328. proc setSlot(c: PCtx; v: PSym) =
  1329. # XXX generate type initialization here?
  1330. if v.position == 0:
  1331. v.position = getFreeRegister(c, if v.kind == skLet: slotFixedLet else: slotFixedVar, start = 1)
  1332. proc cannotEval(c: PCtx; n: PNode) {.noinline.} =
  1333. globalError(c.config, n.info, "cannot evaluate at compile time: " &
  1334. n.renderTree)
  1335. proc isOwnedBy(a, b: PSym): bool =
  1336. var a = a.owner
  1337. while a != nil and a.kind != skModule:
  1338. if a == b: return true
  1339. a = a.owner
  1340. proc getOwner(c: PCtx): PSym =
  1341. result = c.prc.sym
  1342. if result.isNil: result = c.module
  1343. proc importcCondVar*(s: PSym): bool {.inline.} =
  1344. # see also importcCond
  1345. if sfImportc in s.flags:
  1346. return s.kind in {skVar, skLet, skConst}
  1347. proc checkCanEval(c: PCtx; n: PNode) =
  1348. # we need to ensure that we don't evaluate 'x' here:
  1349. # proc foo() = var x ...
  1350. let s = n.sym
  1351. if {sfCompileTime, sfGlobal} <= s.flags: return
  1352. if compiletimeFFI in c.config.features and s.importcCondVar: return
  1353. if s.kind in {skVar, skTemp, skLet, skParam, skResult} and
  1354. not s.isOwnedBy(c.prc.sym) and s.owner != c.module and c.mode != emRepl:
  1355. # little hack ahead for bug #12612: assume gensym'ed variables
  1356. # are in the right scope:
  1357. if sfGenSym in s.flags and c.prc.sym == nil: discard
  1358. else: cannotEval(c, n)
  1359. elif s.kind in {skProc, skFunc, skConverter, skMethod,
  1360. skIterator} and sfForward in s.flags:
  1361. cannotEval(c, n)
  1362. template needsAdditionalCopy(n): untyped =
  1363. not c.isTemp(dest) and not fitsRegister(n.typ)
  1364. proc genAdditionalCopy(c: PCtx; n: PNode; opc: TOpcode;
  1365. dest, idx, value: TRegister) =
  1366. var cc = c.getTemp(n.typ)
  1367. c.gABC(n, whichAsgnOpc(n), cc, value)
  1368. c.gABC(n, opc, dest, idx, cc)
  1369. c.freeTemp(cc)
  1370. proc preventFalseAlias(c: PCtx; n: PNode; opc: TOpcode;
  1371. dest, idx, value: TRegister) =
  1372. # opcLdObj et al really means "load address". We sometimes have to create a
  1373. # copy in order to not introduce false aliasing:
  1374. # mylocal = a.b # needs a copy of the data!
  1375. assert n.typ != nil
  1376. if needsAdditionalCopy(n):
  1377. genAdditionalCopy(c, n, opc, dest, idx, value)
  1378. else:
  1379. c.gABC(n, opc, dest, idx, value)
  1380. proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) =
  1381. case le.kind
  1382. of nkBracketExpr:
  1383. let dest = c.genx(le[0], {gfNode})
  1384. let idx = c.genIndex(le[1], le[0].typ)
  1385. let tmp = c.genx(ri)
  1386. if le[0].typ.skipTypes(abstractVarRange-{tyTypeDesc}).kind in {
  1387. tyString, tyCstring}:
  1388. c.preventFalseAlias(le, opcWrStrIdx, dest, idx, tmp)
  1389. else:
  1390. c.preventFalseAlias(le, opcWrArr, dest, idx, tmp)
  1391. c.freeTemp(tmp)
  1392. c.freeTemp(idx)
  1393. c.freeTemp(dest)
  1394. of nkCheckedFieldExpr:
  1395. var objR: TDest = -1
  1396. genCheckedObjAccessAux(c, le, objR, {gfNode})
  1397. let idx = genField(c, le[0][1])
  1398. let tmp = c.genx(ri)
  1399. c.preventFalseAlias(le[0], opcWrObj, objR, idx, tmp)
  1400. c.freeTemp(tmp)
  1401. # c.freeTemp(idx) # BUGFIX, see nkDotExpr
  1402. c.freeTemp(objR)
  1403. of nkDotExpr:
  1404. let dest = c.genx(le[0], {gfNode})
  1405. let idx = genField(c, le[1])
  1406. let tmp = c.genx(ri)
  1407. c.preventFalseAlias(le, opcWrObj, dest, idx, tmp)
  1408. # c.freeTemp(idx) # BUGFIX: idx is an immediate (field position), not a register
  1409. c.freeTemp(tmp)
  1410. c.freeTemp(dest)
  1411. of nkDerefExpr, nkHiddenDeref:
  1412. let dest = c.genx(le[0], {gfNode})
  1413. let tmp = c.genx(ri)
  1414. c.preventFalseAlias(le, opcWrDeref, dest, 0, tmp)
  1415. c.freeTemp(dest)
  1416. c.freeTemp(tmp)
  1417. of nkSym:
  1418. let s = le.sym
  1419. checkCanEval(c, le)
  1420. if s.isGlobal:
  1421. withTemp(tmp, le.typ):
  1422. c.gen(le, tmp, {gfNodeAddr})
  1423. let val = c.genx(ri)
  1424. c.preventFalseAlias(le, opcWrDeref, tmp, 0, val)
  1425. c.freeTemp(val)
  1426. else:
  1427. if s.kind == skForVar: c.setSlot s
  1428. internalAssert c.config, s.position > 0 or (s.position == 0 and
  1429. s.kind in {skParam, skResult})
  1430. var dest: TRegister = s.position + ord(s.kind == skParam)
  1431. assert le.typ != nil
  1432. if needsAdditionalCopy(le) and s.kind in {skResult, skVar, skParam}:
  1433. var cc = c.getTemp(le.typ)
  1434. gen(c, ri, cc)
  1435. c.gABC(le, whichAsgnOpc(le), dest, cc)
  1436. c.freeTemp(cc)
  1437. else:
  1438. gen(c, ri, dest)
  1439. else:
  1440. let dest = c.genx(le, {gfNodeAddr})
  1441. genAsgn(c, dest, ri, requiresCopy)
  1442. c.freeTemp(dest)
  1443. proc genTypeLit(c: PCtx; t: PType; dest: var TDest) =
  1444. var n = newNode(nkType)
  1445. n.typ = t
  1446. genLit(c, n, dest)
  1447. proc importcCond*(c: PCtx; s: PSym): bool {.inline.} =
  1448. ## return true to importc `s`, false to execute its body instead (refs #8405)
  1449. if sfImportc in s.flags:
  1450. if s.kind in routineKinds:
  1451. return getBody(c.graph, s).kind == nkEmpty
  1452. proc importcSym(c: PCtx; info: TLineInfo; s: PSym) =
  1453. when hasFFI:
  1454. if compiletimeFFI in c.config.features:
  1455. c.globals.add(importcSymbol(c.config, s))
  1456. s.position = c.globals.len
  1457. else:
  1458. localError(c.config, info,
  1459. "VM is not allowed to 'importc' without --experimental:compiletimeFFI")
  1460. else:
  1461. localError(c.config, info,
  1462. "cannot 'importc' variable at compile time; " & s.name.s)
  1463. proc getNullValue*(typ: PType, info: TLineInfo; conf: ConfigRef): PNode
  1464. proc genGlobalInit(c: PCtx; n: PNode; s: PSym) =
  1465. c.globals.add(getNullValue(s.typ, n.info, c.config))
  1466. s.position = c.globals.len
  1467. # This is rather hard to support, due to the laziness of the VM code
  1468. # generator. See tests/compile/tmacro2 for why this is necessary:
  1469. # var decls{.compileTime.}: seq[NimNode] = @[]
  1470. let dest = c.getTemp(s.typ)
  1471. c.gABx(n, opcLdGlobal, dest, s.position)
  1472. if s.astdef != nil:
  1473. let tmp = c.genx(s.astdef)
  1474. c.genAdditionalCopy(n, opcWrDeref, dest, 0, tmp)
  1475. c.freeTemp(dest)
  1476. c.freeTemp(tmp)
  1477. proc genRdVar(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1478. # gfNodeAddr and gfNode are mutually exclusive
  1479. assert card(flags * {gfNodeAddr, gfNode}) < 2
  1480. let s = n.sym
  1481. if s.isGlobal:
  1482. let isImportcVar = importcCondVar(s)
  1483. if sfCompileTime in s.flags or c.mode == emRepl or isImportcVar:
  1484. discard
  1485. elif s.position == 0:
  1486. cannotEval(c, n)
  1487. if s.position == 0:
  1488. if importcCond(c, s) or isImportcVar: c.importcSym(n.info, s)
  1489. else: genGlobalInit(c, n, s)
  1490. if dest < 0: dest = c.getTemp(n.typ)
  1491. assert s.typ != nil
  1492. if gfNodeAddr in flags:
  1493. if isImportcVar:
  1494. c.gABx(n, opcLdGlobalAddrDerefFFI, dest, s.position)
  1495. else:
  1496. c.gABx(n, opcLdGlobalAddr, dest, s.position)
  1497. elif isImportcVar:
  1498. c.gABx(n, opcLdGlobalDerefFFI, dest, s.position)
  1499. elif fitsRegister(s.typ) and gfNode notin flags:
  1500. var cc = c.getTemp(n.typ)
  1501. c.gABx(n, opcLdGlobal, cc, s.position)
  1502. c.gABC(n, opcNodeToReg, dest, cc)
  1503. c.freeTemp(cc)
  1504. else:
  1505. c.gABx(n, opcLdGlobal, dest, s.position)
  1506. else:
  1507. if s.kind == skForVar and c.mode == emRepl: c.setSlot(s)
  1508. if s.position > 0 or (s.position == 0 and
  1509. s.kind in {skParam, skResult}):
  1510. if dest < 0:
  1511. dest = s.position + ord(s.kind == skParam)
  1512. internalAssert(c.config, c.prc.regInfo[dest].kind < slotSomeTemp)
  1513. else:
  1514. # we need to generate an assignment:
  1515. let requiresCopy = c.prc.regInfo[dest].kind >= slotSomeTemp and
  1516. gfIsParam notin flags
  1517. genAsgn(c, dest, n, requiresCopy)
  1518. else:
  1519. # see tests/t99bott for an example that triggers it:
  1520. cannotEval(c, n)
  1521. template needsRegLoad(): untyped =
  1522. {gfNode, gfNodeAddr} * flags == {} and
  1523. fitsRegister(n.typ.skipTypes({tyVar, tyLent, tyStatic}))
  1524. proc genArrAccessOpcode(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode;
  1525. flags: TGenFlags) =
  1526. let a = c.genx(n[0], flags)
  1527. let b = c.genIndex(n[1], n[0].typ)
  1528. if dest < 0: dest = c.getTemp(n.typ)
  1529. if opc in {opcLdArrAddr, opcLdStrIdxAddr} and gfNodeAddr in flags:
  1530. c.gABC(n, opc, dest, a, b)
  1531. elif needsRegLoad():
  1532. var cc = c.getTemp(n.typ)
  1533. c.gABC(n, opc, cc, a, b)
  1534. c.gABC(n, opcNodeToReg, dest, cc)
  1535. c.freeTemp(cc)
  1536. else:
  1537. #message(c.config, n.info, warnUser, "argh")
  1538. #echo "FLAGS ", flags, " ", fitsRegister(n.typ), " ", typeToString(n.typ)
  1539. c.gABC(n, opc, dest, a, b)
  1540. c.freeTemp(a)
  1541. c.freeTemp(b)
  1542. proc genObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1543. let a = c.genx(n[0], flags)
  1544. let b = genField(c, n[1])
  1545. if dest < 0: dest = c.getTemp(n.typ)
  1546. if {gfNodeAddr} * flags != {}:
  1547. c.gABC(n, opcLdObjAddr, dest, a, b)
  1548. elif needsRegLoad():
  1549. var cc = c.getTemp(n.typ)
  1550. c.gABC(n, opcLdObj, cc, a, b)
  1551. c.gABC(n, opcNodeToReg, dest, cc)
  1552. c.freeTemp(cc)
  1553. else:
  1554. c.gABC(n, opcLdObj, dest, a, b)
  1555. c.freeTemp(a)
  1556. proc genCheckedObjAccessAux(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1557. internalAssert c.config, n.kind == nkCheckedFieldExpr
  1558. # nkDotExpr to access the requested field
  1559. let accessExpr = n[0]
  1560. # nkCall to check if the discriminant is valid
  1561. var checkExpr = n[1]
  1562. let negCheck = checkExpr[0].sym.magic == mNot
  1563. if negCheck:
  1564. checkExpr = checkExpr[^1]
  1565. # Discriminant symbol
  1566. let disc = checkExpr[2]
  1567. internalAssert c.config, disc.sym.kind == skField
  1568. # Load the object in `dest`
  1569. c.gen(accessExpr[0], dest, flags)
  1570. # Load the discriminant
  1571. var discVal = c.getTemp(disc.typ)
  1572. c.gABC(n, opcLdObj, discVal, dest, genField(c, disc))
  1573. # Check if its value is contained in the supplied set
  1574. let setLit = c.genx(checkExpr[1])
  1575. var rs = c.getTemp(getSysType(c.graph, n.info, tyBool))
  1576. c.gABC(n, opcContainsSet, rs, setLit, discVal)
  1577. c.freeTemp(discVal)
  1578. c.freeTemp(setLit)
  1579. # If the check fails let the user know
  1580. let lab1 = c.xjmp(n, if negCheck: opcFJmp else: opcTJmp, rs)
  1581. c.freeTemp(rs)
  1582. let strType = getSysType(c.graph, n.info, tyString)
  1583. var msgReg: TDest = c.getTemp(strType)
  1584. let fieldName = $accessExpr[1]
  1585. let msg = genFieldDefect(c.config, fieldName, disc.sym)
  1586. let strLit = newStrNode(msg, accessExpr[1].info)
  1587. strLit.typ = strType
  1588. c.genLit(strLit, msgReg)
  1589. c.gABC(n, opcInvalidField, msgReg, discVal)
  1590. c.freeTemp(msgReg)
  1591. c.patch(lab1)
  1592. proc genCheckedObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1593. var objR: TDest = -1
  1594. genCheckedObjAccessAux(c, n, objR, flags)
  1595. let accessExpr = n[0]
  1596. # Field symbol
  1597. var field = accessExpr[1]
  1598. internalAssert c.config, field.sym.kind == skField
  1599. # Load the content now
  1600. if dest < 0: dest = c.getTemp(n.typ)
  1601. let fieldPos = genField(c, field)
  1602. if {gfNodeAddr} * flags != {}:
  1603. c.gABC(n, opcLdObjAddr, dest, objR, fieldPos)
  1604. elif needsRegLoad():
  1605. var cc = c.getTemp(accessExpr.typ)
  1606. c.gABC(n, opcLdObj, cc, objR, fieldPos)
  1607. c.gABC(n, opcNodeToReg, dest, cc)
  1608. c.freeTemp(cc)
  1609. else:
  1610. c.gABC(n, opcLdObj, dest, objR, fieldPos)
  1611. c.freeTemp(objR)
  1612. proc genArrAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) =
  1613. let arrayType = n[0].typ.skipTypes(abstractVarRange-{tyTypeDesc}).kind
  1614. if arrayType in {tyString, tyCstring}:
  1615. let opc = if gfNodeAddr in flags: opcLdStrIdxAddr else: opcLdStrIdx
  1616. genArrAccessOpcode(c, n, dest, opc, flags)
  1617. elif arrayType == tyTypeDesc:
  1618. c.genTypeLit(n.typ, dest)
  1619. else:
  1620. let opc = if gfNodeAddr in flags: opcLdArrAddr else: opcLdArr
  1621. genArrAccessOpcode(c, n, dest, opc, flags)
  1622. proc getNullValueAux(t: PType; obj: PNode, result: PNode; conf: ConfigRef; currPosition: var int) =
  1623. if t != nil and t.len > 0 and t[0] != nil:
  1624. let b = skipTypes(t[0], skipPtrs)
  1625. getNullValueAux(b, b.n, result, conf, currPosition)
  1626. case obj.kind
  1627. of nkRecList:
  1628. for i in 0..<obj.len: getNullValueAux(nil, obj[i], result, conf, currPosition)
  1629. of nkRecCase:
  1630. getNullValueAux(nil, obj[0], result, conf, currPosition)
  1631. for i in 1..<obj.len:
  1632. getNullValueAux(nil, lastSon(obj[i]), result, conf, currPosition)
  1633. of nkSym:
  1634. let field = newNodeI(nkExprColonExpr, result.info)
  1635. field.add(obj)
  1636. field.add(getNullValue(obj.sym.typ, result.info, conf))
  1637. result.add field
  1638. doAssert obj.sym.position == currPosition
  1639. inc currPosition
  1640. else: globalError(conf, result.info, "cannot create null element for: " & $obj)
  1641. proc getNullValue(typ: PType, info: TLineInfo; conf: ConfigRef): PNode =
  1642. var t = skipTypes(typ, abstractRange+{tyStatic, tyOwned}-{tyTypeDesc})
  1643. case t.kind
  1644. of tyBool, tyEnum, tyChar, tyInt..tyInt64:
  1645. result = newNodeIT(nkIntLit, info, t)
  1646. of tyUInt..tyUInt64:
  1647. result = newNodeIT(nkUIntLit, info, t)
  1648. of tyFloat..tyFloat128:
  1649. result = newNodeIT(nkFloatLit, info, t)
  1650. of tyCstring, tyString:
  1651. result = newNodeIT(nkStrLit, info, t)
  1652. result.strVal = ""
  1653. of tyVar, tyLent, tyPointer, tyPtr, tyUntyped,
  1654. tyTyped, tyTypeDesc, tyRef, tyNil:
  1655. result = newNodeIT(nkNilLit, info, t)
  1656. of tyProc:
  1657. if t.callConv != ccClosure:
  1658. result = newNodeIT(nkNilLit, info, t)
  1659. else:
  1660. result = newNodeIT(nkTupleConstr, info, t)
  1661. result.add(newNodeIT(nkNilLit, info, t))
  1662. result.add(newNodeIT(nkNilLit, info, t))
  1663. of tyObject:
  1664. result = newNodeIT(nkObjConstr, info, t)
  1665. result.add(newNodeIT(nkEmpty, info, t))
  1666. # initialize inherited fields, and all in the correct order:
  1667. var currPosition = 0
  1668. getNullValueAux(t, t.n, result, conf, currPosition)
  1669. of tyArray:
  1670. result = newNodeIT(nkBracket, info, t)
  1671. for i in 0..<toInt(lengthOrd(conf, t)):
  1672. result.add getNullValue(elemType(t), info, conf)
  1673. of tyTuple:
  1674. result = newNodeIT(nkTupleConstr, info, t)
  1675. for i in 0..<t.len:
  1676. result.add getNullValue(t[i], info, conf)
  1677. of tySet:
  1678. result = newNodeIT(nkCurly, info, t)
  1679. of tySequence, tyOpenArray:
  1680. result = newNodeIT(nkBracket, info, t)
  1681. else:
  1682. globalError(conf, info, "cannot create null element for: " & $t.kind)
  1683. result = newNodeI(nkEmpty, info)
  1684. proc genVarSection(c: PCtx; n: PNode) =
  1685. for a in n:
  1686. if a.kind == nkCommentStmt: continue
  1687. #assert(a[0].kind == nkSym) can happen for transformed vars
  1688. if a.kind == nkVarTuple:
  1689. for i in 0..<a.len-2:
  1690. if a[i].kind == nkSym:
  1691. if not a[i].sym.isGlobal: setSlot(c, a[i].sym)
  1692. checkCanEval(c, a[i])
  1693. c.gen(lowerTupleUnpacking(c.graph, a, c.idgen, c.getOwner))
  1694. elif a[0].kind == nkSym:
  1695. let s = a[0].sym
  1696. checkCanEval(c, a[0])
  1697. if s.isGlobal:
  1698. if s.position == 0:
  1699. if importcCond(c, s): c.importcSym(a.info, s)
  1700. else:
  1701. let sa = getNullValue(s.typ, a.info, c.config)
  1702. #if s.ast.isNil: getNullValue(s.typ, a.info)
  1703. #else: s.ast
  1704. assert sa.kind != nkCall
  1705. c.globals.add(sa)
  1706. s.position = c.globals.len
  1707. if a[2].kind != nkEmpty:
  1708. let tmp = c.genx(a[0], {gfNodeAddr})
  1709. let val = c.genx(a[2])
  1710. c.genAdditionalCopy(a[2], opcWrDeref, tmp, 0, val)
  1711. c.freeTemp(val)
  1712. c.freeTemp(tmp)
  1713. else:
  1714. setSlot(c, s)
  1715. if a[2].kind == nkEmpty:
  1716. c.gABx(a, ldNullOpcode(s.typ), s.position, c.genType(s.typ))
  1717. else:
  1718. assert s.typ != nil
  1719. if not fitsRegister(s.typ):
  1720. c.gABx(a, ldNullOpcode(s.typ), s.position, c.genType(s.typ))
  1721. let le = a[0]
  1722. assert le.typ != nil
  1723. if not fitsRegister(le.typ) and s.kind in {skResult, skVar, skParam}:
  1724. var cc = c.getTemp(le.typ)
  1725. gen(c, a[2], cc)
  1726. c.gABC(le, whichAsgnOpc(le), s.position.TRegister, cc)
  1727. c.freeTemp(cc)
  1728. else:
  1729. gen(c, a[2], s.position.TRegister)
  1730. else:
  1731. # assign to a[0]; happens for closures
  1732. if a[2].kind == nkEmpty:
  1733. let tmp = genx(c, a[0])
  1734. c.gABx(a, ldNullOpcode(a[0].typ), tmp, c.genType(a[0].typ))
  1735. c.freeTemp(tmp)
  1736. else:
  1737. genAsgn(c, a[0], a[2], true)
  1738. proc genArrayConstr(c: PCtx, n: PNode, dest: var TDest) =
  1739. if dest < 0: dest = c.getTemp(n.typ)
  1740. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1741. let intType = getSysType(c.graph, n.info, tyInt)
  1742. let seqType = n.typ.skipTypes(abstractVar-{tyTypeDesc})
  1743. if seqType.kind == tySequence:
  1744. var tmp = c.getTemp(intType)
  1745. c.gABx(n, opcLdImmInt, tmp, n.len)
  1746. c.gABx(n, opcNewSeq, dest, c.genType(seqType))
  1747. c.gABx(n, opcNewSeq, tmp, 0)
  1748. c.freeTemp(tmp)
  1749. if n.len > 0:
  1750. var tmp = getTemp(c, intType)
  1751. c.gABx(n, opcLdNullReg, tmp, c.genType(intType))
  1752. for x in n:
  1753. let a = c.genx(x)
  1754. c.preventFalseAlias(n, opcWrArr, dest, tmp, a)
  1755. c.gABI(n, opcAddImmInt, tmp, tmp, 1)
  1756. c.freeTemp(a)
  1757. c.freeTemp(tmp)
  1758. proc genSetConstr(c: PCtx, n: PNode, dest: var TDest) =
  1759. if dest < 0: dest = c.getTemp(n.typ)
  1760. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1761. for x in n:
  1762. if x.kind == nkRange:
  1763. let a = c.genx(x[0])
  1764. let b = c.genx(x[1])
  1765. c.gABC(n, opcInclRange, dest, a, b)
  1766. c.freeTemp(b)
  1767. c.freeTemp(a)
  1768. else:
  1769. let a = c.genx(x)
  1770. c.gABC(n, opcIncl, dest, a)
  1771. c.freeTemp(a)
  1772. proc genObjConstr(c: PCtx, n: PNode, dest: var TDest) =
  1773. if dest < 0: dest = c.getTemp(n.typ)
  1774. let t = n.typ.skipTypes(abstractRange+{tyOwned}-{tyTypeDesc})
  1775. if t.kind == tyRef:
  1776. c.gABx(n, opcNew, dest, c.genType(t[0]))
  1777. else:
  1778. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1779. for i in 1..<n.len:
  1780. let it = n[i]
  1781. if it.kind == nkExprColonExpr and it[0].kind == nkSym:
  1782. let idx = genField(c, it[0])
  1783. let tmp = c.genx(it[1])
  1784. c.preventFalseAlias(it[1], opcWrObj,
  1785. dest, idx, tmp)
  1786. c.freeTemp(tmp)
  1787. else:
  1788. globalError(c.config, n.info, "invalid object constructor")
  1789. proc genTupleConstr(c: PCtx, n: PNode, dest: var TDest) =
  1790. if dest < 0: dest = c.getTemp(n.typ)
  1791. if n.typ.kind != tyTypeDesc:
  1792. c.gABx(n, opcLdNull, dest, c.genType(n.typ))
  1793. # XXX x = (x.old, 22) produces wrong code ... stupid self assignments
  1794. for i in 0..<n.len:
  1795. let it = n[i]
  1796. if it.kind == nkExprColonExpr:
  1797. let idx = genField(c, it[0])
  1798. let tmp = c.genx(it[1])
  1799. c.preventFalseAlias(it[1], opcWrObj,
  1800. dest, idx, tmp)
  1801. c.freeTemp(tmp)
  1802. else:
  1803. let tmp = c.genx(it)
  1804. c.preventFalseAlias(it, opcWrObj, dest, i.TRegister, tmp)
  1805. c.freeTemp(tmp)
  1806. proc genProc*(c: PCtx; s: PSym): int
  1807. proc matches(s: PSym; x: string): bool =
  1808. let y = x.split('.')
  1809. var s = s
  1810. for i in 1..y.len:
  1811. if s == nil or (y[^i].cmpIgnoreStyle(s.name.s) != 0 and y[^i] != "*"):
  1812. return false
  1813. s = if sfFromGeneric in s.flags: s.owner.owner else: s.owner
  1814. while s != nil and s.kind == skPackage and s.owner != nil: s = s.owner
  1815. result = true
  1816. proc procIsCallback(c: PCtx; s: PSym): bool =
  1817. if s.offset < -1: return true
  1818. var i = -2
  1819. for key, value in items(c.callbacks):
  1820. if s.matches(key):
  1821. doAssert s.offset == -1
  1822. s.offset = i
  1823. return true
  1824. dec i
  1825. proc gen(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags = {}) =
  1826. when defined(nimCompilerStacktraceHints):
  1827. setFrameMsg c.config$n.info & " " & $n.kind & " " & $flags
  1828. case n.kind
  1829. of nkSym:
  1830. let s = n.sym
  1831. checkCanEval(c, n)
  1832. case s.kind
  1833. of skVar, skForVar, skTemp, skLet, skParam, skResult:
  1834. genRdVar(c, n, dest, flags)
  1835. of skProc, skFunc, skConverter, skMacro, skTemplate, skMethod, skIterator:
  1836. # 'skTemplate' is only allowed for 'getAst' support:
  1837. if s.kind == skIterator and s.typ.callConv == TCallingConvention.ccClosure:
  1838. globalError(c.config, n.info, "Closure iterators are not supported by VM!")
  1839. if procIsCallback(c, s): discard
  1840. elif importcCond(c, s): c.importcSym(n.info, s)
  1841. genLit(c, n, dest)
  1842. of skConst:
  1843. let constVal = if s.astdef != nil: s.astdef else: s.typ.n
  1844. gen(c, constVal, dest)
  1845. of skEnumField:
  1846. # we never reach this case - as of the time of this comment,
  1847. # skEnumField is folded to an int in semfold.nim, but this code
  1848. # remains for robustness
  1849. if dest < 0: dest = c.getTemp(n.typ)
  1850. if s.position >= low(int16) and s.position <= high(int16):
  1851. c.gABx(n, opcLdImmInt, dest, s.position)
  1852. else:
  1853. var lit = genLiteral(c, newIntNode(nkIntLit, s.position))
  1854. c.gABx(n, opcLdConst, dest, lit)
  1855. of skType:
  1856. genTypeLit(c, s.typ, dest)
  1857. of skGenericParam:
  1858. if c.prc.sym != nil and c.prc.sym.kind == skMacro:
  1859. genRdVar(c, n, dest, flags)
  1860. else:
  1861. globalError(c.config, n.info, "cannot generate code for: " & s.name.s)
  1862. else:
  1863. globalError(c.config, n.info, "cannot generate code for: " & s.name.s)
  1864. of nkCallKinds:
  1865. if n[0].kind == nkSym:
  1866. let s = n[0].sym
  1867. if s.magic != mNone:
  1868. genMagic(c, n, dest, s.magic)
  1869. elif s.kind == skMethod:
  1870. localError(c.config, n.info, "cannot call method " & s.name.s &
  1871. " at compile time")
  1872. else:
  1873. genCall(c, n, dest)
  1874. clearDest(c, n, dest)
  1875. else:
  1876. genCall(c, n, dest)
  1877. clearDest(c, n, dest)
  1878. of nkCharLit..nkInt64Lit:
  1879. if isInt16Lit(n):
  1880. if dest < 0: dest = c.getTemp(n.typ)
  1881. c.gABx(n, opcLdImmInt, dest, n.intVal.int)
  1882. else:
  1883. genLit(c, n, dest)
  1884. of nkUIntLit..pred(nkNilLit): genLit(c, n, dest)
  1885. of nkNilLit:
  1886. if not n.typ.isEmptyType: genLit(c, getNullValue(n.typ, n.info, c.config), dest)
  1887. else: unused(c, n, dest)
  1888. of nkAsgn, nkFastAsgn:
  1889. unused(c, n, dest)
  1890. genAsgn(c, n[0], n[1], n.kind == nkAsgn)
  1891. of nkDotExpr: genObjAccess(c, n, dest, flags)
  1892. of nkCheckedFieldExpr: genCheckedObjAccess(c, n, dest, flags)
  1893. of nkBracketExpr: genArrAccess(c, n, dest, flags)
  1894. of nkDerefExpr, nkHiddenDeref: genDeref(c, n, dest, flags)
  1895. of nkAddr, nkHiddenAddr: genAddr(c, n, dest, flags)
  1896. of nkIfStmt, nkIfExpr: genIf(c, n, dest)
  1897. of nkWhenStmt:
  1898. # This is "when nimvm" node. Chose the first branch.
  1899. gen(c, n[0][1], dest)
  1900. of nkCaseStmt: genCase(c, n, dest)
  1901. of nkWhileStmt:
  1902. unused(c, n, dest)
  1903. genWhile(c, n)
  1904. of nkBlockExpr, nkBlockStmt: genBlock(c, n, dest)
  1905. of nkReturnStmt:
  1906. genReturn(c, n)
  1907. of nkRaiseStmt:
  1908. genRaise(c, n)
  1909. of nkBreakStmt:
  1910. genBreak(c, n)
  1911. of nkTryStmt, nkHiddenTryStmt: genTry(c, n, dest)
  1912. of nkStmtList:
  1913. #unused(c, n, dest)
  1914. # XXX Fix this bug properly, lexim triggers it
  1915. for x in n: gen(c, x)
  1916. of nkStmtListExpr:
  1917. for i in 0..<n.len-1: gen(c, n[i])
  1918. gen(c, n[^1], dest, flags)
  1919. of nkPragmaBlock:
  1920. gen(c, n.lastSon, dest, flags)
  1921. of nkDiscardStmt:
  1922. unused(c, n, dest)
  1923. gen(c, n[0])
  1924. of nkHiddenStdConv, nkHiddenSubConv, nkConv:
  1925. genConv(c, n, n[1], dest)
  1926. of nkObjDownConv:
  1927. genConv(c, n, n[0], dest)
  1928. of nkObjUpConv:
  1929. genConv(c, n, n[0], dest)
  1930. of nkVarSection, nkLetSection:
  1931. unused(c, n, dest)
  1932. genVarSection(c, n)
  1933. of declarativeDefs, nkMacroDef:
  1934. unused(c, n, dest)
  1935. of nkLambdaKinds:
  1936. #let s = n[namePos].sym
  1937. #discard genProc(c, s)
  1938. genLit(c, newSymNode(n[namePos].sym), dest)
  1939. of nkChckRangeF, nkChckRange64, nkChckRange:
  1940. let
  1941. tmp0 = c.genx(n[0])
  1942. tmp1 = c.genx(n[1])
  1943. tmp2 = c.genx(n[2])
  1944. c.gABC(n, opcRangeChck, tmp0, tmp1, tmp2)
  1945. c.freeTemp(tmp1)
  1946. c.freeTemp(tmp2)
  1947. if dest >= 0:
  1948. gABC(c, n, whichAsgnOpc(n), dest, tmp0)
  1949. c.freeTemp(tmp0)
  1950. else:
  1951. dest = tmp0
  1952. of nkEmpty, nkCommentStmt, nkTypeSection, nkConstSection, nkPragma,
  1953. nkTemplateDef, nkIncludeStmt, nkImportStmt, nkFromStmt, nkExportStmt,
  1954. nkMixinStmt, nkBindStmt:
  1955. unused(c, n, dest)
  1956. of nkStringToCString, nkCStringToString:
  1957. gen(c, n[0], dest)
  1958. of nkBracket: genArrayConstr(c, n, dest)
  1959. of nkCurly: genSetConstr(c, n, dest)
  1960. of nkObjConstr: genObjConstr(c, n, dest)
  1961. of nkPar, nkClosure, nkTupleConstr: genTupleConstr(c, n, dest)
  1962. of nkCast:
  1963. if allowCast in c.features:
  1964. genConv(c, n, n[1], dest, opcCast)
  1965. else:
  1966. genCastIntFloat(c, n, dest)
  1967. of nkTypeOfExpr:
  1968. genTypeLit(c, n.typ, dest)
  1969. of nkComesFrom:
  1970. discard "XXX to implement for better stack traces"
  1971. else:
  1972. if n.typ != nil and n.typ.isCompileTimeOnly:
  1973. genTypeLit(c, n.typ, dest)
  1974. else:
  1975. globalError(c.config, n.info, "cannot generate VM code for " & $n)
  1976. proc removeLastEof(c: PCtx) =
  1977. let last = c.code.len-1
  1978. if last >= 0 and c.code[last].opcode == opcEof:
  1979. # overwrite last EOF:
  1980. assert c.code.len == c.debug.len
  1981. c.code.setLen(last)
  1982. c.debug.setLen(last)
  1983. proc genStmt*(c: PCtx; n: PNode): int =
  1984. c.removeLastEof
  1985. result = c.code.len
  1986. var d: TDest = -1
  1987. c.gen(n, d)
  1988. c.gABC(n, opcEof)
  1989. if d >= 0:
  1990. globalError(c.config, n.info, "VM problem: dest register is set")
  1991. proc genExpr*(c: PCtx; n: PNode, requiresValue = true): int =
  1992. c.removeLastEof
  1993. result = c.code.len
  1994. var d: TDest = -1
  1995. c.gen(n, d)
  1996. if d < 0:
  1997. if requiresValue:
  1998. globalError(c.config, n.info, "VM problem: dest register is not set")
  1999. d = 0
  2000. c.gABC(n, opcEof, d)
  2001. #echo renderTree(n)
  2002. #c.echoCode(result)
  2003. proc genParams(c: PCtx; params: PNode) =
  2004. # res.sym.position is already 0
  2005. setLen(c.prc.regInfo, max(params.len, 1))
  2006. c.prc.regInfo[0] = (inUse: true, kind: slotFixedVar)
  2007. for i in 1..<params.len:
  2008. c.prc.regInfo[i] = (inUse: true, kind: slotFixedLet)
  2009. proc finalJumpTarget(c: PCtx; pc, diff: int) =
  2010. internalAssert(c.config, regBxMin < diff and diff < regBxMax)
  2011. let oldInstr = c.code[pc]
  2012. # opcode and regA stay the same:
  2013. c.code[pc] = ((oldInstr.TInstrType and ((regOMask shl regOShift) or (regAMask shl regAShift))).TInstrType or
  2014. TInstrType(diff+wordExcess) shl regBxShift).TInstr
  2015. proc genGenericParams(c: PCtx; gp: PNode) =
  2016. var base = c.prc.regInfo.len
  2017. setLen c.prc.regInfo, base + gp.len
  2018. for i in 0..<gp.len:
  2019. var param = gp[i].sym
  2020. param.position = base + i # XXX: fix this earlier; make it consistent with templates
  2021. c.prc.regInfo[base + i] = (inUse: true, kind: slotFixedLet)
  2022. proc optimizeJumps(c: PCtx; start: int) =
  2023. const maxIterations = 10
  2024. for i in start..<c.code.len:
  2025. let opc = c.code[i].opcode
  2026. case opc
  2027. of opcTJmp, opcFJmp:
  2028. var reg = c.code[i].regA
  2029. var d = i + c.code[i].jmpDiff
  2030. for iters in countdown(maxIterations, 0):
  2031. case c.code[d].opcode
  2032. of opcJmp:
  2033. d += c.code[d].jmpDiff
  2034. of opcTJmp, opcFJmp:
  2035. if c.code[d].regA != reg: break
  2036. # tjmp x, 23
  2037. # ...
  2038. # tjmp x, 12
  2039. # -- we know 'x' is true, and so can jump to 12+13:
  2040. if c.code[d].opcode == opc:
  2041. d += c.code[d].jmpDiff
  2042. else:
  2043. # tjmp x, 23
  2044. # fjmp x, 22
  2045. # We know 'x' is true so skip to the next instruction:
  2046. d += 1
  2047. else: break
  2048. if d != i + c.code[i].jmpDiff:
  2049. c.finalJumpTarget(i, d - i)
  2050. of opcJmp, opcJmpBack:
  2051. var d = i + c.code[i].jmpDiff
  2052. var iters = maxIterations
  2053. while c.code[d].opcode == opcJmp and iters > 0:
  2054. d += c.code[d].jmpDiff
  2055. dec iters
  2056. if c.code[d].opcode == opcRet:
  2057. # optimize 'jmp to ret' to 'ret' here
  2058. c.code[i] = c.code[d]
  2059. elif d != i + c.code[i].jmpDiff:
  2060. c.finalJumpTarget(i, d - i)
  2061. else: discard
  2062. proc genProc(c: PCtx; s: PSym): int =
  2063. let
  2064. pos = c.procToCodePos.getOrDefault(s.id)
  2065. wasNotGenProcBefore = pos == 0
  2066. noRegistersAllocated = s.offset == -1
  2067. if wasNotGenProcBefore or noRegistersAllocated:
  2068. # xxx: the noRegisterAllocated check is required in order to avoid issues
  2069. # where nimsuggest can crash due as a macro with pos will be loaded
  2070. # but it doesn't have offsets for register allocations see:
  2071. # https://github.com/nim-lang/Nim/issues/18385
  2072. # Improvements and further use of IC should remove the need for this.
  2073. #if s.name.s == "outterMacro" or s.name.s == "innerProc":
  2074. # echo "GENERATING CODE FOR ", s.name.s
  2075. let last = c.code.len-1
  2076. var eofInstr: TInstr
  2077. if last >= 0 and c.code[last].opcode == opcEof:
  2078. eofInstr = c.code[last]
  2079. c.code.setLen(last)
  2080. c.debug.setLen(last)
  2081. #c.removeLastEof
  2082. result = c.code.len+1 # skip the jump instruction
  2083. c.procToCodePos[s.id] = result
  2084. # thanks to the jmp we can add top level statements easily and also nest
  2085. # procs easily:
  2086. let body = transformBody(c.graph, c.idgen, s, if isCompileTimeProc(s): dontUseCache else: useCache)
  2087. let procStart = c.xjmp(body, opcJmp, 0)
  2088. var p = PProc(blocks: @[], sym: s)
  2089. let oldPrc = c.prc
  2090. c.prc = p
  2091. # iterate over the parameters and allocate space for them:
  2092. genParams(c, s.typ.n)
  2093. # allocate additional space for any generically bound parameters
  2094. if s.kind == skMacro and s.isGenericRoutineStrict:
  2095. genGenericParams(c, s.ast[genericParamsPos])
  2096. if tfCapturesEnv in s.typ.flags:
  2097. #let env = s.ast[paramsPos].lastSon.sym
  2098. #assert env.position == 2
  2099. c.prc.regInfo.add (inUse: true, kind: slotFixedLet)
  2100. gen(c, body)
  2101. # generate final 'return' statement:
  2102. c.gABC(body, opcRet)
  2103. c.patch(procStart)
  2104. c.gABC(body, opcEof, eofInstr.regA)
  2105. c.optimizeJumps(result)
  2106. s.offset = c.prc.regInfo.len
  2107. #if s.name.s == "main" or s.name.s == "[]":
  2108. # echo renderTree(body)
  2109. # c.echoCode(result)
  2110. c.prc = oldPrc
  2111. else:
  2112. c.prc.regInfo.setLen s.offset
  2113. result = pos