ccgexprs.nim 124 KB

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