vmgen.nim 77 KB

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