vmgen.nim 76 KB

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