ccgexprs.nim 108 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # included from cgen.nim
  10. # -------------------------- constant expressions ------------------------
  11. proc int64Literal(i: BiggestInt): Rope =
  12. if i > low(int64):
  13. result = "IL64($1)" % [rope(i)]
  14. else:
  15. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  16. proc uint64Literal(i: uint64): Rope = rope($i & "ULL")
  17. proc intLiteral(i: BiggestInt): Rope =
  18. if i > low(int32) and i <= high(int32):
  19. result = rope(i)
  20. elif i == low(int32):
  21. # Nim has the same bug for the same reasons :-)
  22. result = ~"(-2147483647 -1)"
  23. elif i > low(int64):
  24. result = "IL64($1)" % [rope(i)]
  25. else:
  26. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  27. proc genLiteral(p: BProc, n: PNode, ty: PType): Rope =
  28. case n.kind
  29. of nkCharLit..nkUInt64Lit:
  30. var k: TTypeKind
  31. if ty != nil:
  32. k = skipTypes(ty, abstractVarRange).kind
  33. else:
  34. case n.kind
  35. of nkCharLit: k = tyChar
  36. of nkUInt64Lit: k = tyUInt64
  37. of nkInt64Lit: k = tyInt64
  38. else: k = tyNil # don't go into the case variant that uses 'ty'
  39. case k
  40. of tyChar, tyNil:
  41. result = intLiteral(n.intVal)
  42. of tyBool:
  43. if n.intVal != 0: result = ~"NIM_TRUE"
  44. else: result = ~"NIM_FALSE"
  45. of tyInt64: result = int64Literal(n.intVal)
  46. of tyUInt64: result = uint64Literal(uint64(n.intVal))
  47. else:
  48. result = "(($1) $2)" % [getTypeDesc(p.module,
  49. ty), intLiteral(n.intVal)]
  50. of nkNilLit:
  51. let k = if ty == nil: tyPointer else: skipTypes(ty, abstractVarRange).kind
  52. if k == tyProc and skipTypes(ty, abstractVarRange).callConv == ccClosure:
  53. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  54. result = p.module.tmpBase & rope(id)
  55. if id == p.module.labels:
  56. # not found in cache:
  57. inc(p.module.labels)
  58. addf(p.module.s[cfsData],
  59. "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n",
  60. [getTypeDesc(p.module, ty), result])
  61. else:
  62. result = rope("NIM_NIL")
  63. of nkStrLit..nkTripleStrLit:
  64. let k = if ty == nil: tyString
  65. else: skipTypes(ty, abstractVarRange + {tyStatic, tyUserTypeClass, tyUserTypeClassInst}).kind
  66. case k
  67. of tyNil:
  68. result = genNilStringLiteral(p.module, n.info)
  69. of tyString:
  70. # with the new semantics for 'nil' strings, we can map "" to nil and
  71. # save tons of allocations:
  72. if n.strVal.len == 0 and optNilSeqs notin p.options and
  73. p.config.selectedGc != gcDestructors:
  74. result = genNilStringLiteral(p.module, n.info)
  75. else:
  76. result = genStringLiteral(p.module, n)
  77. else:
  78. result = makeCString(n.strVal)
  79. of nkFloatLit, nkFloat64Lit:
  80. result = rope(n.floatVal.toStrMaxPrecision)
  81. of nkFloat32Lit:
  82. result = rope(n.floatVal.toStrMaxPrecision("f"))
  83. else:
  84. internalError(p.config, n.info, "genLiteral(" & $n.kind & ')')
  85. result = nil
  86. proc genLiteral(p: BProc, n: PNode): Rope =
  87. result = genLiteral(p, n, n.typ)
  88. proc bitSetToWord(s: TBitSet, size: int): BiggestUInt =
  89. result = 0
  90. for j in 0 ..< size:
  91. if j < len(s): result = result or (BiggestUInt(s[j]) shl (j * 8))
  92. proc genRawSetData(cs: TBitSet, size: int): Rope =
  93. if size > 8:
  94. var res = "{\n"
  95. for i in 0 ..< size:
  96. res.add "0x"
  97. res.add "0123456789abcdef"[cs[i] div 16]
  98. res.add "0123456789abcdef"[cs[i] mod 16]
  99. if i < size - 1:
  100. # not last iteration
  101. if i mod 8 == 7:
  102. res.add ",\n"
  103. else:
  104. res.add ", "
  105. else:
  106. res.add "}\n"
  107. result = rope(res)
  108. else:
  109. result = intLiteral(cast[BiggestInt](bitSetToWord(cs, size)))
  110. proc genSetNode(p: BProc, n: PNode): Rope =
  111. var cs: TBitSet
  112. var size = int(getSize(p.config, n.typ))
  113. toBitSet(p.config, n, cs)
  114. if size > 8:
  115. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  116. result = p.module.tmpBase & rope(id)
  117. if id == p.module.labels:
  118. # not found in cache:
  119. inc(p.module.labels)
  120. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  121. [getTypeDesc(p.module, n.typ), result, genRawSetData(cs, size)])
  122. else:
  123. result = genRawSetData(cs, size)
  124. proc getStorageLoc(n: PNode): TStorageLoc =
  125. case n.kind
  126. of nkSym:
  127. case n.sym.kind
  128. of skParam, skTemp:
  129. result = OnStack
  130. of skVar, skForVar, skResult, skLet:
  131. if sfGlobal in n.sym.flags: result = OnHeap
  132. else: result = OnStack
  133. of skConst:
  134. if sfGlobal in n.sym.flags: result = OnHeap
  135. else: result = OnUnknown
  136. else: result = OnUnknown
  137. of nkDerefExpr, nkHiddenDeref:
  138. case n.sons[0].typ.kind
  139. of tyVar, tyLent: result = OnUnknown
  140. of tyPtr: result = OnStack
  141. of tyRef: result = OnHeap
  142. else: doAssert(false, "getStorageLoc")
  143. of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv:
  144. result = getStorageLoc(n.sons[0])
  145. else: result = OnUnknown
  146. proc canMove(p: BProc, n: PNode; dest: TLoc): bool =
  147. # for now we're conservative here:
  148. if n.kind == nkBracket:
  149. # This needs to be kept consistent with 'const' seq code
  150. # generation!
  151. if not isDeepConstExpr(n) or n.len == 0:
  152. if skipTypes(n.typ, abstractVarRange).kind == tySequence:
  153. return true
  154. elif optNilSeqs notin p.options and
  155. n.kind in nkStrKinds and n.strVal.len == 0:
  156. # Empty strings are codegen'd as NIM_NIL so it's just a pointer copy
  157. return true
  158. result = n.kind in nkCallKinds
  159. #if not result and dest.k == locTemp:
  160. # return true
  161. #if result:
  162. # echo n.info, " optimized ", n
  163. # result = false
  164. proc genRefAssign(p: BProc, dest, src: TLoc) =
  165. if (dest.storage == OnStack and p.config.selectedGC != gcGo) or not usesWriteBarrier(p.config):
  166. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  167. elif dest.storage == OnHeap:
  168. linefmt(p, cpsStmts, "#asgnRef((void**) $1, $2);$n",
  169. [addrLoc(p.config, dest), rdLoc(src)])
  170. else:
  171. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  172. [addrLoc(p.config, dest), rdLoc(src)])
  173. proc asgnComplexity(n: PNode): int =
  174. if n != nil:
  175. case n.kind
  176. of nkSym: result = 1
  177. of nkRecCase:
  178. # 'case objects' are too difficult to inline their assignment operation:
  179. result = 100
  180. of nkRecList:
  181. for t in items(n):
  182. result += asgnComplexity(t)
  183. else: discard
  184. proc optAsgnLoc(a: TLoc, t: PType, field: Rope): TLoc =
  185. assert field != nil
  186. result.k = locField
  187. result.storage = a.storage
  188. result.lode = lodeTyp t
  189. result.r = rdLoc(a) & "." & field
  190. proc genOptAsgnTuple(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  191. let newflags =
  192. if src.storage == OnStatic:
  193. flags + {needToCopy}
  194. elif tfShallow in dest.t.flags:
  195. flags - {needToCopy}
  196. else:
  197. flags
  198. let t = skipTypes(dest.t, abstractInst).getUniqueType()
  199. for i in 0 ..< t.len:
  200. let t = t.sons[i]
  201. let field = "Field$1" % [i.rope]
  202. genAssignment(p, optAsgnLoc(dest, t, field),
  203. optAsgnLoc(src, t, field), newflags)
  204. proc genOptAsgnObject(p: BProc, dest, src: TLoc, flags: TAssignmentFlags,
  205. t: PNode, typ: PType) =
  206. if t == nil: return
  207. let newflags =
  208. if src.storage == OnStatic:
  209. flags + {needToCopy}
  210. elif tfShallow in dest.t.flags:
  211. flags - {needToCopy}
  212. else:
  213. flags
  214. case t.kind
  215. of nkSym:
  216. let field = t.sym
  217. if field.loc.r == nil: fillObjectFields(p.module, typ)
  218. genAssignment(p, optAsgnLoc(dest, field.typ, field.loc.r),
  219. optAsgnLoc(src, field.typ, field.loc.r), newflags)
  220. of nkRecList:
  221. for child in items(t): genOptAsgnObject(p, dest, src, newflags, child, typ)
  222. else: discard
  223. proc genGenericAsgn(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  224. # Consider:
  225. # type TMyFastString {.shallow.} = string
  226. # Due to the implementation of pragmas this would end up to set the
  227. # tfShallow flag for the built-in string type too! So we check only
  228. # here for this flag, where it is reasonably safe to do so
  229. # (for objects, etc.):
  230. if p.config.selectedGC == gcDestructors:
  231. linefmt(p, cpsStmts,
  232. "$1 = $2;$n",
  233. [rdLoc(dest), rdLoc(src)])
  234. elif needToCopy notin flags or
  235. tfShallow in skipTypes(dest.t, abstractVarRange).flags:
  236. if (dest.storage == OnStack and p.config.selectedGC != gcGo) or not usesWriteBarrier(p.config):
  237. linefmt(p, cpsStmts,
  238. "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  239. [addrLoc(p.config, dest), addrLoc(p.config, src), rdLoc(dest)])
  240. else:
  241. linefmt(p, cpsStmts, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n",
  242. [addrLoc(p.config, dest), addrLoc(p.config, src), genTypeInfo(p.module, dest.t, dest.lode.info)])
  243. else:
  244. linefmt(p, cpsStmts, "#genericAssign((void*)$1, (void*)$2, $3);$n",
  245. [addrLoc(p.config, dest), addrLoc(p.config, src), genTypeInfo(p.module, dest.t, dest.lode.info)])
  246. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  247. # This function replaces all other methods for generating
  248. # the assignment operation in C.
  249. if src.t != nil and src.t.kind == tyPtr:
  250. # little HACK to support the new 'var T' as return type:
  251. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  252. return
  253. let ty = skipTypes(dest.t, abstractRange + tyUserTypeClasses + {tyStatic})
  254. case ty.kind
  255. of tyRef:
  256. genRefAssign(p, dest, src)
  257. of tySequence:
  258. if p.config.selectedGC == gcDestructors:
  259. genGenericAsgn(p, dest, src, flags)
  260. elif (needToCopy notin flags and src.storage != OnStatic) or canMove(p, src.lode, dest):
  261. genRefAssign(p, dest, src)
  262. else:
  263. linefmt(p, cpsStmts, "#genericSeqAssign($1, $2, $3);$n",
  264. [addrLoc(p.config, dest), rdLoc(src),
  265. genTypeInfo(p.module, dest.t, dest.lode.info)])
  266. of tyString:
  267. if p.config.selectedGC == gcDestructors:
  268. genGenericAsgn(p, dest, src, flags)
  269. elif (needToCopy notin flags and src.storage != OnStatic) or canMove(p, src.lode, dest):
  270. genRefAssign(p, dest, src)
  271. else:
  272. if (dest.storage == OnStack and p.config.selectedGC != gcGo) or not usesWriteBarrier(p.config):
  273. linefmt(p, cpsStmts, "$1 = #copyString($2);$n", [dest.rdLoc, src.rdLoc])
  274. elif dest.storage == OnHeap:
  275. # we use a temporary to care for the dreaded self assignment:
  276. var tmp: TLoc
  277. getTemp(p, ty, tmp)
  278. linefmt(p, cpsStmts, "$3 = $1; $1 = #copyStringRC1($2);$n",
  279. [dest.rdLoc, src.rdLoc, tmp.rdLoc])
  280. linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", [tmp.rdLoc])
  281. else:
  282. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, #copyString($2));$n",
  283. [addrLoc(p.config, dest), rdLoc(src)])
  284. of tyProc:
  285. if containsGarbageCollectedRef(dest.t):
  286. # optimize closure assignment:
  287. let a = optAsgnLoc(dest, dest.t, "ClE_0".rope)
  288. let b = optAsgnLoc(src, dest.t, "ClE_0".rope)
  289. genRefAssign(p, a, b)
  290. linefmt(p, cpsStmts, "$1.ClP_0 = $2.ClP_0;$n", [rdLoc(dest), rdLoc(src)])
  291. else:
  292. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  293. of tyTuple:
  294. if containsGarbageCollectedRef(dest.t):
  295. if dest.t.len <= 4: genOptAsgnTuple(p, dest, src, flags)
  296. else: genGenericAsgn(p, dest, src, flags)
  297. else:
  298. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  299. of tyObject:
  300. # XXX: check for subtyping?
  301. if ty.isImportedCppType:
  302. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  303. elif not isObjLackingTypeField(ty):
  304. genGenericAsgn(p, dest, src, flags)
  305. elif containsGarbageCollectedRef(ty):
  306. if ty.sons[0].isNil and asgnComplexity(ty.n) <= 4:
  307. discard getTypeDesc(p.module, ty)
  308. internalAssert p.config, ty.n != nil
  309. genOptAsgnObject(p, dest, src, flags, ty.n, ty)
  310. else:
  311. genGenericAsgn(p, dest, src, flags)
  312. else:
  313. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  314. of tyArray:
  315. if containsGarbageCollectedRef(dest.t):
  316. genGenericAsgn(p, dest, src, flags)
  317. else:
  318. linefmt(p, cpsStmts,
  319. "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  320. [rdLoc(dest), rdLoc(src), getTypeDesc(p.module, dest.t)])
  321. of tyOpenArray, tyVarargs:
  322. # open arrays are always on the stack - really? What if a sequence is
  323. # passed to an open array?
  324. if containsGarbageCollectedRef(dest.t):
  325. linefmt(p, cpsStmts, # XXX: is this correct for arrays?
  326. "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  327. [addrLoc(p.config, dest), addrLoc(p.config, src),
  328. genTypeInfo(p.module, dest.t, dest.lode.info)])
  329. else:
  330. linefmt(p, cpsStmts,
  331. # bug #4799, keep the nimCopyMem for a while
  332. #"#nimCopyMem((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len_0);$n",
  333. "$1 = $2;$n",
  334. [rdLoc(dest), rdLoc(src)])
  335. of tySet:
  336. if mapType(p.config, ty) == ctArray:
  337. linefmt(p, cpsStmts, "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, $3);$n",
  338. [rdLoc(dest), rdLoc(src), getSize(p.config, dest.t)])
  339. else:
  340. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  341. of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString,
  342. tyInt..tyUInt64, tyRange, tyVar, tyLent, tyNil:
  343. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  344. else: internalError(p.config, "genAssignment: " & $ty.kind)
  345. if optMemTracker in p.options and dest.storage in {OnHeap, OnUnknown}:
  346. #writeStackTrace()
  347. #echo p.currLineInfo, " requesting"
  348. linefmt(p, cpsStmts, "#memTrackerWrite((void*)$1, $2, $3, $4);$n",
  349. [addrLoc(p.config, dest), getSize(p.config, dest.t),
  350. makeCString(toFullPath(p.config, p.currLineInfo)),
  351. p.currLineInfo.safeLineNm])
  352. proc genDeepCopy(p: BProc; dest, src: TLoc) =
  353. template addrLocOrTemp(a: TLoc): Rope =
  354. if a.k == locExpr:
  355. var tmp: TLoc
  356. getTemp(p, a.t, tmp)
  357. genAssignment(p, tmp, a, {})
  358. addrLoc(p.config, tmp)
  359. else:
  360. addrLoc(p.config, a)
  361. var ty = skipTypes(dest.t, abstractVarRange + {tyStatic})
  362. case ty.kind
  363. of tyPtr, tyRef, tyProc, tyTuple, tyObject, tyArray:
  364. # XXX optimize this
  365. linefmt(p, cpsStmts, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n",
  366. [addrLoc(p.config, dest), addrLocOrTemp(src),
  367. genTypeInfo(p.module, dest.t, dest.lode.info)])
  368. of tySequence, tyString:
  369. linefmt(p, cpsStmts, "#genericSeqDeepCopy($1, $2, $3);$n",
  370. [addrLoc(p.config, dest), rdLoc(src),
  371. genTypeInfo(p.module, dest.t, dest.lode.info)])
  372. of tyOpenArray, tyVarargs:
  373. linefmt(p, cpsStmts,
  374. "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  375. [addrLoc(p.config, dest), addrLocOrTemp(src),
  376. genTypeInfo(p.module, dest.t, dest.lode.info)])
  377. of tySet:
  378. if mapType(p.config, ty) == ctArray:
  379. linefmt(p, cpsStmts, "#nimCopyMem((void*)$1, (NIM_CONST void*)$2, $3);$n",
  380. [rdLoc(dest), rdLoc(src), getSize(p.config, dest.t)])
  381. else:
  382. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  383. of tyPointer, tyChar, tyBool, tyEnum, tyCString,
  384. tyInt..tyUInt64, tyRange, tyVar, tyLent:
  385. linefmt(p, cpsStmts, "$1 = $2;$n", [rdLoc(dest), rdLoc(src)])
  386. else: internalError(p.config, "genDeepCopy: " & $ty.kind)
  387. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) =
  388. if d.k != locNone:
  389. if lfNoDeepCopy in d.flags: genAssignment(p, d, s, {})
  390. else: genAssignment(p, d, s, {needToCopy})
  391. else:
  392. d = s # ``d`` is free, so fill it with ``s``
  393. proc putDataIntoDest(p: BProc, d: var TLoc, n: PNode, r: Rope) =
  394. var a: TLoc
  395. if d.k != locNone:
  396. # need to generate an assignment here
  397. initLoc(a, locData, n, OnStatic)
  398. a.r = r
  399. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  400. else: genAssignment(p, d, a, {needToCopy})
  401. else:
  402. # we cannot call initLoc() here as that would overwrite
  403. # the flags field!
  404. d.k = locData
  405. d.lode = n
  406. d.r = r
  407. proc putIntoDest(p: BProc, d: var TLoc, n: PNode, r: Rope; s=OnUnknown) =
  408. var a: TLoc
  409. if d.k != locNone:
  410. # need to generate an assignment here
  411. initLoc(a, locExpr, n, s)
  412. a.r = r
  413. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  414. else: genAssignment(p, d, a, {needToCopy})
  415. else:
  416. # we cannot call initLoc() here as that would overwrite
  417. # the flags field!
  418. d.k = locExpr
  419. d.lode = n
  420. d.r = r
  421. proc binaryStmt(p: BProc, e: PNode, d: var TLoc, op: string) =
  422. var a, b: TLoc
  423. if d.k != locNone: internalError(p.config, e.info, "binaryStmt")
  424. initLocExpr(p, e.sons[1], a)
  425. initLocExpr(p, e.sons[2], b)
  426. lineCg(p, cpsStmts, "$1 $2 $3;$n", [rdLoc(a), op, rdLoc(b)])
  427. proc binaryStmtAddr(p: BProc, e: PNode, d: var TLoc, cpname: string) =
  428. var a, b: TLoc
  429. if d.k != locNone: internalError(p.config, e.info, "binaryStmtAddr")
  430. initLocExpr(p, e.sons[1], a)
  431. initLocExpr(p, e.sons[2], b)
  432. lineCg(p, cpsStmts, "#$1($2, $3);$n", [cpname, byRefLoc(p, a), rdLoc(b)])
  433. template unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  434. var a: TLoc
  435. if d.k != locNone: internalError(p.config, e.info, "unaryStmt")
  436. initLocExpr(p, e.sons[1], a)
  437. lineCg(p, cpsStmts, frmt, [rdLoc(a)])
  438. template binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  439. var a, b: TLoc
  440. assert(e.sons[1].typ != nil)
  441. assert(e.sons[2].typ != nil)
  442. initLocExpr(p, e.sons[1], a)
  443. initLocExpr(p, e.sons[2], b)
  444. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)]))
  445. template binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  446. var a, b: TLoc
  447. assert(e.sons[1].typ != nil)
  448. assert(e.sons[2].typ != nil)
  449. initLocExpr(p, e.sons[1], a)
  450. initLocExpr(p, e.sons[2], b)
  451. putIntoDest(p, d, e, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc]))
  452. template unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  453. var a: TLoc
  454. initLocExpr(p, e.sons[1], a)
  455. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdLoc(a)]))
  456. template unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  457. var a: TLoc
  458. initLocExpr(p, e.sons[1], a)
  459. putIntoDest(p, d, e, ropecg(p.module, frmt, [rdCharLoc(a)]))
  460. template binaryArithOverflowRaw(p: BProc, t: PType, a, b: TLoc;
  461. cpname: string): Rope =
  462. var size = getSize(p.config, t)
  463. let storage = if size < p.config.target.intSize: rope("NI")
  464. else: getTypeDesc(p.module, t)
  465. var result = getTempName(p.module)
  466. linefmt(p, cpsLocals, "$1 $2;$n", [storage, result])
  467. lineCg(p, cpsStmts, "$1 = #$2($3, $4);$n", [result, cpname, rdCharLoc(a), rdCharLoc(b)])
  468. if size < p.config.target.intSize or t.kind in {tyRange, tyEnum}:
  469. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
  470. [result, intLiteral(firstOrd(p.config, t)), intLiteral(lastOrd(p.config, t))])
  471. result
  472. proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  473. const
  474. prc: array[mAddI..mPred, string] = [
  475. "addInt", "subInt",
  476. "mulInt", "divInt", "modInt",
  477. "addInt", "subInt"
  478. ]
  479. prc64: array[mAddI..mPred, string] = [
  480. "addInt64", "subInt64",
  481. "mulInt64", "divInt64", "modInt64",
  482. "addInt64", "subInt64"
  483. ]
  484. opr: array[mAddI..mPred, string] = ["+", "-", "*", "/", "%", "+", "-"]
  485. var a, b: TLoc
  486. assert(e.sons[1].typ != nil)
  487. assert(e.sons[2].typ != nil)
  488. initLocExpr(p, e.sons[1], a)
  489. initLocExpr(p, e.sons[2], b)
  490. # skipping 'range' is correct here as we'll generate a proper range check
  491. # later via 'chckRange'
  492. let t = e.typ.skipTypes(abstractRange)
  493. if optOverflowCheck notin p.options:
  494. let res = "($1)($2 $3 $4)" % [getTypeDesc(p.module, e.typ), rdLoc(a), rope(opr[m]), rdLoc(b)]
  495. putIntoDest(p, d, e, res)
  496. else:
  497. let res = binaryArithOverflowRaw(p, t, a, b,
  498. if t.kind == tyInt64: prc64[m] else: prc[m])
  499. putIntoDest(p, d, e, "($#)($#)" % [getTypeDesc(p.module, e.typ), res])
  500. proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  501. var
  502. a: TLoc
  503. t: PType
  504. assert(e.sons[1].typ != nil)
  505. initLocExpr(p, e.sons[1], a)
  506. t = skipTypes(e.typ, abstractRange)
  507. if optOverflowCheck in p.options:
  508. linefmt(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n",
  509. [rdLoc(a), intLiteral(firstOrd(p.config, t))])
  510. case m
  511. of mUnaryMinusI:
  512. putIntoDest(p, d, e, "((NI$2)-($1))" % [rdLoc(a), rope(getSize(p.config, t) * 8)])
  513. of mUnaryMinusI64:
  514. putIntoDest(p, d, e, "-($1)" % [rdLoc(a)])
  515. of mAbsI:
  516. putIntoDest(p, d, e, "($1 > 0? ($1) : -($1))" % [rdLoc(a)])
  517. else:
  518. assert(false, $m)
  519. proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  520. var
  521. a, b: TLoc
  522. s, k: BiggestInt
  523. assert(e.sons[1].typ != nil)
  524. assert(e.sons[2].typ != nil)
  525. initLocExpr(p, e.sons[1], a)
  526. initLocExpr(p, e.sons[2], b)
  527. # BUGFIX: cannot use result-type here, as it may be a boolean
  528. s = max(getSize(p.config, a.t), getSize(p.config, b.t)) * 8
  529. k = getSize(p.config, a.t) * 8
  530. template applyFormat(frmt: untyped) =
  531. putIntoDest(p, d, e, frmt % [
  532. rdLoc(a), rdLoc(b), rope(s),
  533. getSimpleTypeDesc(p.module, e.typ), rope(k)]
  534. )
  535. case op
  536. of mAddF64: applyFormat("(($4)($1) + ($4)($2))")
  537. of mSubF64: applyFormat("(($4)($1) - ($4)($2))")
  538. of mMulF64: applyFormat("(($4)($1) * ($4)($2))")
  539. of mDivF64: applyFormat("(($4)($1) / ($4)($2))")
  540. of mShrI: applyFormat("($4)((NU$5)($1) >> (NU$3)($2))")
  541. of mShlI: applyFormat("($4)((NU$3)($1) << (NU$3)($2))")
  542. of mAshrI: applyFormat("($4)((NI$3)($1) >> (NU$3)($2))")
  543. of mBitandI: applyFormat("($4)($1 & $2)")
  544. of mBitorI: applyFormat("($4)($1 | $2)")
  545. of mBitxorI: applyFormat("($4)($1 ^ $2)")
  546. of mMinI: applyFormat("(($1 <= $2) ? $1 : $2)")
  547. of mMaxI: applyFormat("(($1 >= $2) ? $1 : $2)")
  548. of mMinF64: applyFormat("(($1 <= $2) ? $1 : $2)")
  549. of mMaxF64: applyFormat("(($1 >= $2) ? $1 : $2)")
  550. of mAddU: applyFormat("($4)((NU$3)($1) + (NU$3)($2))")
  551. of mSubU: applyFormat("($4)((NU$3)($1) - (NU$3)($2))")
  552. of mMulU: applyFormat("($4)((NU$3)($1) * (NU$3)($2))")
  553. of mDivU: applyFormat("($4)((NU$3)($1) / (NU$3)($2))")
  554. of mModU: applyFormat("($4)((NU$3)($1) % (NU$3)($2))")
  555. of mEqI: applyFormat("($1 == $2)")
  556. of mLeI: applyFormat("($1 <= $2)")
  557. of mLtI: applyFormat("($1 < $2)")
  558. of mEqF64: applyFormat("($1 == $2)")
  559. of mLeF64: applyFormat("($1 <= $2)")
  560. of mLtF64: applyFormat("($1 < $2)")
  561. of mLeU: applyFormat("((NU$3)($1) <= (NU$3)($2))")
  562. of mLtU: applyFormat("((NU$3)($1) < (NU$3)($2))")
  563. of mLeU64: applyFormat("((NU64)($1) <= (NU64)($2))")
  564. of mLtU64: applyFormat("((NU64)($1) < (NU64)($2))")
  565. of mEqEnum: applyFormat("($1 == $2)")
  566. of mLeEnum: applyFormat("($1 <= $2)")
  567. of mLtEnum: applyFormat("($1 < $2)")
  568. of mEqCh: applyFormat("((NU8)($1) == (NU8)($2))")
  569. of mLeCh: applyFormat("((NU8)($1) <= (NU8)($2))")
  570. of mLtCh: applyFormat("((NU8)($1) < (NU8)($2))")
  571. of mEqB: applyFormat("($1 == $2)")
  572. of mLeB: applyFormat("($1 <= $2)")
  573. of mLtB: applyFormat("($1 < $2)")
  574. of mEqRef: applyFormat("($1 == $2)")
  575. of mEqUntracedRef: applyFormat("($1 == $2)")
  576. of mLePtr: applyFormat("($1 <= $2)")
  577. of mLtPtr: applyFormat("($1 < $2)")
  578. of mXor: applyFormat("($1 != $2)")
  579. else:
  580. assert(false, $op)
  581. proc genEqProc(p: BProc, e: PNode, d: var TLoc) =
  582. var a, b: TLoc
  583. assert(e.sons[1].typ != nil)
  584. assert(e.sons[2].typ != nil)
  585. initLocExpr(p, e.sons[1], a)
  586. initLocExpr(p, e.sons[2], b)
  587. if a.t.skipTypes(abstractInstOwned).callConv == ccClosure:
  588. putIntoDest(p, d, e,
  589. "($1.ClP_0 == $2.ClP_0 && $1.ClE_0 == $2.ClE_0)" % [rdLoc(a), rdLoc(b)])
  590. else:
  591. putIntoDest(p, d, e, "($1 == $2)" % [rdLoc(a), rdLoc(b)])
  592. proc genIsNil(p: BProc, e: PNode, d: var TLoc) =
  593. let t = skipTypes(e.sons[1].typ, abstractRange)
  594. if t.kind == tyProc and t.callConv == ccClosure:
  595. unaryExpr(p, e, d, "($1.ClP_0 == 0)")
  596. else:
  597. unaryExpr(p, e, d, "($1 == 0)")
  598. proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  599. var
  600. a: TLoc
  601. t: PType
  602. assert(e.sons[1].typ != nil)
  603. initLocExpr(p, e.sons[1], a)
  604. t = skipTypes(e.typ, abstractRange)
  605. template applyFormat(frmt: untyped) =
  606. putIntoDest(p, d, e, frmt % [rdLoc(a), rope(getSize(p.config, t) * 8),
  607. getSimpleTypeDesc(p.module, e.typ)])
  608. case op
  609. of mNot:
  610. applyFormat("!($1)")
  611. of mUnaryPlusI:
  612. applyFormat("$1")
  613. of mBitnotI:
  614. applyFormat("($3)((NU$2) ~($1))")
  615. of mUnaryPlusF64:
  616. applyFormat("$1")
  617. of mUnaryMinusF64:
  618. applyFormat("-($1)")
  619. of mAbsF64:
  620. applyFormat("($1 < 0? -($1) : ($1))")
  621. # BUGFIX: fabs() makes problems for Tiny C
  622. of mToFloat:
  623. applyFormat("((double) ($1))")
  624. of mToBiggestFloat:
  625. applyFormat("((double) ($1))")
  626. of mToInt:
  627. applyFormat("float64ToInt32($1)")
  628. of mToBiggestInt:
  629. applyFormat("float64ToInt64($1)")
  630. else:
  631. assert false, $op
  632. proc isCppRef(p: BProc; typ: PType): bool {.inline.} =
  633. result = p.module.compileToCpp and
  634. skipTypes(typ, abstractInstOwned).kind == tyVar and
  635. tfVarIsPtr notin skipTypes(typ, abstractInstOwned).flags
  636. proc genDeref(p: BProc, e: PNode, d: var TLoc) =
  637. let mt = mapType(p.config, e.sons[0].typ)
  638. if mt in {ctArray, ctPtrToArray} and lfEnforceDeref notin d.flags:
  639. # XXX the amount of hacks for C's arrays is incredible, maybe we should
  640. # simply wrap them in a struct? --> Losing auto vectorization then?
  641. expr(p, e.sons[0], d)
  642. if e.sons[0].typ.skipTypes(abstractInstOwned).kind == tyRef:
  643. d.storage = OnHeap
  644. else:
  645. var a: TLoc
  646. var typ = e.sons[0].typ
  647. if typ.kind in {tyUserTypeClass, tyUserTypeClassInst} and typ.isResolvedUserTypeClass:
  648. typ = typ.lastSon
  649. typ = typ.skipTypes(abstractInstOwned)
  650. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and p.module.compileToCpp and e.sons[0].kind == nkHiddenAddr:
  651. initLocExprSingleUse(p, e[0][0], d)
  652. return
  653. else:
  654. initLocExprSingleUse(p, e.sons[0], a)
  655. if d.k == locNone:
  656. # dest = *a; <-- We do not know that 'dest' is on the heap!
  657. # It is completely wrong to set 'd.storage' here, unless it's not yet
  658. # been assigned to.
  659. case typ.kind
  660. of tyRef:
  661. d.storage = OnHeap
  662. of tyVar, tyLent:
  663. d.storage = OnUnknown
  664. if tfVarIsPtr notin typ.flags and p.module.compileToCpp and
  665. e.kind == nkHiddenDeref:
  666. putIntoDest(p, d, e, rdLoc(a), a.storage)
  667. return
  668. of tyPtr:
  669. d.storage = OnUnknown # BUGFIX!
  670. else:
  671. internalError(p.config, e.info, "genDeref " & $typ.kind)
  672. elif p.module.compileToCpp:
  673. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and
  674. e.kind == nkHiddenDeref:
  675. putIntoDest(p, d, e, rdLoc(a), a.storage)
  676. return
  677. if mt == ctPtrToArray and lfEnforceDeref in d.flags:
  678. # we lie about the type for better C interop: 'ptr array[3,T]' is
  679. # translated to 'ptr T', but for deref'ing this produces wrong code.
  680. # See tmissingderef. So we get rid of the deref instead. The codegen
  681. # ends up using 'memcpy' for the array assignment,
  682. # so the '&' and '*' cancel out:
  683. putIntoDest(p, d, lodeTyp(a.t.sons[0]), rdLoc(a), a.storage)
  684. else:
  685. putIntoDest(p, d, e, "(*$1)" % [rdLoc(a)], a.storage)
  686. proc genAddr(p: BProc, e: PNode, d: var TLoc) =
  687. # careful 'addr(myptrToArray)' needs to get the ampersand:
  688. if e.sons[0].typ.skipTypes(abstractInstOwned).kind in {tyRef, tyPtr}:
  689. var a: TLoc
  690. initLocExpr(p, e.sons[0], a)
  691. putIntoDest(p, d, e, "&" & a.r, a.storage)
  692. #Message(e.info, warnUser, "HERE NEW &")
  693. elif mapType(p.config, e.sons[0].typ) == ctArray or isCppRef(p, e.typ):
  694. expr(p, e.sons[0], d)
  695. else:
  696. var a: TLoc
  697. initLocExpr(p, e.sons[0], a)
  698. putIntoDest(p, d, e, addrLoc(p.config, a), a.storage)
  699. template inheritLocation(d: var TLoc, a: TLoc) =
  700. if d.k == locNone: d.storage = a.storage
  701. proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc) =
  702. initLocExpr(p, e.sons[0], a)
  703. if e.sons[1].kind != nkSym: internalError(p.config, e.info, "genRecordFieldAux")
  704. d.inheritLocation(a)
  705. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  706. proc genTupleElem(p: BProc, e: PNode, d: var TLoc) =
  707. var
  708. a: TLoc
  709. i: int
  710. initLocExpr(p, e.sons[0], a)
  711. let tupType = a.t.skipTypes(abstractInst+{tyVar})
  712. assert tupType.kind == tyTuple
  713. d.inheritLocation(a)
  714. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  715. var r = rdLoc(a)
  716. case e.sons[1].kind
  717. of nkIntLit..nkUInt64Lit: i = int(e.sons[1].intVal)
  718. else: internalError(p.config, e.info, "genTupleElem")
  719. addf(r, ".Field$1", [rope(i)])
  720. putIntoDest(p, d, e, r, a.storage)
  721. proc lookupFieldAgain(p: BProc, ty: PType; field: PSym; r: var Rope;
  722. resTyp: ptr PType = nil): PSym =
  723. var ty = ty
  724. assert r != nil
  725. while ty != nil:
  726. ty = ty.skipTypes(skipPtrs)
  727. assert(ty.kind in {tyTuple, tyObject})
  728. result = lookupInRecord(ty.n, field.name)
  729. if result != nil:
  730. if resTyp != nil: resTyp[] = ty
  731. break
  732. if not p.module.compileToCpp: add(r, ".Sup")
  733. ty = ty.sons[0]
  734. if result == nil: internalError(p.config, field.info, "genCheckedRecordField")
  735. proc genRecordField(p: BProc, e: PNode, d: var TLoc) =
  736. var a: TLoc
  737. genRecordFieldAux(p, e, d, a)
  738. var r = rdLoc(a)
  739. var f = e.sons[1].sym
  740. let ty = skipTypes(a.t, abstractInstOwned + tyUserTypeClasses)
  741. if ty.kind == tyTuple:
  742. # we found a unique tuple type which lacks field information
  743. # so we use Field$i
  744. addf(r, ".Field$1", [rope(f.position)])
  745. putIntoDest(p, d, e, r, a.storage)
  746. else:
  747. var rtyp: PType
  748. let field = lookupFieldAgain(p, ty, f, r, addr rtyp)
  749. if field.loc.r == nil and rtyp != nil: fillObjectFields(p.module, rtyp)
  750. if field.loc.r == nil: internalError(p.config, e.info, "genRecordField 3 " & typeToString(ty))
  751. addf(r, ".$1", [field.loc.r])
  752. putIntoDest(p, d, e, r, a.storage)
  753. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc)
  754. proc genFieldCheck(p: BProc, e: PNode, obj: Rope, field: PSym) =
  755. var test, u, v: TLoc
  756. for i in 1 ..< sonsLen(e):
  757. var it = e.sons[i]
  758. assert(it.kind in nkCallKinds)
  759. assert(it.sons[0].kind == nkSym)
  760. let op = it.sons[0].sym
  761. if op.magic == mNot: it = it.sons[1]
  762. let disc = it.sons[2].skipConv
  763. assert(disc.kind == nkSym)
  764. initLoc(test, locNone, it, OnStack)
  765. initLocExpr(p, it.sons[1], u)
  766. initLoc(v, locExpr, disc, OnUnknown)
  767. v.r = obj
  768. v.r.add(".")
  769. v.r.add(disc.sym.loc.r)
  770. genInExprAux(p, it, u, v, test)
  771. let strLit = genStringLiteral(p.module, newStrNode(nkStrLit, field.name.s))
  772. if op.magic == mNot:
  773. linefmt(p, cpsStmts,
  774. "if ($1) #raiseFieldError($2);$n",
  775. [rdLoc(test), strLit])
  776. else:
  777. linefmt(p, cpsStmts,
  778. "if (!($1)) #raiseFieldError($2);$n",
  779. [rdLoc(test), strLit])
  780. proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) =
  781. if optFieldCheck in p.options:
  782. var a: TLoc
  783. genRecordFieldAux(p, e.sons[0], d, a)
  784. let ty = skipTypes(a.t, abstractInst + tyUserTypeClasses)
  785. var r = rdLoc(a)
  786. let f = e.sons[0].sons[1].sym
  787. let field = lookupFieldAgain(p, ty, f, r)
  788. if field.loc.r == nil: fillObjectFields(p.module, ty)
  789. if field.loc.r == nil:
  790. internalError(p.config, e.info, "genCheckedRecordField") # generate the checks:
  791. genFieldCheck(p, e, r, field)
  792. add(r, ropecg(p.module, ".$1", [field.loc.r]))
  793. putIntoDest(p, d, e.sons[0], r, a.storage)
  794. else:
  795. genRecordField(p, e.sons[0], d)
  796. proc genUncheckedArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  797. var a, b: TLoc
  798. initLocExpr(p, x, a)
  799. initLocExpr(p, y, b)
  800. d.inheritLocation(a)
  801. putIntoDest(p, d, n, ropecg(p.module, "$1[$2]", [rdLoc(a), rdCharLoc(b)]),
  802. a.storage)
  803. proc genArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  804. var a, b: TLoc
  805. initLocExpr(p, x, a)
  806. initLocExpr(p, y, b)
  807. var ty = skipTypes(a.t, abstractVarRange + abstractPtrs + tyUserTypeClasses)
  808. var first = intLiteral(firstOrd(p.config, ty))
  809. # emit range check:
  810. if optBoundsCheck in p.options and ty.kind != tyUncheckedArray:
  811. if not isConstExpr(y):
  812. # semantic pass has already checked for const index expressions
  813. if firstOrd(p.config, ty) == 0:
  814. if (firstOrd(p.config, b.t) < firstOrd(p.config, ty)) or (lastOrd(p.config, b.t) > lastOrd(p.config, ty)):
  815. linefmt(p, cpsStmts, "if ((NU)($1) > (NU)($2)) #raiseIndexError2($1, $2);$n",
  816. [rdCharLoc(b), intLiteral(lastOrd(p.config, ty))])
  817. else:
  818. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseIndexError3($1, $2, $3);$n",
  819. [rdCharLoc(b), first, intLiteral(lastOrd(p.config, ty))])
  820. else:
  821. let idx = getOrdValue(y)
  822. if idx < firstOrd(p.config, ty) or idx > lastOrd(p.config, ty):
  823. localError(p.config, x.info, formatErrorIndexBound(idx, firstOrd(p.config, ty), lastOrd(p.config, ty)))
  824. d.inheritLocation(a)
  825. putIntoDest(p, d, n,
  826. ropecg(p.module, "$1[($2)- $3]", [rdLoc(a), rdCharLoc(b), first]), a.storage)
  827. proc genCStringElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  828. var a, b: TLoc
  829. initLocExpr(p, x, a)
  830. initLocExpr(p, y, b)
  831. inheritLocation(d, a)
  832. putIntoDest(p, d, n,
  833. ropecg(p.module, "$1[$2]", [rdLoc(a), rdCharLoc(b)]), a.storage)
  834. proc genBoundsCheck(p: BProc; arr, a, b: TLoc) =
  835. let ty = skipTypes(arr.t, abstractVarRange)
  836. case ty.kind
  837. of tyOpenArray, tyVarargs:
  838. linefmt(p, cpsStmts,
  839. "if ($2-$1 != -1 && " &
  840. "((NU)($1) >= (NU)($3Len_0) || (NU)($2) >= (NU)($3Len_0))) #raiseIndexError();$n",
  841. [rdLoc(a), rdLoc(b), rdLoc(arr)])
  842. of tyArray:
  843. let first = intLiteral(firstOrd(p.config, ty))
  844. linefmt(p, cpsStmts,
  845. "if ($2-$1 != -1 && " &
  846. "($2-$1 < -1 || $1 < $3 || $1 > $4 || $2 < $3 || $2 > $4)) #raiseIndexError();$n",
  847. [rdCharLoc(a), rdCharLoc(b), first, intLiteral(lastOrd(p.config, ty))])
  848. of tySequence, tyString:
  849. linefmt(p, cpsStmts,
  850. "if ($2-$1 != -1 && " &
  851. "((NU)($1) >= (NU)$3 || (NU)($2) >= (NU)$3)) #raiseIndexError();$n",
  852. [rdLoc(a), rdLoc(b), lenExpr(p, arr)])
  853. else: discard
  854. proc genOpenArrayElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  855. var a, b: TLoc
  856. initLocExpr(p, x, a)
  857. initLocExpr(p, y, b) # emit range check:
  858. if optBoundsCheck in p.options:
  859. linefmt(p, cpsStmts, "if ((NU)($1) >= (NU)($2Len_0)) #raiseIndexError2($1,$2Len_0-1);$n",
  860. [rdLoc(b), rdLoc(a)]) # BUGFIX: ``>=`` and not ``>``!
  861. inheritLocation(d, a)
  862. putIntoDest(p, d, n,
  863. ropecg(p.module, "$1[$2]", [rdLoc(a), rdCharLoc(b)]), a.storage)
  864. proc genSeqElem(p: BProc, n, x, y: PNode, d: var TLoc) =
  865. var a, b: TLoc
  866. initLocExpr(p, x, a)
  867. initLocExpr(p, y, b)
  868. var ty = skipTypes(a.t, abstractVarRange)
  869. if ty.kind in {tyRef, tyPtr}:
  870. ty = skipTypes(ty.lastSon, abstractVarRange) # emit range check:
  871. if optBoundsCheck in p.options:
  872. if ty.kind == tyString and (not defined(nimNoZeroTerminator) or optLaxStrings in p.options):
  873. linefmt(p, cpsStmts,
  874. "if ((NU)($1) > (NU)$2) #raiseIndexError2($1,$2);$n",
  875. [rdLoc(b), lenExpr(p, a)])
  876. else:
  877. linefmt(p, cpsStmts,
  878. "if ((NU)($1) >= (NU)$2) #raiseIndexError2($1,$2-1);$n",
  879. [rdLoc(b), lenExpr(p, a)])
  880. if d.k == locNone: d.storage = OnHeap
  881. if skipTypes(a.t, abstractVar).kind in {tyRef, tyPtr}:
  882. a.r = ropecg(p.module, "(*$1)", [a.r])
  883. putIntoDest(p, d, n,
  884. ropecg(p.module, "$1$3[$2]", [rdLoc(a), rdCharLoc(b), dataField(p)]), a.storage)
  885. proc genBracketExpr(p: BProc; n: PNode; d: var TLoc) =
  886. var ty = skipTypes(n.sons[0].typ, abstractVarRange + tyUserTypeClasses)
  887. if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange)
  888. case ty.kind
  889. of tyUncheckedArray: genUncheckedArrayElem(p, n, n.sons[0], n.sons[1], d)
  890. of tyArray: genArrayElem(p, n, n.sons[0], n.sons[1], d)
  891. of tyOpenArray, tyVarargs: genOpenArrayElem(p, n, n.sons[0], n.sons[1], d)
  892. of tySequence, tyString: genSeqElem(p, n, n.sons[0], n.sons[1], d)
  893. of tyCString: genCStringElem(p, n, n.sons[0], n.sons[1], d)
  894. of tyTuple: genTupleElem(p, n, d)
  895. else: internalError(p.config, n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  896. discard getTypeDesc(p.module, n.typ)
  897. proc isSimpleExpr(n: PNode): bool =
  898. # calls all the way down --> can stay expression based
  899. case n.kind
  900. of nkCallKinds, nkDotExpr, nkPar, nkTupleConstr,
  901. nkObjConstr, nkBracket, nkCurly, nkHiddenDeref, nkDerefExpr, nkHiddenAddr,
  902. nkHiddenStdConv, nkHiddenSubConv, nkConv, nkAddr:
  903. for c in n:
  904. if not isSimpleExpr(c): return false
  905. result = true
  906. of nkStmtListExpr:
  907. for i in 0..n.len-2:
  908. if n[i].kind notin {nkCommentStmt, nkEmpty}: return false
  909. result = isSimpleExpr(n.lastSon)
  910. else:
  911. if n.isAtom:
  912. result = true
  913. proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  914. # how to generate code?
  915. # 'expr1 and expr2' becomes:
  916. # result = expr1
  917. # fjmp result, end
  918. # result = expr2
  919. # end:
  920. # ... (result computed)
  921. # BUGFIX:
  922. # a = b or a
  923. # used to generate:
  924. # a = b
  925. # if a: goto end
  926. # a = a
  927. # end:
  928. # now it generates:
  929. # tmp = b
  930. # if tmp: goto end
  931. # tmp = a
  932. # end:
  933. # a = tmp
  934. when false:
  935. #if isSimpleExpr(e) and p.module.compileToCpp:
  936. var tmpA, tmpB: TLoc
  937. #getTemp(p, e.typ, tmpA)
  938. #getTemp(p, e.typ, tmpB)
  939. initLocExprSingleUse(p, e.sons[1], tmpA)
  940. initLocExprSingleUse(p, e.sons[2], tmpB)
  941. tmpB.k = locExpr
  942. if m == mOr:
  943. tmpB.r = "((" & rdLoc(tmpA) & ")||(" & rdLoc(tmpB) & "))"
  944. else:
  945. tmpB.r = "((" & rdLoc(tmpA) & ")&&(" & rdLoc(tmpB) & "))"
  946. if d.k == locNone:
  947. d = tmpB
  948. else:
  949. genAssignment(p, d, tmpB, {})
  950. else:
  951. var
  952. L: TLabel
  953. tmp: TLoc
  954. getTemp(p, e.typ, tmp) # force it into a temp!
  955. inc p.splitDecls
  956. expr(p, e.sons[1], tmp)
  957. L = getLabel(p)
  958. if m == mOr:
  959. lineF(p, cpsStmts, "if ($1) goto $2;$n", [rdLoc(tmp), L])
  960. else:
  961. lineF(p, cpsStmts, "if (!($1)) goto $2;$n", [rdLoc(tmp), L])
  962. expr(p, e.sons[2], tmp)
  963. fixLabel(p, L)
  964. if d.k == locNone:
  965. d = tmp
  966. else:
  967. genAssignment(p, d, tmp, {}) # no need for deep copying
  968. dec p.splitDecls
  969. proc genEcho(p: BProc, n: PNode) =
  970. # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)``
  971. # is threadsafe.
  972. internalAssert p.config, n.kind == nkBracket
  973. if p.config.target.targetOS == osGenode:
  974. # echo directly to the Genode LOG session
  975. var args: Rope = nil
  976. var a: TLoc
  977. for it in n.sons:
  978. if it.skipConv.kind == nkNilLit:
  979. add(args, ", \"\"")
  980. else:
  981. initLocExpr(p, it, a)
  982. add(args, ropecg(p.module, ", Genode::Cstring($1->data, $1->len)", [rdLoc(a)]))
  983. p.module.includeHeader("<base/log.h>")
  984. p.module.includeHeader("<util/string.h>")
  985. linefmt(p, cpsStmts, """Genode::log(""$1);$n""", [args])
  986. else:
  987. if n.len == 0:
  988. linefmt(p, cpsStmts, "#echoBinSafe(NIM_NIL, $1);$n", [n.len])
  989. else:
  990. var a: TLoc
  991. initLocExpr(p, n, a)
  992. linefmt(p, cpsStmts, "#echoBinSafe($1, $2);$n", [a.rdLoc, n.len])
  993. when false:
  994. p.module.includeHeader("<stdio.h>")
  995. linefmt(p, cpsStmts, "printf($1$2);$n",
  996. makeCString(repeat("%s", n.len) & "\L"), [args])
  997. linefmt(p, cpsStmts, "fflush(stdout);$n", [])
  998. proc gcUsage(conf: ConfigRef; n: PNode) =
  999. if conf.selectedGC == gcNone: message(conf, n.info, warnGcMem, n.renderTree)
  1000. proc strLoc(p: BProc; d: TLoc): Rope =
  1001. if p.config.selectedGc == gcDestructors:
  1002. result = byRefLoc(p, d)
  1003. else:
  1004. result = rdLoc(d)
  1005. proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
  1006. # <Nim code>
  1007. # s = 'Hello ' & name & ', how do you feel?' & 'z'
  1008. #
  1009. # <generated C code>
  1010. # {
  1011. # string tmp0;
  1012. # ...
  1013. # tmp0 = rawNewString(6 + 17 + 1 + s2->len);
  1014. # // we cannot generate s = rawNewString(...) here, because
  1015. # // ``s`` may be used on the right side of the expression
  1016. # appendString(tmp0, strlit_1);
  1017. # appendString(tmp0, name);
  1018. # appendString(tmp0, strlit_2);
  1019. # appendChar(tmp0, 'z');
  1020. # asgn(s, tmp0);
  1021. # }
  1022. var a, tmp: TLoc
  1023. getTemp(p, e.typ, tmp)
  1024. var L = 0
  1025. var appends: Rope = nil
  1026. var lens: Rope = nil
  1027. for i in 0 .. sonsLen(e) - 2:
  1028. # compute the length expression:
  1029. initLocExpr(p, e.sons[i + 1], a)
  1030. if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar:
  1031. inc(L)
  1032. add(appends, ropecg(p.module, "#appendChar($1, $2);$n", [strLoc(p, tmp), rdLoc(a)]))
  1033. else:
  1034. if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}:
  1035. inc(L, len(e.sons[i + 1].strVal))
  1036. else:
  1037. add(lens, lenExpr(p, a))
  1038. add(lens, " + ")
  1039. add(appends, ropecg(p.module, "#appendString($1, $2);$n", [strLoc(p, tmp), rdLoc(a)]))
  1040. linefmt(p, cpsStmts, "$1 = #rawNewString($2$3);$n", [tmp.r, lens, L])
  1041. add(p.s(cpsStmts), appends)
  1042. if d.k == locNone:
  1043. d = tmp
  1044. else:
  1045. genAssignment(p, d, tmp, {}) # no need for deep copying
  1046. gcUsage(p.config, e)
  1047. proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
  1048. # <Nim code>
  1049. # s &= 'Hello ' & name & ', how do you feel?' & 'z'
  1050. # // BUG: what if s is on the left side too?
  1051. # <generated C code>
  1052. # {
  1053. # s = resizeString(s, 6 + 17 + 1 + name->len);
  1054. # appendString(s, strlit_1);
  1055. # appendString(s, name);
  1056. # appendString(s, strlit_2);
  1057. # appendChar(s, 'z');
  1058. # }
  1059. var
  1060. a, dest, call: TLoc
  1061. appends, lens: Rope
  1062. assert(d.k == locNone)
  1063. var L = 0
  1064. initLocExpr(p, e.sons[1], dest)
  1065. for i in 0 .. sonsLen(e) - 3:
  1066. # compute the length expression:
  1067. initLocExpr(p, e.sons[i + 2], a)
  1068. if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar:
  1069. inc(L)
  1070. add(appends, ropecg(p.module, "#appendChar($1, $2);$n",
  1071. [strLoc(p, dest), rdLoc(a)]))
  1072. else:
  1073. if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}:
  1074. inc(L, len(e.sons[i + 2].strVal))
  1075. else:
  1076. add(lens, lenExpr(p, a))
  1077. add(lens, " + ")
  1078. add(appends, ropecg(p.module, "#appendString($1, $2);$n",
  1079. [strLoc(p, dest), rdLoc(a)]))
  1080. if p.config.selectedGC == gcDestructors:
  1081. linefmt(p, cpsStmts, "#prepareAdd($1, $2$3);$n",
  1082. [byRefLoc(p, dest), lens, L])
  1083. else:
  1084. initLoc(call, locCall, e, OnHeap)
  1085. call.r = ropecg(p.module, "#resizeString($1, $2$3)", [rdLoc(dest), lens, L])
  1086. genAssignment(p, dest, call, {})
  1087. gcUsage(p.config, e)
  1088. add(p.s(cpsStmts), appends)
  1089. proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
  1090. # seq &= x -->
  1091. # seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x));
  1092. # seq->data[seq->len-1] = x;
  1093. var a, b, dest, tmpL, call: TLoc
  1094. initLocExpr(p, e.sons[1], a)
  1095. initLocExpr(p, e.sons[2], b)
  1096. let seqType = skipTypes(e.sons[1].typ, {tyVar})
  1097. initLoc(call, locCall, e, OnHeap)
  1098. if not p.module.compileToCpp:
  1099. const seqAppendPattern = "($2) #incrSeqV3((TGenericSeq*)($1), $3)"
  1100. call.r = ropecg(p.module, seqAppendPattern, [rdLoc(a),
  1101. getTypeDesc(p.module, e.sons[1].typ),
  1102. genTypeInfo(p.module, seqType, e.info)])
  1103. else:
  1104. const seqAppendPattern = "($2) #incrSeqV3($1, $3)"
  1105. call.r = ropecg(p.module, seqAppendPattern, [rdLoc(a),
  1106. getTypeDesc(p.module, e.sons[1].typ),
  1107. genTypeInfo(p.module, seqType, e.info)])
  1108. # emit the write barrier if required, but we can always move here, so
  1109. # use 'genRefAssign' for the seq.
  1110. genRefAssign(p, a, call)
  1111. #if bt != b.t:
  1112. # echo "YES ", e.info, " new: ", typeToString(bt), " old: ", typeToString(b.t)
  1113. initLoc(dest, locExpr, e.sons[2], OnHeap)
  1114. getIntTemp(p, tmpL)
  1115. lineCg(p, cpsStmts, "$1 = $2->$3++;$n", [tmpL.r, rdLoc(a), lenField(p)])
  1116. dest.r = ropecg(p.module, "$1$3[$2]", [rdLoc(a), tmpL.r, dataField(p)])
  1117. genAssignment(p, dest, b, {needToCopy})
  1118. gcUsage(p.config, e)
  1119. proc genReset(p: BProc, n: PNode) =
  1120. var a: TLoc
  1121. initLocExpr(p, n.sons[1], a)
  1122. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  1123. [addrLoc(p.config, a),
  1124. genTypeInfo(p.module, skipTypes(a.t, {tyVar}), n.info)])
  1125. proc genDefault(p: BProc; n: PNode; d: var TLoc) =
  1126. if d.k == locNone: getTemp(p, n.typ, d, needsInit=true)
  1127. else: resetLoc(p, d)
  1128. proc rawGenNew(p: BProc, a: TLoc, sizeExpr: Rope) =
  1129. var sizeExpr = sizeExpr
  1130. let typ = a.t
  1131. var b: TLoc
  1132. initLoc(b, locExpr, a.lode, OnHeap)
  1133. let refType = typ.skipTypes(abstractInstOwned)
  1134. assert refType.kind == tyRef
  1135. let bt = refType.lastSon
  1136. if sizeExpr.isNil:
  1137. sizeExpr = "sizeof($1)" % [getTypeDesc(p.module, bt)]
  1138. if optNimV2 in p.config.globalOptions:
  1139. b.r = ropecg(p.module, "($1) #nimNewObj($2)",
  1140. [getTypeDesc(p.module, typ), sizeExpr])
  1141. genAssignment(p, a, b, {})
  1142. else:
  1143. let ti = genTypeInfo(p.module, typ, a.lode.info)
  1144. if bt.destructor != nil:
  1145. # the prototype of a destructor is ``=destroy(x: var T)`` and that of a
  1146. # finalizer is: ``proc (x: ref T) {.nimcall.}``. We need to check the calling
  1147. # convention at least:
  1148. if bt.destructor.typ == nil or bt.destructor.typ.callConv != ccDefault:
  1149. localError(p.module.config, a.lode.info,
  1150. "the destructor that is turned into a finalizer needs " &
  1151. "to have the 'nimcall' calling convention")
  1152. var f: TLoc
  1153. initLocExpr(p, newSymNode(bt.destructor), f)
  1154. addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1155. if a.storage == OnHeap and usesWriteBarrier(p.config):
  1156. if canFormAcycle(a.t):
  1157. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", [a.rdLoc])
  1158. else:
  1159. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", [a.rdLoc])
  1160. if p.config.selectedGC == gcGo:
  1161. # newObjRC1() would clash with unsureAsgnRef() - which is used by gcGo to
  1162. # implement the write barrier
  1163. b.r = ropecg(p.module, "($1) #newObj($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1164. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  1165. [addrLoc(p.config, a), b.rdLoc])
  1166. else:
  1167. # use newObjRC1 as an optimization
  1168. b.r = ropecg(p.module, "($1) #newObjRC1($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1169. linefmt(p, cpsStmts, "$1 = $2;$n", [a.rdLoc, b.rdLoc])
  1170. else:
  1171. b.r = ropecg(p.module, "($1) #newObj($2, $3)", [getTypeDesc(p.module, typ), ti, sizeExpr])
  1172. genAssignment(p, a, b, {})
  1173. # set the object type:
  1174. genObjectInit(p, cpsStmts, bt, a, false)
  1175. proc genNew(p: BProc, e: PNode) =
  1176. var a: TLoc
  1177. initLocExpr(p, e.sons[1], a)
  1178. # 'genNew' also handles 'unsafeNew':
  1179. if e.len == 3:
  1180. var se: TLoc
  1181. initLocExpr(p, e.sons[2], se)
  1182. rawGenNew(p, a, se.rdLoc)
  1183. else:
  1184. rawGenNew(p, a, nil)
  1185. gcUsage(p.config, e)
  1186. proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope; lenIsZero: bool) =
  1187. let seqtype = skipTypes(dest.t, abstractVarRange)
  1188. var call: TLoc
  1189. initLoc(call, locExpr, dest.lode, OnHeap)
  1190. if dest.storage == OnHeap and usesWriteBarrier(p.config):
  1191. if canFormAcycle(dest.t):
  1192. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", [dest.rdLoc])
  1193. else:
  1194. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", [dest.rdLoc])
  1195. if not lenIsZero:
  1196. if p.config.selectedGC == gcGo:
  1197. # we need the write barrier
  1198. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", [getTypeDesc(p.module, seqtype),
  1199. genTypeInfo(p.module, seqtype, dest.lode.info), length])
  1200. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n", [addrLoc(p.config, dest), call.rdLoc])
  1201. else:
  1202. call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", [getTypeDesc(p.module, seqtype),
  1203. genTypeInfo(p.module, seqtype, dest.lode.info), length])
  1204. linefmt(p, cpsStmts, "$1 = $2;$n", [dest.rdLoc, call.rdLoc])
  1205. else:
  1206. if lenIsZero:
  1207. call.r = rope"NIM_NIL"
  1208. else:
  1209. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", [getTypeDesc(p.module, seqtype),
  1210. genTypeInfo(p.module, seqtype, dest.lode.info), length])
  1211. genAssignment(p, dest, call, {})
  1212. proc genNewSeq(p: BProc, e: PNode) =
  1213. var a, b: TLoc
  1214. initLocExpr(p, e.sons[1], a)
  1215. initLocExpr(p, e.sons[2], b)
  1216. if p.config.selectedGC == gcDestructors:
  1217. let seqtype = skipTypes(e.sons[1].typ, abstractVarRange)
  1218. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1219. [a.rdLoc, b.rdLoc, getTypeDesc(p.module, seqtype.lastSon),
  1220. getSeqPayloadType(p.module, seqtype)])
  1221. else:
  1222. let lenIsZero = optNilSeqs notin p.options and
  1223. e[2].kind == nkIntLit and e[2].intVal == 0
  1224. genNewSeqAux(p, a, b.rdLoc, lenIsZero)
  1225. gcUsage(p.config, e)
  1226. proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) =
  1227. let seqtype = skipTypes(e.typ, abstractVarRange)
  1228. var a: TLoc
  1229. initLocExpr(p, e.sons[1], a)
  1230. if p.config.selectedGC == gcDestructors:
  1231. if d.k == locNone: getTemp(p, e.typ, d, needsInit=false)
  1232. linefmt(p, cpsStmts, "$1.len = 0; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1233. [d.rdLoc, a.rdLoc, getTypeDesc(p.module, seqtype.lastSon),
  1234. getSeqPayloadType(p.module, seqtype)])
  1235. else:
  1236. putIntoDest(p, d, e, ropecg(p.module,
  1237. "($1)#nimNewSeqOfCap($2, $3)", [
  1238. getTypeDesc(p.module, seqtype),
  1239. genTypeInfo(p.module, seqtype, e.info), a.rdLoc]))
  1240. gcUsage(p.config, e)
  1241. proc genConstExpr(p: BProc, n: PNode): Rope
  1242. proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  1243. if d.k == locNone and n.len > ord(n.kind == nkObjConstr) and n.isDeepConstExpr:
  1244. let t = n.typ
  1245. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1246. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1247. fillLoc(d, locData, n, p.module.tmpBase & rope(id), OnStatic)
  1248. if id == p.module.labels:
  1249. # expression not found in the cache:
  1250. inc(p.module.labels)
  1251. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  1252. [getTypeDesc(p.module, t), d.r, genConstExpr(p, n)])
  1253. result = true
  1254. else:
  1255. result = false
  1256. proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
  1257. #echo rendertree e, " ", e.isDeepConstExpr
  1258. # inheritance in C++ does not allow struct initialization so
  1259. # we skip this step here:
  1260. if not p.module.compileToCpp:
  1261. if handleConstExpr(p, e, d): return
  1262. var t = e.typ.skipTypes(abstractInstOwned)
  1263. let isRef = t.kind == tyRef
  1264. # check if we need to construct the object in a temporary
  1265. var useTemp =
  1266. isRef or
  1267. (d.k notin {locTemp,locLocalVar,locGlobalVar,locParam,locField}) or
  1268. (isPartOf(d.lode, e) != arNo)
  1269. var tmp: TLoc
  1270. var r: Rope
  1271. if useTemp:
  1272. getTemp(p, t, tmp)
  1273. r = rdLoc(tmp)
  1274. if isRef:
  1275. rawGenNew(p, tmp, nil)
  1276. t = t.lastSon.skipTypes(abstractInstOwned)
  1277. r = "(*$1)" % [r]
  1278. gcUsage(p.config, e)
  1279. else:
  1280. constructLoc(p, tmp)
  1281. else:
  1282. resetLoc(p, d)
  1283. r = rdLoc(d)
  1284. discard getTypeDesc(p.module, t)
  1285. let ty = getUniqueType(t)
  1286. for i in 1 ..< e.len:
  1287. let it = e.sons[i]
  1288. var tmp2: TLoc
  1289. tmp2.r = r
  1290. let field = lookupFieldAgain(p, ty, it.sons[0].sym, tmp2.r)
  1291. if field.loc.r == nil: fillObjectFields(p.module, ty)
  1292. if field.loc.r == nil: internalError(p.config, e.info, "genObjConstr")
  1293. if it.len == 3 and optFieldCheck in p.options:
  1294. genFieldCheck(p, it.sons[2], r, field)
  1295. add(tmp2.r, ".")
  1296. add(tmp2.r, field.loc.r)
  1297. if useTemp:
  1298. tmp2.k = locTemp
  1299. tmp2.storage = if isRef: OnHeap else: OnStack
  1300. else:
  1301. tmp2.k = d.k
  1302. tmp2.storage = if isRef: OnHeap else: d.storage
  1303. tmp2.lode = it.sons[1]
  1304. expr(p, it.sons[1], tmp2)
  1305. if useTemp:
  1306. if d.k == locNone:
  1307. d = tmp
  1308. else:
  1309. genAssignment(p, d, tmp, {})
  1310. proc lhsDoesAlias(a, b: PNode): bool =
  1311. for y in b:
  1312. if isPartOf(a, y) != arNo: return true
  1313. proc genSeqConstr(p: BProc, n: PNode, d: var TLoc) =
  1314. var arr, tmp: TLoc
  1315. # bug #668
  1316. let doesAlias = lhsDoesAlias(d.lode, n)
  1317. let dest = if doesAlias: addr(tmp) else: addr(d)
  1318. if doesAlias:
  1319. getTemp(p, n.typ, tmp)
  1320. elif d.k == locNone:
  1321. getTemp(p, n.typ, d)
  1322. let l = intLiteral(sonsLen(n))
  1323. if p.config.selectedGC == gcDestructors:
  1324. let seqtype = n.typ
  1325. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1326. [rdLoc dest[], l, getTypeDesc(p.module, seqtype.lastSon),
  1327. getSeqPayloadType(p.module, seqtype)])
  1328. else:
  1329. # generate call to newSeq before adding the elements per hand:
  1330. genNewSeqAux(p, dest[], l,
  1331. optNilSeqs notin p.options and n.len == 0)
  1332. for i in 0 ..< sonsLen(n):
  1333. initLoc(arr, locExpr, n[i], OnHeap)
  1334. arr.r = ropecg(p.module, "$1$3[$2]", [rdLoc(dest[]), intLiteral(i), dataField(p)])
  1335. arr.storage = OnHeap # we know that sequences are on the heap
  1336. expr(p, n[i], arr)
  1337. gcUsage(p.config, n)
  1338. if doesAlias:
  1339. if d.k == locNone:
  1340. d = tmp
  1341. else:
  1342. genAssignment(p, d, tmp, {})
  1343. proc genArrToSeq(p: BProc, n: PNode, d: var TLoc) =
  1344. var elem, a, arr: TLoc
  1345. if n.sons[1].kind == nkBracket:
  1346. n.sons[1].typ = n.typ
  1347. genSeqConstr(p, n.sons[1], d)
  1348. return
  1349. if d.k == locNone:
  1350. getTemp(p, n.typ, d)
  1351. # generate call to newSeq before adding the elements per hand:
  1352. let L = int(lengthOrd(p.config, n.sons[1].typ))
  1353. if p.config.selectedGC == gcDestructors:
  1354. let seqtype = n.typ
  1355. linefmt(p, cpsStmts, "$1.len = $2; $1.p = ($4*) #newSeqPayload($2, sizeof($3));$n",
  1356. [rdLoc d, L, getTypeDesc(p.module, seqtype.lastSon),
  1357. getSeqPayloadType(p.module, seqtype)])
  1358. else:
  1359. genNewSeqAux(p, d, intLiteral(L), optNilSeqs notin p.options and L == 0)
  1360. initLocExpr(p, n.sons[1], a)
  1361. # bug #5007; do not produce excessive C source code:
  1362. if L < 10:
  1363. for i in 0 ..< L:
  1364. initLoc(elem, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1365. elem.r = ropecg(p.module, "$1$3[$2]", [rdLoc(d), intLiteral(i), dataField(p)])
  1366. elem.storage = OnHeap # we know that sequences are on the heap
  1367. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.sons[1].typ, abstractInst)), a.storage)
  1368. arr.r = ropecg(p.module, "$1[$2]", [rdLoc(a), intLiteral(i)])
  1369. genAssignment(p, elem, arr, {needToCopy})
  1370. else:
  1371. var i: TLoc
  1372. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), i)
  1373. linefmt(p, cpsStmts, "for ($1 = 0; $1 < $2; $1++) {$n", [i.r, L])
  1374. initLoc(elem, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), OnHeap)
  1375. elem.r = ropecg(p.module, "$1$3[$2]", [rdLoc(d), rdLoc(i), dataField(p)])
  1376. elem.storage = OnHeap # we know that sequences are on the heap
  1377. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.sons[1].typ, abstractInst)), a.storage)
  1378. arr.r = ropecg(p.module, "$1[$2]", [rdLoc(a), rdLoc(i)])
  1379. genAssignment(p, elem, arr, {needToCopy})
  1380. lineF(p, cpsStmts, "}$n", [])
  1381. proc genNewFinalize(p: BProc, e: PNode) =
  1382. var
  1383. a, b, f: TLoc
  1384. refType, bt: PType
  1385. ti: Rope
  1386. refType = skipTypes(e.sons[1].typ, abstractVarRange)
  1387. initLocExpr(p, e.sons[1], a)
  1388. initLocExpr(p, e.sons[2], f)
  1389. initLoc(b, locExpr, a.lode, OnHeap)
  1390. ti = genTypeInfo(p.module, refType, e.info)
  1391. addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1392. b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
  1393. getTypeDesc(p.module, refType),
  1394. ti, getTypeDesc(p.module, skipTypes(refType.lastSon, abstractRange))])
  1395. genAssignment(p, a, b, {}) # set the object type:
  1396. bt = skipTypes(refType.lastSon, abstractRange)
  1397. genObjectInit(p, cpsStmts, bt, a, false)
  1398. gcUsage(p.config, e)
  1399. proc genOfHelper(p: BProc; dest: PType; a: Rope; info: TLineInfo): Rope =
  1400. if optNimV2 in p.config.globalOptions:
  1401. result = ropecg(p.module, "#isObj($1.m_type, $2)",
  1402. [a, genTypeInfo2Name(p.module, dest)])
  1403. else:
  1404. # unfortunately 'genTypeInfo' sets tfObjHasKids as a side effect, so we
  1405. # have to call it here first:
  1406. let ti = genTypeInfo(p.module, dest, info)
  1407. if tfFinal in dest.flags or (objHasKidsValid in p.module.flags and
  1408. tfObjHasKids notin dest.flags):
  1409. result = "$1.m_type == $2" % [a, ti]
  1410. else:
  1411. discard cgsym(p.module, "TNimType")
  1412. inc p.module.labels
  1413. let cache = "Nim_OfCheck_CACHE" & p.module.labels.rope
  1414. addf(p.module.s[cfsVars], "static TNimType* $#[2];$n", [cache])
  1415. result = ropecg(p.module, "#isObjWithCache($#.m_type, $#, $#)", [a, ti, cache])
  1416. when false:
  1417. # former version:
  1418. result = ropecg(p.module, "#isObj($1.m_type, $2)",
  1419. [a, genTypeInfo(p.module, dest, info)])
  1420. proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  1421. var a: TLoc
  1422. initLocExpr(p, x, a)
  1423. var dest = skipTypes(typ, typedescPtrs)
  1424. var r = rdLoc(a)
  1425. var nilCheck: Rope = nil
  1426. var t = skipTypes(a.t, abstractInstOwned)
  1427. while t.kind in {tyVar, tyLent, tyPtr, tyRef}:
  1428. if t.kind notin {tyVar, tyLent}: nilCheck = r
  1429. if t.kind notin {tyVar, tyLent} or not p.module.compileToCpp:
  1430. r = ropecg(p.module, "(*$1)", [r])
  1431. t = skipTypes(t.lastSon, typedescInst+{tyOwned})
  1432. discard getTypeDesc(p.module, t)
  1433. if not p.module.compileToCpp:
  1434. while t.kind == tyObject and t.sons[0] != nil:
  1435. add(r, ~".Sup")
  1436. t = skipTypes(t.sons[0], skipPtrs)
  1437. if isObjLackingTypeField(t):
  1438. globalError(p.config, x.info,
  1439. "no 'of' operator available for pure objects")
  1440. if nilCheck != nil:
  1441. r = ropecg(p.module, "(($1) && ($2))", [nilCheck, genOfHelper(p, dest, r, x.info)])
  1442. else:
  1443. r = ropecg(p.module, "($1)", [genOfHelper(p, dest, r, x.info)])
  1444. putIntoDest(p, d, x, r, a.storage)
  1445. proc genOf(p: BProc, n: PNode, d: var TLoc) =
  1446. genOf(p, n.sons[1], n.sons[2].typ, d)
  1447. proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  1448. if optNimV2 in p.config.globalOptions:
  1449. localError(p.config, e.info, "'repr' is not available for --newruntime")
  1450. var a: TLoc
  1451. initLocExpr(p, e.sons[1], a)
  1452. var t = skipTypes(e.sons[1].typ, abstractVarRange)
  1453. case t.kind
  1454. of tyInt..tyInt64, tyUInt..tyUInt64:
  1455. putIntoDest(p, d, e,
  1456. ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]), a.storage)
  1457. of tyFloat..tyFloat128:
  1458. putIntoDest(p, d, e, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]), a.storage)
  1459. of tyBool:
  1460. putIntoDest(p, d, e, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]), a.storage)
  1461. of tyChar:
  1462. putIntoDest(p, d, e, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]), a.storage)
  1463. of tyEnum, tyOrdinal:
  1464. putIntoDest(p, d, e,
  1465. ropecg(p.module, "#reprEnum((NI)$1, $2)", [
  1466. rdLoc(a), genTypeInfo(p.module, t, e.info)]), a.storage)
  1467. of tyString:
  1468. putIntoDest(p, d, e, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]), a.storage)
  1469. of tySet:
  1470. putIntoDest(p, d, e, ropecg(p.module, "#reprSet($1, $2)", [
  1471. addrLoc(p.config, a), genTypeInfo(p.module, t, e.info)]), a.storage)
  1472. of tyOpenArray, tyVarargs:
  1473. var b: TLoc
  1474. case skipTypes(a.t, abstractVarRange).kind
  1475. of tyOpenArray, tyVarargs:
  1476. putIntoDest(p, b, e, "$1, $1Len_0" % [rdLoc(a)], a.storage)
  1477. of tyString, tySequence:
  1478. putIntoDest(p, b, e,
  1479. "$1$3, $2" % [rdLoc(a), lenExpr(p, a), dataField(p)], a.storage)
  1480. of tyArray:
  1481. putIntoDest(p, b, e,
  1482. "$1, $2" % [rdLoc(a), rope(lengthOrd(p.config, a.t))], a.storage)
  1483. else: internalError(p.config, e.sons[0].info, "genRepr()")
  1484. putIntoDest(p, d, e,
  1485. ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
  1486. genTypeInfo(p.module, elemType(t), e.info)]), a.storage)
  1487. of tyCString, tyArray, tyRef, tyPtr, tyPointer, tyNil, tySequence:
  1488. putIntoDest(p, d, e,
  1489. ropecg(p.module, "#reprAny($1, $2)", [
  1490. rdLoc(a), genTypeInfo(p.module, t, e.info)]), a.storage)
  1491. of tyEmpty, tyVoid:
  1492. localError(p.config, e.info, "'repr' doesn't support 'void' type")
  1493. else:
  1494. putIntoDest(p, d, e, ropecg(p.module, "#reprAny($1, $2)",
  1495. [addrLoc(p.config, a), genTypeInfo(p.module, t, e.info)]),
  1496. a.storage)
  1497. gcUsage(p.config, e)
  1498. proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  1499. let t = e.sons[1].typ
  1500. putIntoDest(p, d, e, genTypeInfo(p.module, t, e.info))
  1501. template genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  1502. var a: TLoc
  1503. initLocExpr(p, n.sons[1], a)
  1504. a.r = ropecg(p.module, frmt, [rdLoc(a)])
  1505. a.flags = a.flags - {lfIndirect} # this flag should not be propagated here (not just for HCR)
  1506. if d.k == locNone: getTemp(p, n.typ, d)
  1507. genAssignment(p, d, a, {})
  1508. gcUsage(p.config, n)
  1509. proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1510. var a = e.sons[1]
  1511. if a.kind == nkHiddenAddr: a = a.sons[0]
  1512. var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
  1513. case typ.kind
  1514. of tyOpenArray, tyVarargs:
  1515. # Bug #9279, len(toOpenArray()) has to work:
  1516. if a.kind in nkCallKinds and a[0].kind == nkSym and a[0].sym.magic == mSlice:
  1517. # magic: pass slice to openArray:
  1518. var b, c: TLoc
  1519. initLocExpr(p, a[2], b)
  1520. initLocExpr(p, a[3], c)
  1521. if op == mHigh:
  1522. putIntoDest(p, d, e, ropecg(p.module, "($2)-($1)", [rdLoc(b), rdLoc(c)]))
  1523. else:
  1524. putIntoDest(p, d, e, ropecg(p.module, "($2)-($1)+1", [rdLoc(b), rdLoc(c)]))
  1525. else:
  1526. if op == mHigh: unaryExpr(p, e, d, "($1Len_0-1)")
  1527. else: unaryExpr(p, e, d, "$1Len_0")
  1528. of tyCString:
  1529. if op == mHigh: unaryExpr(p, e, d, "($1 ? (#nimCStrLen($1)-1) : -1)")
  1530. else: unaryExpr(p, e, d, "($1 ? #nimCStrLen($1) : 0)")
  1531. of tyString:
  1532. var a: TLoc
  1533. initLocExpr(p, e.sons[1], a)
  1534. var x = lenExpr(p, a)
  1535. if op == mHigh: x = "($1-1)" % [x]
  1536. putIntoDest(p, d, e, x)
  1537. of tySequence:
  1538. # we go through a temporary here because people write bullshit code.
  1539. var a, tmp: TLoc
  1540. initLocExpr(p, e[1], a)
  1541. getIntTemp(p, tmp)
  1542. var x = lenExpr(p, a)
  1543. if op == mHigh: x = "($1-1)" % [x]
  1544. lineCg(p, cpsStmts, "$1 = $2;$n", [tmp.r, x])
  1545. putIntoDest(p, d, e, tmp.r)
  1546. of tyArray:
  1547. # YYY: length(sideeffect) is optimized away incorrectly?
  1548. if op == mHigh: putIntoDest(p, d, e, rope(lastOrd(p.config, typ)))
  1549. else: putIntoDest(p, d, e, rope(lengthOrd(p.config, typ)))
  1550. else: internalError(p.config, e.info, "genArrayLen()")
  1551. proc makePtrType(baseType: PType): PType =
  1552. result = newType(tyPtr, baseType.owner)
  1553. addSonSkipIntLit(result, baseType)
  1554. proc makeAddr(n: PNode): PNode =
  1555. result = newTree(nkHiddenAddr, n)
  1556. result.typ = makePtrType(n.typ)
  1557. proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  1558. if p.config.selectedGc == gcDestructors:
  1559. e.sons[1] = makeAddr(e[1])
  1560. genCall(p, e, d)
  1561. return
  1562. var a, b, call: TLoc
  1563. assert(d.k == locNone)
  1564. var x = e.sons[1]
  1565. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  1566. initLocExpr(p, x, a)
  1567. initLocExpr(p, e.sons[2], b)
  1568. let t = skipTypes(e.sons[1].typ, {tyVar})
  1569. initLoc(call, locCall, e, OnHeap)
  1570. if not p.module.compileToCpp:
  1571. const setLenPattern = "($3) #setLengthSeqV2(&($1)->Sup, $4, $2)"
  1572. call.r = ropecg(p.module, setLenPattern, [
  1573. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1574. genTypeInfo(p.module, t.skipTypes(abstractInst), e.info)])
  1575. else:
  1576. const setLenPattern = "($3) #setLengthSeqV2($1, $4, $2)"
  1577. call.r = ropecg(p.module, setLenPattern, [
  1578. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1579. genTypeInfo(p.module, t.skipTypes(abstractInst), e.info)])
  1580. genAssignment(p, a, call, {})
  1581. gcUsage(p.config, e)
  1582. proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  1583. if p.config.selectedGc == gcDestructors:
  1584. binaryStmtAddr(p, e, d, "setLengthStrV2")
  1585. else:
  1586. var a, b, call: TLoc
  1587. if d.k != locNone: internalError(p.config, e.info, "genSetLengthStr")
  1588. initLocExpr(p, e.sons[1], a)
  1589. initLocExpr(p, e.sons[2], b)
  1590. initLoc(call, locCall, e, OnHeap)
  1591. call.r = ropecg(p.module, "#setLengthStr($1, $2)", [
  1592. rdLoc(a), rdLoc(b)])
  1593. genAssignment(p, a, call, {})
  1594. gcUsage(p.config, e)
  1595. proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  1596. # swap(a, b) -->
  1597. # temp = a
  1598. # a = b
  1599. # b = temp
  1600. var a, b, tmp: TLoc
  1601. getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp)
  1602. initLocExpr(p, e.sons[1], a) # eval a
  1603. initLocExpr(p, e.sons[2], b) # eval b
  1604. genAssignment(p, tmp, a, {})
  1605. genAssignment(p, a, b, {})
  1606. genAssignment(p, b, tmp, {})
  1607. proc rdSetElemLoc(conf: ConfigRef; a: TLoc, typ: PType): Rope =
  1608. # read a location of an set element; it may need a subtraction operation
  1609. # before the set operation
  1610. result = rdCharLoc(a)
  1611. let setType = typ.skipTypes(abstractPtrs)
  1612. assert(setType.kind == tySet)
  1613. if firstOrd(conf, setType) != 0:
  1614. result = "($1- $2)" % [result, rope(firstOrd(conf, setType))]
  1615. proc fewCmps(conf: ConfigRef; s: PNode): bool =
  1616. # this function estimates whether it is better to emit code
  1617. # for constructing the set or generating a bunch of comparisons directly
  1618. if s.kind != nkCurly: return false
  1619. if (getSize(conf, s.typ) <= conf.target.intSize) and (nfAllConst in s.flags):
  1620. result = false # it is better to emit the set generation code
  1621. elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
  1622. result = true # better not emit the set if int is basetype!
  1623. else:
  1624. result = sonsLen(s) <= 8 # 8 seems to be a good value
  1625. template binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  1626. putIntoDest(p, d, e, frmt % [rdLoc(a), rdSetElemLoc(p.config, b, a.t)])
  1627. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  1628. case int(getSize(p.config, skipTypes(e.sons[1].typ, abstractVar)))
  1629. of 1: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&7U)))!=0)")
  1630. of 2: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&15U)))!=0)")
  1631. of 4: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&31U)))!=0)")
  1632. of 8: binaryExprIn(p, e, a, b, d, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)")
  1633. else: binaryExprIn(p, e, a, b, d, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)")
  1634. template binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  1635. var a, b: TLoc
  1636. assert(d.k == locNone)
  1637. initLocExpr(p, e.sons[1], a)
  1638. initLocExpr(p, e.sons[2], b)
  1639. lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(p.config, b, a.t)])
  1640. proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  1641. var a, b, x, y: TLoc
  1642. if (e.sons[1].kind == nkCurly) and fewCmps(p.config, e.sons[1]):
  1643. # a set constructor but not a constant set:
  1644. # do not emit the set, but generate a bunch of comparisons; and if we do
  1645. # so, we skip the unnecessary range check: This is a semantical extension
  1646. # that code now relies on. :-/ XXX
  1647. let ea = if e.sons[2].kind in {nkChckRange, nkChckRange64}:
  1648. e.sons[2].sons[0]
  1649. else:
  1650. e.sons[2]
  1651. initLocExpr(p, ea, a)
  1652. initLoc(b, locExpr, e, OnUnknown)
  1653. var length = sonsLen(e.sons[1])
  1654. if length > 0:
  1655. b.r = rope("(")
  1656. for i in 0 ..< length:
  1657. let it = e.sons[1].sons[i]
  1658. if it.kind == nkRange:
  1659. initLocExpr(p, it.sons[0], x)
  1660. initLocExpr(p, it.sons[1], y)
  1661. addf(b.r, "$1 >= $2 && $1 <= $3",
  1662. [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
  1663. else:
  1664. initLocExpr(p, it, x)
  1665. addf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
  1666. if i < length - 1: add(b.r, " || ")
  1667. add(b.r, ")")
  1668. else:
  1669. # handle the case of an empty set
  1670. b.r = rope("0")
  1671. putIntoDest(p, d, e, b.r)
  1672. else:
  1673. assert(e.sons[1].typ != nil)
  1674. assert(e.sons[2].typ != nil)
  1675. initLocExpr(p, e.sons[1], a)
  1676. initLocExpr(p, e.sons[2], b)
  1677. genInExprAux(p, e, a, b, d)
  1678. proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1679. const
  1680. lookupOpr: array[mLeSet..mSymDiffSet, string] = [
  1681. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1682. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1683. " if (!$3) break;}$n",
  1684. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1685. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1686. " if (!$3) break;}$n" &
  1687. "if ($3) $3 = (#nimCmpMem($4, $5, $2) != 0);$n",
  1688. "&",
  1689. "|",
  1690. "& ~",
  1691. "^"]
  1692. var a, b, i: TLoc
  1693. var setType = skipTypes(e.sons[1].typ, abstractVar)
  1694. var size = int(getSize(p.config, setType))
  1695. case size
  1696. of 1, 2, 4, 8:
  1697. case op
  1698. of mIncl:
  1699. case size
  1700. of 1: binaryStmtInExcl(p, e, d, "$1 |= ((NU8)1)<<(($2) & 7);$n")
  1701. of 2: binaryStmtInExcl(p, e, d, "$1 |= ((NU16)1)<<(($2) & 15);$n")
  1702. of 4: binaryStmtInExcl(p, e, d, "$1 |= ((NU32)1)<<(($2) & 31);$n")
  1703. of 8: binaryStmtInExcl(p, e, d, "$1 |= ((NU64)1)<<(($2) & 63);$n")
  1704. else: assert(false, $size)
  1705. of mExcl:
  1706. case size
  1707. of 1: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU8)1) << (($2) & 7));$n")
  1708. of 2: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU16)1) << (($2) & 15));$n")
  1709. of 4: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU32)1) << (($2) & 31));$n")
  1710. of 8: binaryStmtInExcl(p, e, d, "$1 &= ~(((NU64)1) << (($2) & 63));$n")
  1711. else: assert(false, $size)
  1712. of mCard:
  1713. if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
  1714. else: unaryExprChar(p, e, d, "#countBits64($1)")
  1715. of mLtSet: binaryExprChar(p, e, d, "(($1 & ~ $2 ==0)&&($1 != $2))")
  1716. of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
  1717. of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
  1718. of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
  1719. of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
  1720. of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
  1721. of mSymDiffSet: binaryExpr(p, e, d, "($1 ^ $2)")
  1722. of mInSet:
  1723. genInOp(p, e, d)
  1724. else: internalError(p.config, e.info, "genSetOp()")
  1725. else:
  1726. case op
  1727. of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n")
  1728. of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n")
  1729. of mCard:
  1730. var a: TLoc
  1731. initLocExpr(p, e.sons[1], a)
  1732. putIntoDest(p, d, e, ropecg(p.module, "#cardSet($1, $2)", [rdCharLoc(a), size]))
  1733. of mLtSet, mLeSet:
  1734. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), i) # our counter
  1735. initLocExpr(p, e.sons[1], a)
  1736. initLocExpr(p, e.sons[2], b)
  1737. if d.k == locNone: getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyBool), d)
  1738. if op == mLtSet:
  1739. linefmt(p, cpsStmts, lookupOpr[mLtSet],
  1740. [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)])
  1741. else:
  1742. linefmt(p, cpsStmts, lookupOpr[mLeSet],
  1743. [rdLoc(i), size, rdLoc(d), rdLoc(a), rdLoc(b)])
  1744. of mEqSet:
  1745. var a, b: TLoc
  1746. assert(e.sons[1].typ != nil)
  1747. assert(e.sons[2].typ != nil)
  1748. initLocExpr(p, e.sons[1], a)
  1749. initLocExpr(p, e.sons[2], b)
  1750. putIntoDest(p, d, e, ropecg(p.module, "(#nimCmpMem($1, $2, $3)==0)", [a.rdCharLoc, b.rdCharLoc, size]))
  1751. of mMulSet, mPlusSet, mMinusSet, mSymDiffSet:
  1752. # we inline the simple for loop for better code generation:
  1753. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), i) # our counter
  1754. initLocExpr(p, e.sons[1], a)
  1755. initLocExpr(p, e.sons[2], b)
  1756. if d.k == locNone: getTemp(p, setType, d)
  1757. lineF(p, cpsStmts,
  1758. "for ($1 = 0; $1 < $2; $1++) $n" &
  1759. " $3[$1] = $4[$1] $6 $5[$1];$n", [
  1760. rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b),
  1761. rope(lookupOpr[op])])
  1762. of mInSet: genInOp(p, e, d)
  1763. else: internalError(p.config, e.info, "genSetOp")
  1764. proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  1765. unaryExprChar(p, e, d, "$1")
  1766. proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
  1767. const
  1768. ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs, tyUncheckedArray}
  1769. # we use whatever C gives us. Except if we have a value-type, we need to go
  1770. # through its address:
  1771. var a: TLoc
  1772. initLocExpr(p, e.sons[1], a)
  1773. let etyp = skipTypes(e.typ, abstractRange+{tyOwned})
  1774. let srcTyp = skipTypes(e.sons[1].typ, abstractRange)
  1775. if etyp.kind in ValueTypes and lfIndirect notin a.flags:
  1776. putIntoDest(p, d, e, "(*($1*) ($2))" %
  1777. [getTypeDesc(p.module, e.typ), addrLoc(p.config, a)], a.storage)
  1778. elif etyp.kind == tyProc and etyp.callConv == ccClosure and srcTyp.callConv != ccClosure:
  1779. putIntoDest(p, d, e, "(($1) ($2))" %
  1780. [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)], a.storage)
  1781. else:
  1782. # C++ does not like direct casts from pointer to shorter integral types
  1783. if srcTyp.kind in {tyPtr, tyPointer} and etyp.kind in IntegralTypes:
  1784. putIntoDest(p, d, e, "(($1) (ptrdiff_t) ($2))" %
  1785. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1786. elif p.config.selectedGc == gcDestructors and etyp.kind in {tySequence, tyString}:
  1787. putIntoDest(p, d, e, "(*($1*) (&$2))" %
  1788. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1789. else:
  1790. putIntoDest(p, d, e, "(($1) ($2))" %
  1791. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.storage)
  1792. proc genCast(p: BProc, e: PNode, d: var TLoc) =
  1793. const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  1794. let
  1795. destt = skipTypes(e.typ, abstractRange)
  1796. srct = skipTypes(e.sons[1].typ, abstractRange)
  1797. if destt.kind in ValueTypes or srct.kind in ValueTypes:
  1798. # 'cast' and some float type involved? --> use a union.
  1799. inc(p.labels)
  1800. var lbl = p.labels.rope
  1801. var tmp: TLoc
  1802. tmp.r = "LOC$1.source" % [lbl]
  1803. linefmt(p, cpsLocals, "union { $1 source; $2 dest; } LOC$3;$n",
  1804. [getTypeDesc(p.module, e.sons[1].typ), getTypeDesc(p.module, e.typ), lbl])
  1805. tmp.k = locExpr
  1806. tmp.lode = lodeTyp srct
  1807. tmp.storage = OnStack
  1808. tmp.flags = {}
  1809. expr(p, e.sons[1], tmp)
  1810. putIntoDest(p, d, e, "LOC$#.dest" % [lbl], tmp.storage)
  1811. else:
  1812. # I prefer the shorter cast version for pointer types -> generate less
  1813. # C code; plus it's the right thing to do for closures:
  1814. genSomeCast(p, e, d)
  1815. proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) =
  1816. var a: TLoc
  1817. var dest = skipTypes(n.typ, abstractVar)
  1818. if optRangeCheck notin p.options:
  1819. initLocExpr(p, n.sons[0], a)
  1820. putIntoDest(p, d, n, "(($1) ($2))" %
  1821. [getTypeDesc(p.module, dest), rdCharLoc(a)], a.storage)
  1822. else:
  1823. let mm = if dest.kind in {tyUInt32, tyUInt64, tyUInt}: "chckRangeU" else: magic
  1824. initLocExpr(p, n.sons[0], a)
  1825. putIntoDest(p, d, lodeTyp dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [
  1826. getTypeDesc(p.module, dest), rdCharLoc(a),
  1827. genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest),
  1828. mm]), a.storage)
  1829. proc genConv(p: BProc, e: PNode, d: var TLoc) =
  1830. let destType = e.typ.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink})
  1831. if sameBackendType(destType, e.sons[1].typ):
  1832. expr(p, e.sons[1], d)
  1833. else:
  1834. genSomeCast(p, e, d)
  1835. proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  1836. var a: TLoc
  1837. initLocExpr(p, n.sons[0], a)
  1838. putIntoDest(p, d, n,
  1839. ropecg(p.module, "#nimToCStringConv($1)", [rdLoc(a)]),
  1840. # "($1 ? $1->data : (NCSTRING)\"\")" % [a.rdLoc],
  1841. a.storage)
  1842. proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  1843. var a: TLoc
  1844. initLocExpr(p, n.sons[0], a)
  1845. putIntoDest(p, d, n,
  1846. ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]),
  1847. a.storage)
  1848. gcUsage(p.config, n)
  1849. proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  1850. var x: TLoc
  1851. var a = e.sons[1]
  1852. var b = e.sons[2]
  1853. if a.kind in {nkStrLit..nkTripleStrLit} and a.strVal == "":
  1854. initLocExpr(p, e.sons[2], x)
  1855. putIntoDest(p, d, e,
  1856. ropecg(p.module, "($1 == 0)", [lenExpr(p, x)]))
  1857. elif b.kind in {nkStrLit..nkTripleStrLit} and b.strVal == "":
  1858. initLocExpr(p, e.sons[1], x)
  1859. putIntoDest(p, d, e,
  1860. ropecg(p.module, "($1 == 0)", [lenExpr(p, x)]))
  1861. else:
  1862. binaryExpr(p, e, d, "#eqStrings($1, $2)")
  1863. proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  1864. if {optNaNCheck, optInfCheck} * p.options != {}:
  1865. const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
  1866. var a, b: TLoc
  1867. assert(e.sons[1].typ != nil)
  1868. assert(e.sons[2].typ != nil)
  1869. initLocExpr(p, e.sons[1], a)
  1870. initLocExpr(p, e.sons[2], b)
  1871. putIntoDest(p, d, e, ropecg(p.module, "(($4)($2) $1 ($4)($3))",
  1872. [opr[m], rdLoc(a), rdLoc(b),
  1873. getSimpleTypeDesc(p.module, e[1].typ)]))
  1874. if optNaNCheck in p.options:
  1875. linefmt(p, cpsStmts, "#nanCheck($1);$n", [rdLoc(d)])
  1876. if optInfCheck in p.options:
  1877. linefmt(p, cpsStmts, "#infCheck($1);$n", [rdLoc(d)])
  1878. else:
  1879. binaryArith(p, e, d, m)
  1880. proc skipAddr(n: PNode): PNode =
  1881. result = if n.kind in {nkAddr, nkHiddenAddr}: n[0] else: n
  1882. proc genWasMoved(p: BProc; n: PNode) =
  1883. var a: TLoc
  1884. initLocExpr(p, n[1].skipAddr, a)
  1885. resetLoc(p, a)
  1886. #linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  1887. # [addrLoc(p.config, a), getTypeDesc(p.module, a.t)])
  1888. proc genMove(p: BProc; n: PNode; d: var TLoc) =
  1889. var a: TLoc
  1890. initLocExpr(p, n[1].skipAddr, a)
  1891. if n.len == 4:
  1892. # generated by liftdestructors:
  1893. var src: TLoc
  1894. initLocExpr(p, n[2], src)
  1895. linefmt(p, cpsStmts, "if ($1.len && $1.p != $2.p) {", [rdLoc(a), rdLoc(src)])
  1896. genStmts(p, n[3])
  1897. linefmt(p, cpsStmts, "}$n$1.len = $2.len; $1.p = $2.p;$n", [rdLoc(a), rdLoc(src)])
  1898. else:
  1899. if d.k == locNone: getTemp(p, n.typ, d)
  1900. genAssignment(p, d, a, {})
  1901. resetLoc(p, a)
  1902. proc genDestroy(p: BProc; n: PNode) =
  1903. if optNimV2 in p.config.globalOptions:
  1904. let arg = n[1].skipAddr
  1905. let t = arg.typ.skipTypes(abstractInst)
  1906. case t.kind
  1907. of tyString:
  1908. var a: TLoc
  1909. initLocExpr(p, arg, a)
  1910. linefmt(p, cpsStmts, "if ($1.p && $1.p->allocator) {$n" &
  1911. " $1.p->allocator->dealloc($1.p->allocator, $1.p, $1.p->cap + 1 + sizeof(NI) + sizeof(void*)); }$n",
  1912. [rdLoc(a)])
  1913. of tySequence:
  1914. var a: TLoc
  1915. initLocExpr(p, arg, a)
  1916. linefmt(p, cpsStmts, "if ($1.p && $1.p->allocator) {$n" &
  1917. " $1.p->allocator->dealloc($1.p->allocator, $1.p, ($1.p->cap * sizeof($2)) + sizeof(NI) + sizeof(void*)); }$n",
  1918. [rdLoc(a), getTypeDesc(p.module, t.lastSon)])
  1919. else: discard "nothing to do"
  1920. else:
  1921. let t = n[1].typ.skipTypes(abstractVar)
  1922. if t.destructor != nil and t.destructor.magic != mDestroy:
  1923. internalError(p.config, n.info, "destructor turned out to be not trivial")
  1924. discard "ignore calls to the default destructor"
  1925. proc genDispose(p: BProc; n: PNode) =
  1926. when false:
  1927. let elemType = n[1].typ.skipTypes(abstractVar).lastSon
  1928. var a: TLoc
  1929. initLocExpr(p, n[1].skipAddr, a)
  1930. if isFinal(elemType):
  1931. if elemType.destructor != nil:
  1932. var destroyCall = newNodeI(nkCall, n.info)
  1933. genStmts(p, destroyCall)
  1934. lineCg(p, cpsStmts, ["#nimRawDispose($#)", rdLoc(a)])
  1935. else:
  1936. # ``nimRawDisposeVirtual`` calls the ``finalizer`` which is the same as the
  1937. # destructor, but it uses the runtime type. Afterwards the memory is freed:
  1938. lineCg(p, cpsStmts, ["#nimDestroyAndDispose($#)", rdLoc(a)])
  1939. proc genEnumToStr(p: BProc, e: PNode, d: var TLoc) =
  1940. const ToStringProcSlot = -4
  1941. let t = e[1].typ.skipTypes(abstractInst)
  1942. var toStrProc: PSym = nil
  1943. for idx, p in items(t.methods):
  1944. if idx == ToStringProcSlot:
  1945. toStrProc = p
  1946. break
  1947. if toStrProc == nil:
  1948. toStrProc = genEnumToStrProc(t, e.info, p.module.g.graph)
  1949. t.methods.add((ToStringProcSlot, toStrProc))
  1950. var n = copyTree(e)
  1951. n[0] = newSymNode(toStrProc)
  1952. expr(p, n, d)
  1953. proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1954. case op
  1955. of mOr, mAnd: genAndOr(p, e, d, op)
  1956. of mNot..mToBiggestInt: unaryArith(p, e, d, op)
  1957. of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  1958. of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  1959. of mShrI..mXor: binaryArith(p, e, d, op)
  1960. of mEqProc: genEqProc(p, e, d)
  1961. of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  1962. of mRepr: genRepr(p, e, d)
  1963. of mGetTypeInfo: genGetTypeInfo(p, e, d)
  1964. of mSwap: genSwap(p, e, d)
  1965. of mUnaryLt:
  1966. if optOverflowCheck notin p.options: unaryExpr(p, e, d, "($1 - 1)")
  1967. else: unaryExpr(p, e, d, "#subInt($1, 1)")
  1968. of mInc, mDec:
  1969. const opr: array[mInc..mDec, string] = ["+=", "-="]
  1970. const fun64: array[mInc..mDec, string] = ["addInt64",
  1971. "subInt64"]
  1972. const fun: array[mInc..mDec, string] = ["addInt",
  1973. "subInt"]
  1974. let underlying = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent, tyRange})
  1975. if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
  1976. binaryStmt(p, e, d, opr[op])
  1977. else:
  1978. var a, b: TLoc
  1979. assert(e.sons[1].typ != nil)
  1980. assert(e.sons[2].typ != nil)
  1981. initLocExpr(p, e.sons[1], a)
  1982. initLocExpr(p, e.sons[2], b)
  1983. let ranged = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent})
  1984. let res = binaryArithOverflowRaw(p, ranged, a, b,
  1985. if underlying.kind == tyInt64: fun64[op] else: fun[op])
  1986. putIntoDest(p, a, e.sons[1], "($#)($#)" % [
  1987. getTypeDesc(p.module, ranged), res])
  1988. of mConStrStr: genStrConcat(p, e, d)
  1989. of mAppendStrCh:
  1990. if p.config.selectedGC == gcDestructors:
  1991. binaryStmtAddr(p, e, d, "nimAddCharV1")
  1992. else:
  1993. var dest, b, call: TLoc
  1994. initLoc(call, locCall, e, OnHeap)
  1995. initLocExpr(p, e.sons[1], dest)
  1996. initLocExpr(p, e.sons[2], b)
  1997. call.r = ropecg(p.module, "#addChar($1, $2)", [rdLoc(dest), rdLoc(b)])
  1998. genAssignment(p, dest, call, {})
  1999. of mAppendStrStr: genStrAppend(p, e, d)
  2000. of mAppendSeqElem:
  2001. if p.config.selectedGc == gcDestructors:
  2002. e.sons[1] = makeAddr(e[1])
  2003. genCall(p, e, d)
  2004. else:
  2005. genSeqElemAppend(p, e, d)
  2006. of mEqStr: genStrEquals(p, e, d)
  2007. of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  2008. of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  2009. of mIsNil: genIsNil(p, e, d)
  2010. of mIntToStr: genDollar(p, e, d, "#nimIntToStr($1)")
  2011. of mInt64ToStr: genDollar(p, e, d, "#nimInt64ToStr($1)")
  2012. of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  2013. of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  2014. of mFloatToStr: genDollar(p, e, d, "#nimFloatToStr($1)")
  2015. of mCStrToStr: genDollar(p, e, d, "#cstrToNimstr($1)")
  2016. of mStrToStr, mUnown: expr(p, e.sons[1], d)
  2017. of mEnumToStr:
  2018. if optNimV2 in p.config.globalOptions:
  2019. genEnumToStr(p, e, d)
  2020. else:
  2021. genRepr(p, e, d)
  2022. of mOf: genOf(p, e, d)
  2023. of mNew: genNew(p, e)
  2024. of mNewFinalize: genNewFinalize(p, e)
  2025. of mNewSeq: genNewSeq(p, e)
  2026. of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  2027. of mSizeOf:
  2028. let t = e.sons[1].typ.skipTypes({tyTypeDesc})
  2029. putIntoDest(p, d, e, "((NI)sizeof($1))" % [getTypeDesc(p.module, t)])
  2030. of mAlignOf:
  2031. let t = e.sons[1].typ.skipTypes({tyTypeDesc})
  2032. if not p.module.compileToCpp:
  2033. p.module.includeHeader("<stdalign.h>")
  2034. putIntoDest(p, d, e, "((NI)alignof($1))" % [getTypeDesc(p.module, t)])
  2035. of mChr: genSomeCast(p, e, d)
  2036. of mOrd: genOrd(p, e, d)
  2037. of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
  2038. genArrayLen(p, e, d, op)
  2039. of mXLenStr:
  2040. if not p.module.compileToCpp:
  2041. unaryExpr(p, e, d, "($1->Sup.len)")
  2042. else:
  2043. unaryExpr(p, e, d, "$1->len")
  2044. of mXLenSeq:
  2045. # see 'taddhigh.nim' for why we need to use a temporary here:
  2046. var a, tmp: TLoc
  2047. initLocExpr(p, e[1], a)
  2048. getIntTemp(p, tmp)
  2049. if not p.module.compileToCpp:
  2050. lineCg(p, cpsStmts, "$1 = $2->Sup.len;$n", [tmp.r, rdLoc(a)])
  2051. else:
  2052. lineCg(p, cpsStmts, "$1 = $2->len;$n", [tmp.r, rdLoc(a)])
  2053. putIntoDest(p, d, e, tmp.r)
  2054. of mGCref: unaryStmt(p, e, d, "if ($1) { #nimGCref($1); }$n")
  2055. of mGCunref: unaryStmt(p, e, d, "if ($1) { #nimGCunref($1); }$n")
  2056. of mSetLengthStr: genSetLengthStr(p, e, d)
  2057. of mSetLengthSeq: genSetLengthSeq(p, e, d)
  2058. of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
  2059. mInSet:
  2060. genSetOp(p, e, d, op)
  2061. of mCopyStr, mCopyStrLast:
  2062. genCall(p, e, d)
  2063. of mNewString, mNewStringOfCap, mExit, mParseBiggestFloat:
  2064. var opr = e.sons[0].sym
  2065. # Why would anyone want to set nodecl to one of these hardcoded magics?
  2066. # - not sure, and it wouldn't work if the symbol behind the magic isn't
  2067. # somehow forward-declared from some other usage, but it is *possible*
  2068. if lfNoDecl notin opr.loc.flags:
  2069. let prc = magicsys.getCompilerProc(p.module.g.graph, $opr.loc.r)
  2070. # HACK:
  2071. # Explicitly add this proc as declared here so the cgsym call doesn't
  2072. # add a forward declaration - without this we could end up with the same
  2073. # 2 forward declarations. That happens because the magic symbol and the original
  2074. # one that shall be used have different ids (even though a call to one is
  2075. # actually a call to the other) so checking into m.declaredProtos with the 2 different ids doesn't work.
  2076. # Why would 2 identical forward declarations be a problem?
  2077. # - in the case of hot code-reloading we generate function pointers instead
  2078. # of forward declarations and in C++ it is an error to redefine a global
  2079. let wasDeclared = containsOrIncl(p.module.declaredProtos, prc.id)
  2080. # Make the function behind the magic get actually generated - this will
  2081. # not lead to a forward declaration! The genCall will lead to one.
  2082. discard cgsym(p.module, $opr.loc.r)
  2083. # make sure we have pointer-initialising code for hot code reloading
  2084. if not wasDeclared and p.hcrOn:
  2085. addf(p.module.s[cfsDynLibInit], "\t$1 = ($2) hcrGetProc($3, \"$1\");$n",
  2086. [mangleDynLibProc(prc), getTypeDesc(p.module, prc.loc.t), getModuleDllPath(p.module, prc)])
  2087. genCall(p, e, d)
  2088. of mDefault: genDefault(p, e, d)
  2089. of mReset: genReset(p, e)
  2090. of mEcho: genEcho(p, e[1].skipConv)
  2091. of mArrToSeq: genArrToSeq(p, e, d)
  2092. of mNLen..mNError, mSlurp..mQuoteAst:
  2093. localError(p.config, e.info, strutils.`%`(errXMustBeCompileTime, e.sons[0].sym.name.s))
  2094. of mSpawn:
  2095. let n = lowerings.wrapProcForSpawn(p.module.g.graph, p.module.module, e, e.typ, nil, nil)
  2096. expr(p, n, d)
  2097. of mParallel:
  2098. when defined(leanCompiler):
  2099. quit "compiler built without support for the 'parallel' statement"
  2100. else:
  2101. let n = semparallel.liftParallel(p.module.g.graph, p.module.module, e)
  2102. expr(p, n, d)
  2103. of mDeepCopy:
  2104. var a, b: TLoc
  2105. let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1]
  2106. initLocExpr(p, x, a)
  2107. initLocExpr(p, e.sons[2], b)
  2108. genDeepCopy(p, a, b)
  2109. of mDotDot, mEqCString: genCall(p, e, d)
  2110. of mWasMoved: genWasMoved(p, e)
  2111. of mMove: genMove(p, e, d)
  2112. of mDestroy: genDestroy(p, e)
  2113. of mAccessEnv: unaryExpr(p, e, d, "$1.ClE_0")
  2114. of mSlice:
  2115. localError(p.config, e.info, "invalid context for 'toOpenArray'; " &
  2116. " 'toOpenArray' is only valid within a call expression")
  2117. else:
  2118. when defined(debugMagics):
  2119. echo p.prc.name.s, " ", p.prc.id, " ", p.prc.flags, " ", p.prc.ast[genericParamsPos].kind
  2120. internalError(p.config, e.info, "genMagicExpr: " & $op)
  2121. proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  2122. # example: { a..b, c, d, e, f..g }
  2123. # we have to emit an expression of the form:
  2124. # nimZeroMem(tmp, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  2125. # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  2126. var
  2127. a, b, idx: TLoc
  2128. if nfAllConst in e.flags:
  2129. putIntoDest(p, d, e, genSetNode(p, e))
  2130. else:
  2131. if d.k == locNone: getTemp(p, e.typ, d)
  2132. if getSize(p.config, e.typ) > 8:
  2133. # big set:
  2134. linefmt(p, cpsStmts, "#nimZeroMem($1, sizeof($2));$n",
  2135. [rdLoc(d), getTypeDesc(p.module, e.typ)])
  2136. for it in e.sons:
  2137. if it.kind == nkRange:
  2138. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), idx) # our counter
  2139. initLocExpr(p, it.sons[0], a)
  2140. initLocExpr(p, it.sons[1], b)
  2141. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  2142. "$2[(NU)($1)>>3] |=(1U<<((NU)($1)&7U));$n", [rdLoc(idx), rdLoc(d),
  2143. rdSetElemLoc(p.config, a, e.typ), rdSetElemLoc(p.config, b, e.typ)])
  2144. else:
  2145. initLocExpr(p, it, a)
  2146. lineF(p, cpsStmts, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n",
  2147. [rdLoc(d), rdSetElemLoc(p.config, a, e.typ)])
  2148. else:
  2149. # small set
  2150. var ts = "NU" & $(getSize(p.config, e.typ) * 8)
  2151. lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)])
  2152. for it in e.sons:
  2153. if it.kind == nkRange:
  2154. getTemp(p, getSysType(p.module.g.graph, unknownLineInfo(), tyInt), idx) # our counter
  2155. initLocExpr(p, it.sons[0], a)
  2156. initLocExpr(p, it.sons[1], b)
  2157. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  2158. "$2 |=(($5)(1)<<(($1)%(sizeof($5)*8)));$n", [
  2159. rdLoc(idx), rdLoc(d), rdSetElemLoc(p.config, a, e.typ),
  2160. rdSetElemLoc(p.config, b, e.typ), rope(ts)])
  2161. else:
  2162. initLocExpr(p, it, a)
  2163. lineF(p, cpsStmts,
  2164. "$1 |=(($3)(1)<<(($2)%(sizeof($3)*8)));$n",
  2165. [rdLoc(d), rdSetElemLoc(p.config, a, e.typ), rope(ts)])
  2166. proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  2167. var rec: TLoc
  2168. if not handleConstExpr(p, n, d):
  2169. let t = n.typ
  2170. discard getTypeDesc(p.module, t) # so that any fields are initialized
  2171. if d.k == locNone: getTemp(p, t, d)
  2172. for i in 0 ..< sonsLen(n):
  2173. var it = n.sons[i]
  2174. if it.kind == nkExprColonExpr: it = it.sons[1]
  2175. initLoc(rec, locExpr, it, d.storage)
  2176. rec.r = "$1.Field$2" % [rdLoc(d), rope(i)]
  2177. rec.flags.incl(lfEnforceDeref)
  2178. expr(p, it, rec)
  2179. proc isConstClosure(n: PNode): bool {.inline.} =
  2180. result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and
  2181. n.sons[1].kind == nkNilLit
  2182. proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  2183. assert n.kind in {nkPar, nkTupleConstr, nkClosure}
  2184. if isConstClosure(n):
  2185. inc(p.module.labels)
  2186. var tmp = "CNSTCLOSURE" & rope(p.module.labels)
  2187. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  2188. [getTypeDesc(p.module, n.typ), tmp, genConstExpr(p, n)])
  2189. putIntoDest(p, d, n, tmp, OnStatic)
  2190. else:
  2191. var tmp, a, b: TLoc
  2192. initLocExpr(p, n.sons[0], a)
  2193. initLocExpr(p, n.sons[1], b)
  2194. if n.sons[0].skipConv.kind == nkClosure:
  2195. internalError(p.config, n.info, "closure to closure created")
  2196. # tasyncawait.nim breaks with this optimization:
  2197. when false:
  2198. if d.k != locNone:
  2199. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  2200. [d.rdLoc, a.rdLoc, b.rdLoc])
  2201. else:
  2202. getTemp(p, n.typ, tmp)
  2203. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  2204. [tmp.rdLoc, a.rdLoc, b.rdLoc])
  2205. putLocIntoDest(p, d, tmp)
  2206. proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  2207. var arr: TLoc
  2208. if not handleConstExpr(p, n, d):
  2209. if d.k == locNone: getTemp(p, n.typ, d)
  2210. for i in 0 ..< sonsLen(n):
  2211. initLoc(arr, locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), d.storage)
  2212. arr.r = "$1[$2]" % [rdLoc(d), intLiteral(i)]
  2213. expr(p, n.sons[i], arr)
  2214. proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  2215. requestConstImpl(p, sym)
  2216. assert((sym.loc.r != nil) and (sym.loc.t != nil))
  2217. putLocIntoDest(p, d, sym.loc)
  2218. template genStmtListExprImpl(exprOrStmt) {.dirty.} =
  2219. #let hasNimFrame = magicsys.getCompilerProc("nimFrame") != nil
  2220. let hasNimFrame = p.prc != nil and
  2221. sfSystemModule notin p.module.module.flags and
  2222. optStackTrace in p.prc.options
  2223. var frameName: Rope = nil
  2224. for i in 0 .. n.len - 2:
  2225. let it = n[i]
  2226. if it.kind == nkComesFrom:
  2227. if hasNimFrame and frameName == nil:
  2228. inc p.labels
  2229. frameName = "FR" & rope(p.labels) & "_"
  2230. let theMacro = it[0].sym
  2231. add p.s(cpsStmts), initFrameNoDebug(p, frameName,
  2232. makeCString theMacro.name.s,
  2233. quotedFilename(p.config, theMacro.info), it.info.line.int)
  2234. else:
  2235. genStmts(p, it)
  2236. if n.len > 0: exprOrStmt
  2237. if frameName != nil:
  2238. add p.s(cpsStmts), deinitFrameNoDebug(p, frameName)
  2239. proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  2240. genStmtListExprImpl:
  2241. expr(p, n[n.len - 1], d)
  2242. proc genStmtList(p: BProc, n: PNode) =
  2243. genStmtListExprImpl:
  2244. genStmts(p, n[n.len - 1])
  2245. proc upConv(p: BProc, n: PNode, d: var TLoc) =
  2246. var a: TLoc
  2247. initLocExpr(p, n.sons[0], a)
  2248. let dest = skipTypes(n.typ, abstractPtrs)
  2249. if optObjCheck in p.options and not isObjLackingTypeField(dest):
  2250. var r = rdLoc(a)
  2251. var nilCheck: Rope = nil
  2252. var t = skipTypes(a.t, abstractInst)
  2253. while t.kind in {tyVar, tyLent, tyPtr, tyRef}:
  2254. if t.kind notin {tyVar, tyLent}: nilCheck = r
  2255. if t.kind notin {tyVar, tyLent} or not p.module.compileToCpp:
  2256. r = "(*$1)" % [r]
  2257. t = skipTypes(t.lastSon, abstractInst)
  2258. discard getTypeDesc(p.module, t)
  2259. if not p.module.compileToCpp:
  2260. while t.kind == tyObject and t.sons[0] != nil:
  2261. add(r, ".Sup")
  2262. t = skipTypes(t.sons[0], skipPtrs)
  2263. let checkFor = if optNimV2 in p.config.globalOptions:
  2264. genTypeInfo2Name(p.module, dest)
  2265. else:
  2266. genTypeInfo(p.module, dest, n.info)
  2267. if nilCheck != nil:
  2268. linefmt(p, cpsStmts, "if ($1) #chckObj($2.m_type, $3);$n",
  2269. [nilCheck, r, checkFor])
  2270. else:
  2271. linefmt(p, cpsStmts, "#chckObj($1.m_type, $2);$n",
  2272. [r, checkFor])
  2273. if n.sons[0].typ.kind != tyObject:
  2274. putIntoDest(p, d, n,
  2275. "(($1) ($2))" % [getTypeDesc(p.module, n.typ), rdLoc(a)], a.storage)
  2276. else:
  2277. putIntoDest(p, d, n, "(*($1*) ($2))" %
  2278. [getTypeDesc(p.module, dest), addrLoc(p.config, a)], a.storage)
  2279. proc downConv(p: BProc, n: PNode, d: var TLoc) =
  2280. if p.module.compileToCpp:
  2281. discard getTypeDesc(p.module, skipTypes(n[0].typ, abstractPtrs))
  2282. expr(p, n.sons[0], d) # downcast does C++ for us
  2283. else:
  2284. var dest = skipTypes(n.typ, abstractPtrs)
  2285. var arg = n.sons[0]
  2286. while arg.kind == nkObjDownConv: arg = arg.sons[0]
  2287. var src = skipTypes(arg.typ, abstractPtrs)
  2288. discard getTypeDesc(p.module, src)
  2289. var a: TLoc
  2290. initLocExpr(p, arg, a)
  2291. var r = rdLoc(a)
  2292. let isRef = skipTypes(arg.typ, abstractInstOwned).kind in {tyRef, tyPtr, tyVar, tyLent}
  2293. if isRef:
  2294. add(r, "->Sup")
  2295. else:
  2296. add(r, ".Sup")
  2297. for i in 2 .. abs(inheritanceDiff(dest, src)): add(r, ".Sup")
  2298. if isRef:
  2299. # it can happen that we end up generating '&&x->Sup' here, so we pack
  2300. # the '&x->Sup' into a temporary and then those address is taken
  2301. # (see bug #837). However sometimes using a temporary is not correct:
  2302. # init(TFigure(my)) # where it is passed to a 'var TFigure'. We test
  2303. # this by ensuring the destination is also a pointer:
  2304. if d.k == locNone and skipTypes(n.typ, abstractInstOwned).kind in {tyRef, tyPtr, tyVar, tyLent}:
  2305. getTemp(p, n.typ, d)
  2306. linefmt(p, cpsStmts, "$1 = &$2;$n", [rdLoc(d), r])
  2307. else:
  2308. r = "&" & r
  2309. putIntoDest(p, d, n, r, a.storage)
  2310. else:
  2311. putIntoDest(p, d, n, r, a.storage)
  2312. proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) =
  2313. let t = n.typ
  2314. discard getTypeDesc(p.module, t) # so that any fields are initialized
  2315. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  2316. let tmp = p.module.tmpBase & rope(id)
  2317. if id == p.module.labels:
  2318. # expression not found in the cache:
  2319. inc(p.module.labels)
  2320. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  2321. [getTypeDesc(p.module, t), tmp, genConstExpr(p, n)])
  2322. if d.k == locNone:
  2323. fillLoc(d, locData, n, tmp, OnStatic)
  2324. else:
  2325. putDataIntoDest(p, d, n, tmp)
  2326. # This fixes bug #4551, but we really need better dataflow
  2327. # analysis to make this 100% safe.
  2328. if t.kind notin {tySequence, tyString}:
  2329. d.storage = OnStatic
  2330. proc expr(p: BProc, n: PNode, d: var TLoc) =
  2331. p.currLineInfo = n.info
  2332. case n.kind
  2333. of nkSym:
  2334. var sym = n.sym
  2335. case sym.kind
  2336. of skMethod:
  2337. if {sfDispatcher, sfForward} * sym.flags != {}:
  2338. # we cannot produce code for the dispatcher yet:
  2339. fillProcLoc(p.module, n)
  2340. genProcPrototype(p.module, sym)
  2341. else:
  2342. genProc(p.module, sym)
  2343. putLocIntoDest(p, d, sym.loc)
  2344. of skProc, skConverter, skIterator, skFunc:
  2345. #if sym.kind == skIterator:
  2346. # echo renderTree(sym.getBody, {renderIds})
  2347. if sfCompileTime in sym.flags:
  2348. localError(p.config, n.info, "request to generate code for .compileTime proc: " &
  2349. sym.name.s)
  2350. genProc(p.module, sym)
  2351. if sym.loc.r == nil or sym.loc.lode == nil:
  2352. internalError(p.config, n.info, "expr: proc not init " & sym.name.s)
  2353. putLocIntoDest(p, d, sym.loc)
  2354. of skConst:
  2355. if isSimpleConst(sym.typ):
  2356. putIntoDest(p, d, n, genLiteral(p, sym.ast, sym.typ), OnStatic)
  2357. else:
  2358. genComplexConst(p, sym, d)
  2359. of skEnumField:
  2360. # we never reach this case - as of the time of this comment,
  2361. # skEnumField is folded to an int in semfold.nim, but this code
  2362. # remains for robustness
  2363. putIntoDest(p, d, n, rope(sym.position))
  2364. of skVar, skForVar, skResult, skLet:
  2365. if {sfGlobal, sfThread} * sym.flags != {}:
  2366. genVarPrototype(p.module, n)
  2367. if sym.loc.r == nil or sym.loc.t == nil:
  2368. #echo "FAILED FOR PRCO ", p.prc.name.s
  2369. #echo renderTree(p.prc.ast, {renderIds})
  2370. internalError p.config, n.info, "expr: var not init " & sym.name.s & "_" & $sym.id
  2371. if sfThread in sym.flags:
  2372. accessThreadLocalVar(p, sym)
  2373. if emulatedThreadVars(p.config):
  2374. putIntoDest(p, d, sym.loc.lode, "NimTV_->" & sym.loc.r)
  2375. else:
  2376. putLocIntoDest(p, d, sym.loc)
  2377. else:
  2378. putLocIntoDest(p, d, sym.loc)
  2379. of skTemp:
  2380. if sym.loc.r == nil or sym.loc.t == nil:
  2381. #echo "FAILED FOR PRCO ", p.prc.name.s
  2382. #echo renderTree(p.prc.ast, {renderIds})
  2383. internalError(p.config, n.info, "expr: temp not init " & sym.name.s & "_" & $sym.id)
  2384. putLocIntoDest(p, d, sym.loc)
  2385. of skParam:
  2386. if sym.loc.r == nil or sym.loc.t == nil:
  2387. # echo "FAILED FOR PRCO ", p.prc.name.s
  2388. # debug p.prc.typ.n
  2389. # echo renderTree(p.prc.ast, {renderIds})
  2390. internalError(p.config, n.info, "expr: param not init " & sym.name.s & "_" & $sym.id)
  2391. putLocIntoDest(p, d, sym.loc)
  2392. else: internalError(p.config, n.info, "expr(" & $sym.kind & "); unknown symbol")
  2393. of nkNilLit:
  2394. if not isEmptyType(n.typ):
  2395. putIntoDest(p, d, n, genLiteral(p, n))
  2396. of nkStrLit..nkTripleStrLit:
  2397. putDataIntoDest(p, d, n, genLiteral(p, n))
  2398. of nkIntLit..nkUInt64Lit,
  2399. nkFloatLit..nkFloat128Lit, nkCharLit:
  2400. putIntoDest(p, d, n, genLiteral(p, n))
  2401. of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkPostfix, nkCommand,
  2402. nkCallStrLit:
  2403. genLineDir(p, n) # may be redundant, it is generated in fixupCall as well
  2404. let op = n.sons[0]
  2405. if n.typ.isNil:
  2406. # discard the value:
  2407. var a: TLoc
  2408. if op.kind == nkSym and op.sym.magic != mNone:
  2409. genMagicExpr(p, n, a, op.sym.magic)
  2410. else:
  2411. genCall(p, n, a)
  2412. else:
  2413. # load it into 'd':
  2414. if op.kind == nkSym and op.sym.magic != mNone:
  2415. genMagicExpr(p, n, d, op.sym.magic)
  2416. else:
  2417. genCall(p, n, d)
  2418. of nkCurly:
  2419. if isDeepConstExpr(n) and n.len != 0:
  2420. putIntoDest(p, d, n, genSetNode(p, n))
  2421. else:
  2422. genSetConstr(p, n, d)
  2423. of nkBracket:
  2424. if isDeepConstExpr(n) and n.len != 0:
  2425. exprComplexConst(p, n, d)
  2426. elif skipTypes(n.typ, abstractVarRange).kind == tySequence:
  2427. genSeqConstr(p, n, d)
  2428. else:
  2429. genArrayConstr(p, n, d)
  2430. of nkPar, nkTupleConstr:
  2431. if n.typ != nil and n.typ.kind == tyProc and n.len == 2:
  2432. genClosure(p, n, d)
  2433. elif isDeepConstExpr(n) and n.len != 0:
  2434. exprComplexConst(p, n, d)
  2435. else:
  2436. genTupleConstr(p, n, d)
  2437. of nkObjConstr: genObjConstr(p, n, d)
  2438. of nkCast: genCast(p, n, d)
  2439. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, d)
  2440. of nkHiddenAddr, nkAddr: genAddr(p, n, d)
  2441. of nkBracketExpr: genBracketExpr(p, n, d)
  2442. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, d)
  2443. of nkDotExpr: genRecordField(p, n, d)
  2444. of nkCheckedFieldExpr: genCheckedRecordField(p, n, d)
  2445. of nkBlockExpr, nkBlockStmt: genBlock(p, n, d)
  2446. of nkStmtListExpr: genStmtListExpr(p, n, d)
  2447. of nkStmtList: genStmtList(p, n)
  2448. of nkIfExpr, nkIfStmt: genIf(p, n, d)
  2449. of nkWhen:
  2450. # This should be a "when nimvm" node.
  2451. expr(p, n.sons[1].sons[0], d)
  2452. of nkObjDownConv: downConv(p, n, d)
  2453. of nkObjUpConv: upConv(p, n, d)
  2454. of nkChckRangeF: genRangeChck(p, n, d, "chckRangeF")
  2455. of nkChckRange64: genRangeChck(p, n, d, "chckRange64")
  2456. of nkChckRange: genRangeChck(p, n, d, "chckRange")
  2457. of nkStringToCString: convStrToCStr(p, n, d)
  2458. of nkCStringToString: convCStrToStr(p, n, d)
  2459. of nkLambdaKinds:
  2460. var sym = n.sons[namePos].sym
  2461. genProc(p.module, sym)
  2462. if sym.loc.r == nil or sym.loc.lode == nil:
  2463. internalError(p.config, n.info, "expr: proc not init " & sym.name.s)
  2464. putLocIntoDest(p, d, sym.loc)
  2465. of nkClosure: genClosure(p, n, d)
  2466. of nkEmpty: discard
  2467. of nkWhileStmt: genWhileStmt(p, n)
  2468. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2469. of nkConstSection: discard # consts generated lazily on use
  2470. of nkForStmt: internalError(p.config, n.info, "for statement not eliminated")
  2471. of nkCaseStmt: genCase(p, n, d)
  2472. of nkReturnStmt: genReturnStmt(p, n)
  2473. of nkBreakStmt: genBreakStmt(p, n)
  2474. of nkAsgn:
  2475. if nfPreventCg notin n.flags:
  2476. genAsgn(p, n, fastAsgn=false)
  2477. of nkFastAsgn:
  2478. if nfPreventCg notin n.flags:
  2479. # transf is overly aggressive with 'nkFastAsgn', so we work around here.
  2480. # See tests/run/tcnstseq3 for an example that would fail otherwise.
  2481. genAsgn(p, n, fastAsgn=p.prc != nil)
  2482. of nkDiscardStmt:
  2483. let ex = n[0]
  2484. if ex.kind != nkEmpty:
  2485. genLineDir(p, n)
  2486. var a: TLoc
  2487. initLocExprSingleUse(p, ex, a)
  2488. line(p, cpsStmts, "(void)(" & a.r & ");\L")
  2489. of nkAsmStmt: genAsmStmt(p, n)
  2490. of nkTryStmt, nkHiddenTryStmt:
  2491. if p.module.compileToCpp and optNoCppExceptions notin p.config.globalOptions:
  2492. genTryCpp(p, n, d)
  2493. else:
  2494. genTry(p, n, d)
  2495. of nkRaiseStmt: genRaiseStmt(p, n)
  2496. of nkTypeSection:
  2497. # we have to emit the type information for object types here to support
  2498. # separate compilation:
  2499. genTypeSection(p.module, n)
  2500. of nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  2501. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2502. nkFromStmt, nkTemplateDef, nkMacroDef, nkStaticStmt:
  2503. discard
  2504. of nkPragma: genPragma(p, n)
  2505. of nkPragmaBlock: expr(p, n.lastSon, d)
  2506. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  2507. if n.sons[genericParamsPos].kind == nkEmpty:
  2508. var prc = n.sons[namePos].sym
  2509. # due to a bug/limitation in the lambda lifting, unused inner procs
  2510. # are not transformed correctly. We work around this issue (#411) here
  2511. # by ensuring it's no inner proc (owner is a module):
  2512. if prc.skipGenericOwner.kind == skModule and sfCompileTime notin prc.flags:
  2513. if ({sfExportc, sfCompilerProc} * prc.flags == {sfExportc}) or
  2514. (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or
  2515. (prc.kind == skMethod):
  2516. # we have not only the header:
  2517. if prc.getBody.kind != nkEmpty or lfDynamicLib in prc.loc.flags:
  2518. genProc(p.module, prc)
  2519. of nkParForStmt: genParForStmt(p, n)
  2520. of nkState: genState(p, n)
  2521. of nkGotoState:
  2522. # simply never set it back to 0 here from here on...
  2523. inc p.splitDecls
  2524. genGotoState(p, n)
  2525. of nkBreakState: genBreakState(p, n, d)
  2526. else: internalError(p.config, n.info, "expr(" & $n.kind & "); unknown node kind")
  2527. proc genNamedConstExpr(p: BProc, n: PNode): Rope =
  2528. if n.kind == nkExprColonExpr: result = genConstExpr(p, n.sons[1])
  2529. else: result = genConstExpr(p, n)
  2530. proc getDefaultValue(p: BProc; typ: PType; info: TLineInfo): Rope =
  2531. var t = skipTypes(typ, abstractRange+{tyOwned}-{tyTypeDesc})
  2532. case t.kind
  2533. of tyBool: result = rope"NIM_FALSE"
  2534. of tyEnum, tyChar, tyInt..tyInt64, tyUInt..tyUInt64: result = rope"0"
  2535. of tyFloat..tyFloat128: result = rope"0.0"
  2536. of tyCString, tyString, tyVar, tyLent, tyPointer, tyPtr, tySequence, tyUntyped,
  2537. tyTyped, tyTypeDesc, tyStatic, tyRef, tyNil:
  2538. result = rope"NIM_NIL"
  2539. of tyProc:
  2540. if t.callConv != ccClosure:
  2541. result = rope"NIM_NIL"
  2542. else:
  2543. result = rope"{NIM_NIL, NIM_NIL}"
  2544. of tyObject:
  2545. if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2546. result = "{{$1}}" % [genTypeInfo(p.module, t, info)]
  2547. else:
  2548. result = rope"{}"
  2549. of tyTuple:
  2550. result = rope"{"
  2551. for i in 0 ..< typ.len:
  2552. if i > 0: result.add ", "
  2553. result.add getDefaultValue(p, typ.sons[i], info)
  2554. result.add "}"
  2555. of tyArray: result = rope"{}"
  2556. of tySet:
  2557. if mapType(p.config, t) == ctArray: result = rope"{}"
  2558. else: result = rope"0"
  2559. else:
  2560. globalError(p.config, info, "cannot create null element for: " & $t.kind)
  2561. proc getNullValueAux(p: BProc; t: PType; obj, cons: PNode,
  2562. result: var Rope; count: var int) =
  2563. case obj.kind
  2564. of nkRecList:
  2565. for it in obj.sons:
  2566. getNullValueAux(p, t, it, cons, result, count)
  2567. of nkRecCase:
  2568. getNullValueAux(p, t, obj.sons[0], cons, result, count)
  2569. for i in 1 ..< sonsLen(obj):
  2570. getNullValueAux(p, t, lastSon(obj.sons[i]), cons, result, count)
  2571. of nkSym:
  2572. if count > 0: result.add ", "
  2573. inc count
  2574. let field = obj.sym
  2575. for i in 1..<cons.len:
  2576. if cons[i].kind == nkExprColonExpr:
  2577. if cons[i][0].sym.name.id == field.name.id:
  2578. result.add genConstExpr(p, cons[i][1])
  2579. return
  2580. elif i == field.position:
  2581. result.add genConstExpr(p, cons[i])
  2582. return
  2583. # not found, produce default value:
  2584. result.add getDefaultValue(p, field.typ, cons.info)
  2585. else:
  2586. localError(p.config, cons.info, "cannot create null element for: " & $obj)
  2587. proc getNullValueAuxT(p: BProc; orig, t: PType; obj, cons: PNode,
  2588. result: var Rope; count: var int) =
  2589. var base = t.sons[0]
  2590. let oldRes = result
  2591. if not p.module.compileToCpp: result.add "{"
  2592. let oldcount = count
  2593. if base != nil:
  2594. base = skipTypes(base, skipPtrs)
  2595. getNullValueAuxT(p, orig, base, base.n, cons, result, count)
  2596. elif not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2597. addf(result, "$1", [genTypeInfo(p.module, orig, obj.info)])
  2598. inc count
  2599. getNullValueAux(p, t, obj, cons, result, count)
  2600. # do not emit '{}' as that is not valid C:
  2601. if oldcount == count: result = oldres
  2602. elif not p.module.compileToCpp: result.add "}"
  2603. proc genConstObjConstr(p: BProc; n: PNode): Rope =
  2604. result = nil
  2605. let t = n.typ.skipTypes(abstractInstOwned)
  2606. var count = 0
  2607. #if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2608. # addf(result, "{$1}", [genTypeInfo(p.module, t)])
  2609. # inc count
  2610. getNullValueAuxT(p, t, t, t.n, n, result, count)
  2611. if p.module.compileToCpp:
  2612. result = "{$1}$n" % [result]
  2613. proc genConstSimpleList(p: BProc, n: PNode): Rope =
  2614. var length = sonsLen(n)
  2615. result = rope("{")
  2616. for i in 0 .. length - 2:
  2617. addf(result, "$1,$n", [genNamedConstExpr(p, n.sons[i])])
  2618. if length > 0:
  2619. add(result, genNamedConstExpr(p, n.sons[length - 1]))
  2620. addf(result, "}$n", [])
  2621. proc genConstSeq(p: BProc, n: PNode, t: PType): Rope =
  2622. var data = "{{$1, $1 | NIM_STRLIT_FLAG}" % [n.len.rope]
  2623. if n.len > 0:
  2624. # array part needs extra curlies:
  2625. data.add(", {")
  2626. for i in 0 ..< n.len:
  2627. if i > 0: data.addf(",$n", [])
  2628. data.add genConstExpr(p, n.sons[i])
  2629. data.add("}")
  2630. data.add("}")
  2631. result = getTempName(p.module)
  2632. let base = t.skipTypes(abstractInst).sons[0]
  2633. appcg(p.module, cfsData,
  2634. "NIM_CONST struct {$n" &
  2635. " #TGenericSeq Sup;$n" &
  2636. " $1 data[$2];$n" &
  2637. "} $3 = $4;$n", [
  2638. getTypeDesc(p.module, base), n.len, result, data])
  2639. result = "(($1)&$2)" % [getTypeDesc(p.module, t), result]
  2640. proc genConstSeqV2(p: BProc, n: PNode, t: PType): Rope =
  2641. var data = rope"{"
  2642. for i in 0 ..< n.len:
  2643. if i > 0: data.addf(",$n", [])
  2644. data.add genConstExpr(p, n.sons[i])
  2645. data.add("}")
  2646. let payload = getTempName(p.module)
  2647. let base = t.skipTypes(abstractInst).sons[0]
  2648. appcg(p.module, cfsData,
  2649. "static const struct {$n" &
  2650. " NI cap; void* allocator; $1 data[$2];$n" &
  2651. "} $3 = {$2, NIM_NIL, $4};$n", [
  2652. getTypeDesc(p.module, base), len(n), payload, data])
  2653. result = "{$1, ($2*)&$3}" % [rope(len(n)), getSeqPayloadType(p.module, t), payload]
  2654. proc genConstExpr(p: BProc, n: PNode): Rope =
  2655. case n.kind
  2656. of nkHiddenStdConv, nkHiddenSubConv:
  2657. result = genConstExpr(p, n.sons[1])
  2658. of nkCurly:
  2659. var cs: TBitSet
  2660. toBitSet(p.config, n, cs)
  2661. result = genRawSetData(cs, int(getSize(p.config, n.typ)))
  2662. of nkBracket, nkPar, nkTupleConstr, nkClosure:
  2663. var t = skipTypes(n.typ, abstractInstOwned)
  2664. if t.kind == tySequence:
  2665. if p.config.selectedGc == gcDestructors:
  2666. result = genConstSeqV2(p, n, n.typ)
  2667. else:
  2668. result = genConstSeq(p, n, n.typ)
  2669. elif t.kind == tyProc and t.callConv == ccClosure and n.len > 1 and
  2670. n.sons[1].kind == nkNilLit:
  2671. # Conversion: nimcall -> closure.
  2672. # this hack fixes issue that nkNilLit is expanded to {NIM_NIL,NIM_NIL}
  2673. # this behaviour is needed since closure_var = nil must be
  2674. # expanded to {NIM_NIL,NIM_NIL}
  2675. # in VM closures are initialized with nkPar(nkNilLit, nkNilLit)
  2676. # leading to duplicate code like this:
  2677. # "{NIM_NIL,NIM_NIL}, {NIM_NIL,NIM_NIL}"
  2678. if n[0].kind == nkNilLit:
  2679. result = ~"{NIM_NIL,NIM_NIL}"
  2680. else:
  2681. var d: TLoc
  2682. initLocExpr(p, n[0], d)
  2683. result = "{(($1) $2),NIM_NIL}" % [getClosureType(p.module, t, clHalfWithEnv), rdLoc(d)]
  2684. else:
  2685. result = genConstSimpleList(p, n)
  2686. of nkObjConstr:
  2687. result = genConstObjConstr(p, n)
  2688. of nkStrLit..nkTripleStrLit:
  2689. if p.config.selectedGc == gcDestructors:
  2690. result = genStringLiteralV2Const(p.module, n)
  2691. else:
  2692. var d: TLoc
  2693. initLocExpr(p, n, d)
  2694. result = rdLoc(d)
  2695. else:
  2696. var d: TLoc
  2697. initLocExpr(p, n, d)
  2698. result = rdLoc(d)