ccgexprs.nim 113 KB

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