vmgen.nim 76 KB

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