ccgexprs.nim 116 KB

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