vmgen.nim 83 KB

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