ccgexprs.nim 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2013 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # included from cgen.nim
  10. # -------------------------- constant expressions ------------------------
  11. proc int64Literal(i: BiggestInt): Rope =
  12. if i > low(int64):
  13. result = rfmt(nil, "IL64($1)", rope(i))
  14. else:
  15. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  16. proc uint64Literal(i: uint64): Rope = rope($i & "ULL")
  17. proc intLiteral(i: BiggestInt): Rope =
  18. if i > low(int32) and i <= high(int32):
  19. result = rope(i)
  20. elif i == low(int32):
  21. # Nim has the same bug for the same reasons :-)
  22. result = ~"(-2147483647 -1)"
  23. elif i > low(int64):
  24. result = rfmt(nil, "IL64($1)", rope(i))
  25. else:
  26. result = ~"(IL64(-9223372036854775807) - IL64(1))"
  27. proc getStrLit(m: BModule, s: string): Rope =
  28. discard cgsym(m, "TGenericSeq")
  29. result = getTempName(m)
  30. addf(m.s[cfsData], "STRING_LITERAL($1, $2, $3);$n",
  31. [result, makeCString(s), rope(len(s))])
  32. proc genLiteral(p: BProc, n: PNode, ty: PType): Rope =
  33. if ty == nil: internalError(n.info, "genLiteral: ty is nil")
  34. case n.kind
  35. of nkCharLit..nkUInt64Lit:
  36. case skipTypes(ty, abstractVarRange).kind
  37. of tyChar, tyNil:
  38. result = intLiteral(n.intVal)
  39. of tyBool:
  40. if n.intVal != 0: result = ~"NIM_TRUE"
  41. else: result = ~"NIM_FALSE"
  42. of tyInt64: result = int64Literal(n.intVal)
  43. of tyUInt64: result = uint64Literal(uint64(n.intVal))
  44. else:
  45. result = "(($1) $2)" % [getTypeDesc(p.module,
  46. ty), intLiteral(n.intVal)]
  47. of nkNilLit:
  48. let t = skipTypes(ty, abstractVarRange)
  49. if t.kind == tyProc and t.callConv == ccClosure:
  50. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  51. result = p.module.tmpBase & rope(id)
  52. if id == p.module.labels:
  53. # not found in cache:
  54. inc(p.module.labels)
  55. addf(p.module.s[cfsData],
  56. "static NIM_CONST $1 $2 = {NIM_NIL,NIM_NIL};$n",
  57. [getTypeDesc(p.module, ty), result])
  58. else:
  59. result = rope("NIM_NIL")
  60. of nkStrLit..nkTripleStrLit:
  61. if n.strVal.isNil:
  62. result = ropecg(p.module, "((#NimStringDesc*) NIM_NIL)", [])
  63. elif skipTypes(ty, abstractVarRange).kind == tyString:
  64. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  65. if id == p.module.labels:
  66. # string literal not found in the cache:
  67. result = ropecg(p.module, "((#NimStringDesc*) &$1)",
  68. [getStrLit(p.module, n.strVal)])
  69. else:
  70. result = ropecg(p.module, "((#NimStringDesc*) &$1$2)",
  71. [p.module.tmpBase, rope(id)])
  72. else:
  73. result = makeCString(n.strVal)
  74. of nkFloatLit, nkFloat64Lit:
  75. result = rope(n.floatVal.toStrMaxPrecision)
  76. of nkFloat32Lit:
  77. result = rope(n.floatVal.toStrMaxPrecision("f"))
  78. else:
  79. internalError(n.info, "genLiteral(" & $n.kind & ')')
  80. result = nil
  81. proc genLiteral(p: BProc, n: PNode): Rope =
  82. result = genLiteral(p, n, n.typ)
  83. proc bitSetToWord(s: TBitSet, size: int): BiggestInt =
  84. result = 0
  85. when true:
  86. for j in countup(0, size - 1):
  87. if j < len(s): result = result or `shl`(ze64(s[j]), j * 8)
  88. else:
  89. # not needed, too complex thinking:
  90. if CPU[platform.hostCPU].endian == CPU[targetCPU].endian:
  91. for j in countup(0, size - 1):
  92. if j < len(s): result = result or `shl`(Ze64(s[j]), j * 8)
  93. else:
  94. for j in countup(0, size - 1):
  95. if j < len(s): result = result or `shl`(Ze64(s[j]), (Size - 1 - j) * 8)
  96. proc genRawSetData(cs: TBitSet, size: int): Rope =
  97. var frmt: FormatStr
  98. if size > 8:
  99. result = "{$n" % []
  100. for i in countup(0, size - 1):
  101. if i < size - 1:
  102. # not last iteration?
  103. if (i + 1) mod 8 == 0: frmt = "0x$1,$n"
  104. else: frmt = "0x$1, "
  105. else:
  106. frmt = "0x$1}$n"
  107. addf(result, frmt, [rope(toHex(ze64(cs[i]), 2))])
  108. else:
  109. result = intLiteral(bitSetToWord(cs, size))
  110. # result := rope('0x' + ToHex(bitSetToWord(cs, size), size * 2))
  111. proc genSetNode(p: BProc, n: PNode): Rope =
  112. var cs: TBitSet
  113. var size = int(getSize(n.typ))
  114. toBitSet(n, cs)
  115. if size > 8:
  116. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  117. result = p.module.tmpBase & rope(id)
  118. if id == p.module.labels:
  119. # not found in cache:
  120. inc(p.module.labels)
  121. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  122. [getTypeDesc(p.module, n.typ), result, genRawSetData(cs, size)])
  123. else:
  124. result = genRawSetData(cs, size)
  125. proc getStorageLoc(n: PNode): TStorageLoc =
  126. case n.kind
  127. of nkSym:
  128. case n.sym.kind
  129. of skParam, skTemp:
  130. result = OnStack
  131. of skVar, skForVar, skResult, skLet:
  132. if sfGlobal in n.sym.flags: result = OnHeap
  133. else: result = OnStack
  134. of skConst:
  135. if sfGlobal in n.sym.flags: result = OnHeap
  136. else: result = OnUnknown
  137. else: result = OnUnknown
  138. of nkDerefExpr, nkHiddenDeref:
  139. case n.sons[0].typ.kind
  140. of tyVar: result = OnUnknown
  141. of tyPtr: result = OnStack
  142. of tyRef: result = OnHeap
  143. else: internalError(n.info, "getStorageLoc")
  144. of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv:
  145. result = getStorageLoc(n.sons[0])
  146. else: result = OnUnknown
  147. proc genRefAssign(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  148. if dest.s == OnStack or not usesNativeGC():
  149. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  150. elif dest.s == OnHeap:
  151. # location is on heap
  152. # now the writer barrier is inlined for performance:
  153. #
  154. # if afSrcIsNotNil in flags:
  155. # UseMagic(p.module, 'nimGCref')
  156. # lineF(p, cpsStmts, 'nimGCref($1);$n', [rdLoc(src)])
  157. # elif afSrcIsNil notin flags:
  158. # UseMagic(p.module, 'nimGCref')
  159. # lineF(p, cpsStmts, 'if ($1) nimGCref($1);$n', [rdLoc(src)])
  160. # if afDestIsNotNil in flags:
  161. # UseMagic(p.module, 'nimGCunref')
  162. # lineF(p, cpsStmts, 'nimGCunref($1);$n', [rdLoc(dest)])
  163. # elif afDestIsNil notin flags:
  164. # UseMagic(p.module, 'nimGCunref')
  165. # lineF(p, cpsStmts, 'if ($1) nimGCunref($1);$n', [rdLoc(dest)])
  166. # lineF(p, cpsStmts, '$1 = $2;$n', [rdLoc(dest), rdLoc(src)])
  167. if canFormAcycle(dest.t):
  168. linefmt(p, cpsStmts, "#asgnRef((void**) $1, $2);$n",
  169. addrLoc(dest), rdLoc(src))
  170. else:
  171. linefmt(p, cpsStmts, "#asgnRefNoCycle((void**) $1, $2);$n",
  172. addrLoc(dest), rdLoc(src))
  173. else:
  174. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, $2);$n",
  175. addrLoc(dest), rdLoc(src))
  176. proc asgnComplexity(n: PNode): int =
  177. if n != nil:
  178. case n.kind
  179. of nkSym: result = 1
  180. of nkRecCase:
  181. # 'case objects' are too difficult to inline their assignment operation:
  182. result = 100
  183. of nkRecList:
  184. for t in items(n):
  185. result += asgnComplexity(t)
  186. else: discard
  187. proc optAsgnLoc(a: TLoc, t: PType, field: Rope): TLoc =
  188. assert field != nil
  189. result.k = locField
  190. result.s = a.s
  191. result.t = t
  192. result.r = rdLoc(a) & "." & field
  193. proc genOptAsgnTuple(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  194. let newflags =
  195. if src.s == OnStatic:
  196. flags + {needToCopy}
  197. elif tfShallow in dest.t.flags:
  198. flags - {needToCopy}
  199. else:
  200. flags
  201. let t = skipTypes(dest.t, abstractInst).getUniqueType()
  202. for i in 0 .. <t.len:
  203. let t = t.sons[i]
  204. let field = "Field$1" % [i.rope]
  205. genAssignment(p, optAsgnLoc(dest, t, field),
  206. optAsgnLoc(src, t, field), newflags)
  207. proc genOptAsgnObject(p: BProc, dest, src: TLoc, flags: TAssignmentFlags,
  208. t: PNode, typ: PType) =
  209. if t == nil: return
  210. let newflags =
  211. if src.s == OnStatic:
  212. flags + {needToCopy}
  213. elif tfShallow in dest.t.flags:
  214. flags - {needToCopy}
  215. else:
  216. flags
  217. case t.kind
  218. of nkSym:
  219. let field = t.sym
  220. if field.loc.r == nil: fillObjectFields(p.module, typ)
  221. genAssignment(p, optAsgnLoc(dest, field.typ, field.loc.r),
  222. optAsgnLoc(src, field.typ, field.loc.r), newflags)
  223. of nkRecList:
  224. for child in items(t): genOptAsgnObject(p, dest, src, newflags, child, typ)
  225. else: discard
  226. proc genGenericAsgn(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  227. # Consider:
  228. # type TMyFastString {.shallow.} = string
  229. # Due to the implementation of pragmas this would end up to set the
  230. # tfShallow flag for the built-in string type too! So we check only
  231. # here for this flag, where it is reasonably safe to do so
  232. # (for objects, etc.):
  233. if needToCopy notin flags or
  234. tfShallow in skipTypes(dest.t, abstractVarRange).flags:
  235. if dest.s == OnStack or not usesNativeGC():
  236. useStringh(p.module)
  237. linefmt(p, cpsStmts,
  238. "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  239. addrLoc(dest), addrLoc(src), rdLoc(dest))
  240. else:
  241. linefmt(p, cpsStmts, "#genericShallowAssign((void*)$1, (void*)$2, $3);$n",
  242. addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  243. else:
  244. linefmt(p, cpsStmts, "#genericAssign((void*)$1, (void*)$2, $3);$n",
  245. addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  246. proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) =
  247. # This function replaces all other methods for generating
  248. # the assignment operation in C.
  249. if src.t != nil and src.t.kind == tyPtr:
  250. # little HACK to support the new 'var T' as return type:
  251. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  252. return
  253. let ty = skipTypes(dest.t, abstractRange + tyUserTypeClasses)
  254. case ty.kind
  255. of tyRef:
  256. genRefAssign(p, dest, src, flags)
  257. of tySequence:
  258. if needToCopy notin flags and src.s != OnStatic:
  259. genRefAssign(p, dest, src, flags)
  260. else:
  261. linefmt(p, cpsStmts, "#genericSeqAssign($1, $2, $3);$n",
  262. addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t))
  263. of tyString:
  264. if needToCopy notin flags and src.s != OnStatic:
  265. genRefAssign(p, dest, src, flags)
  266. else:
  267. if dest.s == OnStack or not usesNativeGC():
  268. linefmt(p, cpsStmts, "$1 = #copyString($2);$n", dest.rdLoc, src.rdLoc)
  269. elif dest.s == OnHeap:
  270. # we use a temporary to care for the dreaded self assignment:
  271. var tmp: TLoc
  272. getTemp(p, ty, tmp)
  273. linefmt(p, cpsStmts, "$3 = $1; $1 = #copyStringRC1($2);$n",
  274. dest.rdLoc, src.rdLoc, tmp.rdLoc)
  275. linefmt(p, cpsStmts, "if ($1) #nimGCunrefNoCycle($1);$n", tmp.rdLoc)
  276. else:
  277. linefmt(p, cpsStmts, "#unsureAsgnRef((void**) $1, #copyString($2));$n",
  278. addrLoc(dest), rdLoc(src))
  279. of tyProc:
  280. if needsComplexAssignment(dest.t):
  281. # optimize closure assignment:
  282. let a = optAsgnLoc(dest, dest.t, "ClE_0".rope)
  283. let b = optAsgnLoc(src, dest.t, "ClE_0".rope)
  284. genRefAssign(p, a, b, flags)
  285. linefmt(p, cpsStmts, "$1.ClP_0 = $2.ClP_0;$n", rdLoc(dest), rdLoc(src))
  286. else:
  287. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  288. of tyTuple:
  289. if needsComplexAssignment(dest.t):
  290. if dest.t.len <= 4: genOptAsgnTuple(p, dest, src, flags)
  291. else: genGenericAsgn(p, dest, src, flags)
  292. else:
  293. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  294. of tyObject:
  295. # XXX: check for subtyping?
  296. if ty.isImportedCppType:
  297. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  298. elif not isObjLackingTypeField(ty):
  299. genGenericAsgn(p, dest, src, flags)
  300. elif needsComplexAssignment(ty):
  301. if ty.sons[0].isNil and asgnComplexity(ty.n) <= 4:
  302. discard getTypeDesc(p.module, ty)
  303. internalAssert ty.n != nil
  304. genOptAsgnObject(p, dest, src, flags, ty.n, ty)
  305. else:
  306. genGenericAsgn(p, dest, src, flags)
  307. else:
  308. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  309. of tyArray:
  310. if needsComplexAssignment(dest.t):
  311. genGenericAsgn(p, dest, src, flags)
  312. else:
  313. useStringh(p.module)
  314. linefmt(p, cpsStmts,
  315. "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($3));$n",
  316. rdLoc(dest), rdLoc(src), getTypeDesc(p.module, dest.t))
  317. of tyOpenArray, tyVarargs:
  318. # open arrays are always on the stack - really? What if a sequence is
  319. # passed to an open array?
  320. if needsComplexAssignment(dest.t):
  321. linefmt(p, cpsStmts, # XXX: is this correct for arrays?
  322. "#genericAssignOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  323. addrLoc(dest), addrLoc(src), genTypeInfo(p.module, dest.t))
  324. else:
  325. useStringh(p.module)
  326. linefmt(p, cpsStmts,
  327. "memcpy((void*)$1, (NIM_CONST void*)$2, sizeof($1[0])*$1Len_0);$n",
  328. rdLoc(dest), rdLoc(src))
  329. of tySet:
  330. if mapType(ty) == ctArray:
  331. useStringh(p.module)
  332. linefmt(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
  333. rdLoc(dest), rdLoc(src), rope(getSize(dest.t)))
  334. else:
  335. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  336. of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString,
  337. tyInt..tyUInt64, tyRange, tyVar:
  338. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  339. else: internalError("genAssignment: " & $ty.kind)
  340. if optMemTracker in p.options and dest.s in {OnHeap, OnUnknown}:
  341. #writeStackTrace()
  342. #echo p.currLineInfo, " requesting"
  343. linefmt(p, cpsStmts, "#memTrackerWrite((void*)$1, $2, $3, $4);$n",
  344. addrLoc(dest), rope getSize(dest.t),
  345. makeCString(p.currLineInfo.toFullPath),
  346. rope p.currLineInfo.safeLineNm)
  347. proc genDeepCopy(p: BProc; dest, src: TLoc) =
  348. template addrLocOrTemp(a: TLoc): Rope =
  349. if a.k == locExpr:
  350. var tmp: TLoc
  351. getTemp(p, a.t, tmp)
  352. genAssignment(p, tmp, a, {})
  353. addrLoc(tmp)
  354. else:
  355. addrLoc(a)
  356. var ty = skipTypes(dest.t, abstractVarRange)
  357. case ty.kind
  358. of tyPtr, tyRef, tyProc, tyTuple, tyObject, tyArray:
  359. # XXX optimize this
  360. linefmt(p, cpsStmts, "#genericDeepCopy((void*)$1, (void*)$2, $3);$n",
  361. addrLoc(dest), addrLocOrTemp(src), genTypeInfo(p.module, dest.t))
  362. of tySequence, tyString:
  363. linefmt(p, cpsStmts, "#genericSeqDeepCopy($1, $2, $3);$n",
  364. addrLoc(dest), rdLoc(src), genTypeInfo(p.module, dest.t))
  365. of tyOpenArray, tyVarargs:
  366. linefmt(p, cpsStmts,
  367. "#genericDeepCopyOpenArray((void*)$1, (void*)$2, $1Len_0, $3);$n",
  368. addrLoc(dest), addrLocOrTemp(src), genTypeInfo(p.module, dest.t))
  369. of tySet:
  370. if mapType(ty) == ctArray:
  371. useStringh(p.module)
  372. linefmt(p, cpsStmts, "memcpy((void*)$1, (NIM_CONST void*)$2, $3);$n",
  373. rdLoc(dest), rdLoc(src), rope(getSize(dest.t)))
  374. else:
  375. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  376. of tyPointer, tyChar, tyBool, tyEnum, tyCString,
  377. tyInt..tyUInt64, tyRange, tyVar:
  378. linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src))
  379. else: internalError("genDeepCopy: " & $ty.kind)
  380. proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) =
  381. if d.k != locNone:
  382. if lfNoDeepCopy in d.flags: genAssignment(p, d, s, {})
  383. else: genAssignment(p, d, s, {needToCopy})
  384. else:
  385. d = s # ``d`` is free, so fill it with ``s``
  386. proc putDataIntoDest(p: BProc, d: var TLoc, t: PType, r: Rope) =
  387. var a: TLoc
  388. if d.k != locNone:
  389. # need to generate an assignment here
  390. initLoc(a, locData, t, OnStatic)
  391. a.r = r
  392. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  393. else: genAssignment(p, d, a, {needToCopy})
  394. else:
  395. # we cannot call initLoc() here as that would overwrite
  396. # the flags field!
  397. d.k = locData
  398. d.t = t
  399. d.r = r
  400. proc putIntoDest(p: BProc, d: var TLoc, t: PType, r: Rope; s=OnUnknown) =
  401. var a: TLoc
  402. if d.k != locNone:
  403. # need to generate an assignment here
  404. initLoc(a, locExpr, t, s)
  405. a.r = r
  406. if lfNoDeepCopy in d.flags: genAssignment(p, d, a, {})
  407. else: genAssignment(p, d, a, {needToCopy})
  408. else:
  409. # we cannot call initLoc() here as that would overwrite
  410. # the flags field!
  411. d.k = locExpr
  412. d.t = t
  413. d.r = r
  414. proc binaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  415. var a, b: TLoc
  416. if d.k != locNone: internalError(e.info, "binaryStmt")
  417. initLocExpr(p, e.sons[1], a)
  418. initLocExpr(p, e.sons[2], b)
  419. lineCg(p, cpsStmts, frmt, rdLoc(a), rdLoc(b))
  420. proc unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  421. var a: TLoc
  422. if d.k != locNone: internalError(e.info, "unaryStmt")
  423. initLocExpr(p, e.sons[1], a)
  424. lineCg(p, cpsStmts, frmt, [rdLoc(a)])
  425. proc binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  426. var a, b: TLoc
  427. assert(e.sons[1].typ != nil)
  428. assert(e.sons[2].typ != nil)
  429. initLocExpr(p, e.sons[1], a)
  430. initLocExpr(p, e.sons[2], b)
  431. putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)]))
  432. proc binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  433. var a, b: TLoc
  434. assert(e.sons[1].typ != nil)
  435. assert(e.sons[2].typ != nil)
  436. initLocExpr(p, e.sons[1], a)
  437. initLocExpr(p, e.sons[2], b)
  438. putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc]))
  439. proc unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  440. var a: TLoc
  441. initLocExpr(p, e.sons[1], a)
  442. putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a)]))
  443. proc unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  444. var a: TLoc
  445. initLocExpr(p, e.sons[1], a)
  446. putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdCharLoc(a)]))
  447. proc binaryArithOverflowRaw(p: BProc, t: PType, a, b: TLoc;
  448. frmt: string): Rope =
  449. var size = getSize(t)
  450. let storage = if size < platform.intSize: rope("NI")
  451. else: getTypeDesc(p.module, t)
  452. result = getTempName(p.module)
  453. linefmt(p, cpsLocals, "$1 $2;$n", storage, result)
  454. lineCg(p, cpsStmts, frmt, result, rdCharLoc(a), rdCharLoc(b))
  455. if size < platform.intSize or t.kind in {tyRange, tyEnum}:
  456. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
  457. result, intLiteral(firstOrd(t)), intLiteral(lastOrd(t)))
  458. proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  459. const
  460. prc: array[mAddI..mPred, string] = [
  461. "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n",
  462. "$# = #mulInt($#, $#);$n", "$# = #divInt($#, $#);$n",
  463. "$# = #modInt($#, $#);$n",
  464. "$# = #addInt($#, $#);$n", "$# = #subInt($#, $#);$n"]
  465. prc64: array[mAddI..mPred, string] = [
  466. "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n",
  467. "$# = #mulInt64($#, $#);$n", "$# = #divInt64($#, $#);$n",
  468. "$# = #modInt64($#, $#);$n",
  469. "$# = #addInt64($#, $#);$n", "$# = #subInt64($#, $#);$n"]
  470. opr: array[mAddI..mPred, string] = [
  471. "($#)($# + $#)", "($#)($# - $#)", "($#)($# * $#)",
  472. "($#)($# / $#)", "($#)($# % $#)",
  473. "($#)($# + $#)", "($#)($# - $#)"]
  474. var a, b: TLoc
  475. assert(e.sons[1].typ != nil)
  476. assert(e.sons[2].typ != nil)
  477. initLocExpr(p, e.sons[1], a)
  478. initLocExpr(p, e.sons[2], b)
  479. # skipping 'range' is correct here as we'll generate a proper range check
  480. # later via 'chckRange'
  481. let t = e.typ.skipTypes(abstractRange)
  482. if optOverflowCheck notin p.options:
  483. let res = opr[m] % [getTypeDesc(p.module, e.typ), rdLoc(a), rdLoc(b)]
  484. putIntoDest(p, d, e.typ, res)
  485. else:
  486. let res = binaryArithOverflowRaw(p, t, a, b,
  487. if t.kind == tyInt64: prc64[m] else: prc[m])
  488. putIntoDest(p, d, e.typ, "($#)($#)" % [getTypeDesc(p.module, e.typ), res])
  489. proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  490. const
  491. opr: array[mUnaryMinusI..mAbsI, string] = [
  492. mUnaryMinusI: "((NI$2)-($1))",
  493. mUnaryMinusI64: "-($1)",
  494. mAbsI: "($1 > 0? ($1) : -($1))"]
  495. var
  496. a: TLoc
  497. t: PType
  498. assert(e.sons[1].typ != nil)
  499. initLocExpr(p, e.sons[1], a)
  500. t = skipTypes(e.typ, abstractRange)
  501. if optOverflowCheck in p.options:
  502. linefmt(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n",
  503. rdLoc(a), intLiteral(firstOrd(t)))
  504. putIntoDest(p, d, e.typ, opr[m] % [rdLoc(a), rope(getSize(t) * 8)])
  505. proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  506. const
  507. binArithTab: array[mAddF64..mXor, string] = [
  508. "(($4)($1) + ($4)($2))", # AddF64
  509. "(($4)($1) - ($4)($2))", # SubF64
  510. "(($4)($1) * ($4)($2))", # MulF64
  511. "(($4)($1) / ($4)($2))", # DivF64
  512. "($4)((NU$5)($1) >> (NU$3)($2))", # ShrI
  513. "($4)((NU$3)($1) << (NU$3)($2))", # ShlI
  514. "($4)($1 & $2)", # BitandI
  515. "($4)($1 | $2)", # BitorI
  516. "($4)($1 ^ $2)", # BitxorI
  517. "(($1 <= $2) ? $1 : $2)", # MinI
  518. "(($1 >= $2) ? $1 : $2)", # MaxI
  519. "(($1 <= $2) ? $1 : $2)", # MinF64
  520. "(($1 >= $2) ? $1 : $2)", # MaxF64
  521. "($4)((NU$3)($1) + (NU$3)($2))", # AddU
  522. "($4)((NU$3)($1) - (NU$3)($2))", # SubU
  523. "($4)((NU$3)($1) * (NU$3)($2))", # MulU
  524. "($4)((NU$3)($1) / (NU$3)($2))", # DivU
  525. "($4)((NU$3)($1) % (NU$3)($2))", # ModU
  526. "($1 == $2)", # EqI
  527. "($1 <= $2)", # LeI
  528. "($1 < $2)", # LtI
  529. "($1 == $2)", # EqF64
  530. "($1 <= $2)", # LeF64
  531. "($1 < $2)", # LtF64
  532. "((NU$3)($1) <= (NU$3)($2))", # LeU
  533. "((NU$3)($1) < (NU$3)($2))", # LtU
  534. "((NU64)($1) <= (NU64)($2))", # LeU64
  535. "((NU64)($1) < (NU64)($2))", # LtU64
  536. "($1 == $2)", # EqEnum
  537. "($1 <= $2)", # LeEnum
  538. "($1 < $2)", # LtEnum
  539. "((NU8)($1) == (NU8)($2))", # EqCh
  540. "((NU8)($1) <= (NU8)($2))", # LeCh
  541. "((NU8)($1) < (NU8)($2))", # LtCh
  542. "($1 == $2)", # EqB
  543. "($1 <= $2)", # LeB
  544. "($1 < $2)", # LtB
  545. "($1 == $2)", # EqRef
  546. "($1 == $2)", # EqPtr
  547. "($1 <= $2)", # LePtr
  548. "($1 < $2)", # LtPtr
  549. "($1 != $2)"] # Xor
  550. var
  551. a, b: TLoc
  552. s, k: BiggestInt
  553. assert(e.sons[1].typ != nil)
  554. assert(e.sons[2].typ != nil)
  555. initLocExpr(p, e.sons[1], a)
  556. initLocExpr(p, e.sons[2], b)
  557. # BUGFIX: cannot use result-type here, as it may be a boolean
  558. s = max(getSize(a.t), getSize(b.t)) * 8
  559. k = getSize(a.t) * 8
  560. putIntoDest(p, d, e.typ,
  561. binArithTab[op] % [rdLoc(a), rdLoc(b), rope(s),
  562. getSimpleTypeDesc(p.module, e.typ), rope(k)])
  563. proc genEqProc(p: BProc, e: PNode, d: var TLoc) =
  564. var a, b: TLoc
  565. assert(e.sons[1].typ != nil)
  566. assert(e.sons[2].typ != nil)
  567. initLocExpr(p, e.sons[1], a)
  568. initLocExpr(p, e.sons[2], b)
  569. if a.t.skipTypes(abstractInst).callConv == ccClosure:
  570. putIntoDest(p, d, e.typ,
  571. "($1.ClP_0 == $2.ClP_0 && $1.ClE_0 == $2.ClE_0)" % [rdLoc(a), rdLoc(b)])
  572. else:
  573. putIntoDest(p, d, e.typ, "($1 == $2)" % [rdLoc(a), rdLoc(b)])
  574. proc genIsNil(p: BProc, e: PNode, d: var TLoc) =
  575. let t = skipTypes(e.sons[1].typ, abstractRange)
  576. if t.kind == tyProc and t.callConv == ccClosure:
  577. unaryExpr(p, e, d, "($1.ClP_0 == 0)")
  578. else:
  579. unaryExpr(p, e, d, "($1 == 0)")
  580. proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  581. const
  582. unArithTab: array[mNot..mToBiggestInt, string] = ["!($1)", # Not
  583. "$1", # UnaryPlusI
  584. "($3)((NU$2) ~($1))", # BitnotI
  585. "$1", # UnaryPlusF64
  586. "-($1)", # UnaryMinusF64
  587. "($1 < 0? -($1) : ($1))", # AbsF64; BUGFIX: fabs() makes problems
  588. # for Tiny C, so we don't use it
  589. "(($3)(NU)(NU8)($1))", # mZe8ToI
  590. "(($3)(NU64)(NU8)($1))", # mZe8ToI64
  591. "(($3)(NU)(NU16)($1))", # mZe16ToI
  592. "(($3)(NU64)(NU16)($1))", # mZe16ToI64
  593. "(($3)(NU64)(NU32)($1))", # mZe32ToI64
  594. "(($3)(NU64)(NU)($1))", # mZeIToI64
  595. "(($3)(NU8)(NU)($1))", # ToU8
  596. "(($3)(NU16)(NU)($1))", # ToU16
  597. "(($3)(NU32)(NU64)($1))", # ToU32
  598. "((double) ($1))", # ToFloat
  599. "((double) ($1))", # ToBiggestFloat
  600. "float64ToInt32($1)", # ToInt
  601. "float64ToInt64($1)"] # ToBiggestInt
  602. var
  603. a: TLoc
  604. t: PType
  605. assert(e.sons[1].typ != nil)
  606. initLocExpr(p, e.sons[1], a)
  607. t = skipTypes(e.typ, abstractRange)
  608. putIntoDest(p, d, e.typ,
  609. unArithTab[op] % [rdLoc(a), rope(getSize(t) * 8),
  610. getSimpleTypeDesc(p.module, e.typ)])
  611. proc isCppRef(p: BProc; typ: PType): bool {.inline.} =
  612. result = p.module.compileToCpp and
  613. skipTypes(typ, abstractInst).kind == tyVar and
  614. tfVarIsPtr notin skipTypes(typ, abstractInst).flags
  615. proc genDeref(p: BProc, e: PNode, d: var TLoc; enforceDeref=false) =
  616. let mt = mapType(e.sons[0].typ)
  617. if mt in {ctArray, ctPtrToArray} and not enforceDeref:
  618. # XXX the amount of hacks for C's arrays is incredible, maybe we should
  619. # simply wrap them in a struct? --> Losing auto vectorization then?
  620. #if e[0].kind != nkBracketExpr:
  621. # message(e.info, warnUser, "CAME HERE " & renderTree(e))
  622. expr(p, e.sons[0], d)
  623. if e.sons[0].typ.skipTypes(abstractInst).kind == tyRef:
  624. d.s = OnHeap
  625. else:
  626. var a: TLoc
  627. var typ = skipTypes(e.sons[0].typ, abstractInst)
  628. if typ.kind in {tyUserTypeClass, tyUserTypeClassInst} and typ.isResolvedUserTypeClass:
  629. typ = typ.lastSon
  630. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and p.module.compileToCpp and e.sons[0].kind == nkHiddenAddr:
  631. initLocExprSingleUse(p, e[0][0], d)
  632. return
  633. else:
  634. initLocExprSingleUse(p, e.sons[0], a)
  635. if d.k == locNone:
  636. # dest = *a; <-- We do not know that 'dest' is on the heap!
  637. # It is completely wrong to set 'd.s' here, unless it's not yet
  638. # been assigned to.
  639. case typ.kind
  640. of tyRef:
  641. d.s = OnHeap
  642. of tyVar:
  643. d.s = OnUnknown
  644. if tfVarIsPtr notin typ.flags and p.module.compileToCpp and
  645. e.kind == nkHiddenDeref:
  646. putIntoDest(p, d, e.typ, rdLoc(a), a.s)
  647. return
  648. of tyPtr:
  649. d.s = OnUnknown # BUGFIX!
  650. else:
  651. internalError(e.info, "genDeref " & $typ.kind)
  652. elif p.module.compileToCpp:
  653. if typ.kind == tyVar and tfVarIsPtr notin typ.flags and
  654. e.kind == nkHiddenDeref:
  655. putIntoDest(p, d, e.typ, rdLoc(a), a.s)
  656. return
  657. if enforceDeref and mt == ctPtrToArray:
  658. # we lie about the type for better C interop: 'ptr array[3,T]' is
  659. # translated to 'ptr T', but for deref'ing this produces wrong code.
  660. # See tmissingderef. So we get rid of the deref instead. The codegen
  661. # ends up using 'memcpy' for the array assignment,
  662. # so the '&' and '*' cancel out:
  663. putIntoDest(p, d, a.t.sons[0], rdLoc(a), a.s)
  664. else:
  665. putIntoDest(p, d, e.typ, "(*$1)" % [rdLoc(a)], a.s)
  666. proc genAddr(p: BProc, e: PNode, d: var TLoc) =
  667. # careful 'addr(myptrToArray)' needs to get the ampersand:
  668. if e.sons[0].typ.skipTypes(abstractInst).kind in {tyRef, tyPtr}:
  669. var a: TLoc
  670. initLocExpr(p, e.sons[0], a)
  671. putIntoDest(p, d, e.typ, "&" & a.r, a.s)
  672. #Message(e.info, warnUser, "HERE NEW &")
  673. elif mapType(e.sons[0].typ) == ctArray or isCppRef(p, e.sons[0].typ):
  674. expr(p, e.sons[0], d)
  675. else:
  676. var a: TLoc
  677. initLocExpr(p, e.sons[0], a)
  678. putIntoDest(p, d, e.typ, addrLoc(a), a.s)
  679. template inheritLocation(d: var TLoc, a: TLoc) =
  680. if d.k == locNone: d.s = a.s
  681. proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc) =
  682. initLocExpr(p, e.sons[0], a)
  683. if e.sons[1].kind != nkSym: internalError(e.info, "genRecordFieldAux")
  684. d.inheritLocation(a)
  685. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  686. proc genTupleElem(p: BProc, e: PNode, d: var TLoc) =
  687. var
  688. a: TLoc
  689. i: int
  690. initLocExpr(p, e.sons[0], a)
  691. let tupType = a.t.skipTypes(abstractInst)
  692. assert tupType.kind == tyTuple
  693. d.inheritLocation(a)
  694. discard getTypeDesc(p.module, a.t) # fill the record's fields.loc
  695. var r = rdLoc(a)
  696. case e.sons[1].kind
  697. of nkIntLit..nkUInt64Lit: i = int(e.sons[1].intVal)
  698. else: internalError(e.info, "genTupleElem")
  699. addf(r, ".Field$1", [rope(i)])
  700. putIntoDest(p, d, tupType.sons[i], r, a.s)
  701. proc lookupFieldAgain(p: BProc, ty: PType; field: PSym; r: var Rope;
  702. resTyp: ptr PType = nil): PSym =
  703. var ty = ty
  704. assert r != nil
  705. while ty != nil:
  706. ty = ty.skipTypes(skipPtrs)
  707. assert(ty.kind in {tyTuple, tyObject})
  708. result = lookupInRecord(ty.n, field.name)
  709. if result != nil:
  710. if resTyp != nil: resTyp[] = ty
  711. break
  712. if not p.module.compileToCpp: add(r, ".Sup")
  713. ty = ty.sons[0]
  714. if result == nil: internalError(field.info, "genCheckedRecordField")
  715. proc genRecordField(p: BProc, e: PNode, d: var TLoc) =
  716. var a: TLoc
  717. genRecordFieldAux(p, e, d, a)
  718. var r = rdLoc(a)
  719. var f = e.sons[1].sym
  720. let ty = skipTypes(a.t, abstractInst + tyUserTypeClasses)
  721. if ty.kind == tyTuple:
  722. # we found a unique tuple type which lacks field information
  723. # so we use Field$i
  724. addf(r, ".Field$1", [rope(f.position)])
  725. putIntoDest(p, d, f.typ, r, a.s)
  726. else:
  727. var rtyp: PType
  728. let field = lookupFieldAgain(p, ty, f, r, addr rtyp)
  729. if field.loc.r == nil and rtyp != nil: fillObjectFields(p.module, rtyp)
  730. if field.loc.r == nil: internalError(e.info, "genRecordField 3 " & typeToString(ty))
  731. addf(r, ".$1", [field.loc.r])
  732. putIntoDest(p, d, field.typ, r, a.s)
  733. #d.s = a.s
  734. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc)
  735. proc genFieldCheck(p: BProc, e: PNode, obj: Rope, field: PSym;
  736. origTy: PType) =
  737. var test, u, v: TLoc
  738. for i in countup(1, sonsLen(e) - 1):
  739. var it = e.sons[i]
  740. assert(it.kind in nkCallKinds)
  741. assert(it.sons[0].kind == nkSym)
  742. let op = it.sons[0].sym
  743. if op.magic == mNot: it = it.sons[1]
  744. let disc = it.sons[2].skipConv
  745. assert(disc.kind == nkSym)
  746. initLoc(test, locNone, it.typ, OnStack)
  747. initLocExpr(p, it.sons[1], u)
  748. var o = obj
  749. let d = lookupFieldAgain(p, origTy, disc.sym, o)
  750. initLoc(v, locExpr, d.typ, OnUnknown)
  751. v.r = o
  752. v.r.add(".")
  753. v.r.add(d.loc.r)
  754. genInExprAux(p, it, u, v, test)
  755. let id = nodeTableTestOrSet(p.module.dataCache,
  756. newStrNode(nkStrLit, field.name.s), p.module.labels)
  757. let strLit = if id == p.module.labels: getStrLit(p.module, field.name.s)
  758. else: p.module.tmpBase & rope(id)
  759. if op.magic == mNot:
  760. linefmt(p, cpsStmts,
  761. "if ($1) #raiseFieldError(((#NimStringDesc*) &$2));$n",
  762. rdLoc(test), strLit)
  763. else:
  764. linefmt(p, cpsStmts,
  765. "if (!($1)) #raiseFieldError(((#NimStringDesc*) &$2));$n",
  766. rdLoc(test), strLit)
  767. proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) =
  768. if optFieldCheck in p.options:
  769. var a: TLoc
  770. genRecordFieldAux(p, e.sons[0], d, a)
  771. let ty = skipTypes(a.t, abstractInst)
  772. var r = rdLoc(a)
  773. let f = e.sons[0].sons[1].sym
  774. let field = lookupFieldAgain(p, ty, f, r)
  775. if field.loc.r == nil: fillObjectFields(p.module, ty)
  776. if field.loc.r == nil:
  777. internalError(e.info, "genCheckedRecordField") # generate the checks:
  778. genFieldCheck(p, e, r, field, ty)
  779. add(r, rfmt(nil, ".$1", field.loc.r))
  780. putIntoDest(p, d, field.typ, r, a.s)
  781. else:
  782. genRecordField(p, e.sons[0], d)
  783. proc genArrayElem(p: BProc, x, y: PNode, d: var TLoc) =
  784. var a, b: TLoc
  785. initLocExpr(p, x, a)
  786. initLocExpr(p, y, b)
  787. var ty = skipTypes(skipTypes(a.t, abstractVarRange), abstractPtrs)
  788. var first = intLiteral(firstOrd(ty))
  789. # emit range check:
  790. if optBoundsCheck in p.options and tfUncheckedArray notin ty.flags:
  791. if not isConstExpr(y):
  792. # semantic pass has already checked for const index expressions
  793. if firstOrd(ty) == 0:
  794. if (firstOrd(b.t) < firstOrd(ty)) or (lastOrd(b.t) > lastOrd(ty)):
  795. linefmt(p, cpsStmts, "if ((NU)($1) > (NU)($2)) #raiseIndexError();$n",
  796. rdCharLoc(b), intLiteral(lastOrd(ty)))
  797. else:
  798. linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseIndexError();$n",
  799. rdCharLoc(b), first, intLiteral(lastOrd(ty)))
  800. else:
  801. let idx = getOrdValue(y)
  802. if idx < firstOrd(ty) or idx > lastOrd(ty):
  803. localError(x.info, errIndexOutOfBounds)
  804. d.inheritLocation(a)
  805. putIntoDest(p, d, elemType(skipTypes(ty, abstractVar)),
  806. rfmt(nil, "$1[($2)- $3]", rdLoc(a), rdCharLoc(b), first), a.s)
  807. proc genCStringElem(p: BProc, x, y: PNode, d: var TLoc) =
  808. var a, b: TLoc
  809. initLocExpr(p, x, a)
  810. initLocExpr(p, y, b)
  811. var ty = skipTypes(a.t, abstractVarRange)
  812. if d.k == locNone: d.s = a.s
  813. putIntoDest(p, d, elemType(skipTypes(ty, abstractVar)),
  814. rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b)), a.s)
  815. proc genOpenArrayElem(p: BProc, x, y: PNode, d: var TLoc) =
  816. var a, b: TLoc
  817. initLocExpr(p, x, a)
  818. initLocExpr(p, y, b) # emit range check:
  819. if optBoundsCheck in p.options:
  820. linefmt(p, cpsStmts, "if ((NU)($1) >= (NU)($2Len_0)) #raiseIndexError();$n",
  821. rdLoc(b), rdLoc(a)) # BUGFIX: ``>=`` and not ``>``!
  822. if d.k == locNone: d.s = a.s
  823. putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)),
  824. rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b)), a.s)
  825. proc genSeqElem(p: BProc, x, y: PNode, d: var TLoc) =
  826. var a, b: TLoc
  827. initLocExpr(p, x, a)
  828. initLocExpr(p, y, b)
  829. var ty = skipTypes(a.t, abstractVarRange)
  830. if ty.kind in {tyRef, tyPtr}:
  831. ty = skipTypes(ty.lastSon, abstractVarRange) # emit range check:
  832. if optBoundsCheck in p.options:
  833. if ty.kind == tyString:
  834. linefmt(p, cpsStmts,
  835. "if ((NU)($1) > (NU)($2->$3)) #raiseIndexError();$n",
  836. rdLoc(b), rdLoc(a), lenField(p))
  837. else:
  838. linefmt(p, cpsStmts,
  839. "if ((NU)($1) >= (NU)($2->$3)) #raiseIndexError();$n",
  840. rdLoc(b), rdLoc(a), lenField(p))
  841. if d.k == locNone: d.s = OnHeap
  842. if skipTypes(a.t, abstractVar).kind in {tyRef, tyPtr}:
  843. a.r = rfmt(nil, "(*$1)", a.r)
  844. putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)),
  845. rfmt(nil, "$1->data[$2]", rdLoc(a), rdCharLoc(b)), a.s)
  846. proc genBracketExpr(p: BProc; n: PNode; d: var TLoc) =
  847. var ty = skipTypes(n.sons[0].typ, abstractVarRange + tyUserTypeClasses)
  848. if ty.kind in {tyRef, tyPtr}: ty = skipTypes(ty.lastSon, abstractVarRange)
  849. case ty.kind
  850. of tyArray: genArrayElem(p, n.sons[0], n.sons[1], d)
  851. of tyOpenArray, tyVarargs: genOpenArrayElem(p, n.sons[0], n.sons[1], d)
  852. of tySequence, tyString: genSeqElem(p, n.sons[0], n.sons[1], d)
  853. of tyCString: genCStringElem(p, n.sons[0], n.sons[1], d)
  854. of tyTuple: genTupleElem(p, n, d)
  855. else: internalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')')
  856. proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  857. # how to generate code?
  858. # 'expr1 and expr2' becomes:
  859. # result = expr1
  860. # fjmp result, end
  861. # result = expr2
  862. # end:
  863. # ... (result computed)
  864. # BUGFIX:
  865. # a = b or a
  866. # used to generate:
  867. # a = b
  868. # if a: goto end
  869. # a = a
  870. # end:
  871. # now it generates:
  872. # tmp = b
  873. # if tmp: goto end
  874. # tmp = a
  875. # end:
  876. # a = tmp
  877. var
  878. L: TLabel
  879. tmp: TLoc
  880. getTemp(p, e.typ, tmp) # force it into a temp!
  881. inc p.splitDecls
  882. expr(p, e.sons[1], tmp)
  883. L = getLabel(p)
  884. if m == mOr:
  885. lineF(p, cpsStmts, "if ($1) goto $2;$n", [rdLoc(tmp), L])
  886. else:
  887. lineF(p, cpsStmts, "if (!($1)) goto $2;$n", [rdLoc(tmp), L])
  888. expr(p, e.sons[2], tmp)
  889. fixLabel(p, L)
  890. if d.k == locNone:
  891. d = tmp
  892. else:
  893. genAssignment(p, d, tmp, {}) # no need for deep copying
  894. dec p.splitDecls
  895. proc genEcho(p: BProc, n: PNode) =
  896. # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)``
  897. # is threadsafe.
  898. internalAssert n.kind == nkBracket
  899. var args: Rope = nil
  900. var a: TLoc
  901. for i in countup(0, n.len-1):
  902. if n.sons[i].skipConv.kind == nkNilLit:
  903. add(args, ", \"nil\"")
  904. else:
  905. initLocExpr(p, n.sons[i], a)
  906. addf(args, ", $1? ($1)->data:\"nil\"", [rdLoc(a)])
  907. if platform.targetOS == osGenode:
  908. # bypass libc and print directly to the Genode LOG session
  909. p.module.includeHeader("<base/log.h>")
  910. linefmt(p, cpsStmts, """Genode::log(""$1);$n""", args)
  911. else:
  912. p.module.includeHeader("<stdio.h>")
  913. linefmt(p, cpsStmts, "printf($1$2);$n",
  914. makeCString(repeat("%s", n.len) & tnl), args)
  915. linefmt(p, cpsStmts, "fflush(stdout);$n")
  916. proc gcUsage(n: PNode) =
  917. if gSelectedGC == gcNone: message(n.info, warnGcMem, n.renderTree)
  918. proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
  919. # <Nim code>
  920. # s = 'Hello ' & name & ', how do you feel?' & 'z'
  921. #
  922. # <generated C code>
  923. # {
  924. # string tmp0;
  925. # ...
  926. # tmp0 = rawNewString(6 + 17 + 1 + s2->len);
  927. # // we cannot generate s = rawNewString(...) here, because
  928. # // ``s`` may be used on the right side of the expression
  929. # appendString(tmp0, strlit_1);
  930. # appendString(tmp0, name);
  931. # appendString(tmp0, strlit_2);
  932. # appendChar(tmp0, 'z');
  933. # asgn(s, tmp0);
  934. # }
  935. var a, tmp: TLoc
  936. getTemp(p, e.typ, tmp)
  937. var L = 0
  938. var appends: Rope = nil
  939. var lens: Rope = nil
  940. for i in countup(0, sonsLen(e) - 2):
  941. # compute the length expression:
  942. initLocExpr(p, e.sons[i + 1], a)
  943. if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar:
  944. inc(L)
  945. add(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a)))
  946. else:
  947. if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}:
  948. inc(L, len(e.sons[i + 1].strVal))
  949. else:
  950. addf(lens, "$1->$2 + ", [rdLoc(a), lenField(p)])
  951. add(appends, rfmt(p.module, "#appendString($1, $2);$n", tmp.r, rdLoc(a)))
  952. linefmt(p, cpsStmts, "$1 = #rawNewString($2$3);$n", tmp.r, lens, rope(L))
  953. add(p.s(cpsStmts), appends)
  954. if d.k == locNone:
  955. d = tmp
  956. else:
  957. genAssignment(p, d, tmp, {}) # no need for deep copying
  958. gcUsage(e)
  959. proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
  960. # <Nim code>
  961. # s &= 'Hello ' & name & ', how do you feel?' & 'z'
  962. # // BUG: what if s is on the left side too?
  963. # <generated C code>
  964. # {
  965. # s = resizeString(s, 6 + 17 + 1 + name->len);
  966. # appendString(s, strlit_1);
  967. # appendString(s, name);
  968. # appendString(s, strlit_2);
  969. # appendChar(s, 'z');
  970. # }
  971. var
  972. a, dest: TLoc
  973. appends, lens: Rope
  974. assert(d.k == locNone)
  975. var L = 0
  976. initLocExpr(p, e.sons[1], dest)
  977. for i in countup(0, sonsLen(e) - 3):
  978. # compute the length expression:
  979. initLocExpr(p, e.sons[i + 2], a)
  980. if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar:
  981. inc(L)
  982. add(appends, rfmt(p.module, "#appendChar($1, $2);$n",
  983. rdLoc(dest), rdLoc(a)))
  984. else:
  985. if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}:
  986. inc(L, len(e.sons[i + 2].strVal))
  987. else:
  988. addf(lens, "$1->$2 + ", [rdLoc(a), lenField(p)])
  989. add(appends, rfmt(p.module, "#appendString($1, $2);$n",
  990. rdLoc(dest), rdLoc(a)))
  991. linefmt(p, cpsStmts, "$1 = #resizeString($1, $2$3);$n",
  992. rdLoc(dest), lens, rope(L))
  993. add(p.s(cpsStmts), appends)
  994. gcUsage(e)
  995. proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
  996. # seq &= x -->
  997. # seq = (typeof seq) incrSeq(&seq->Sup, sizeof(x));
  998. # seq->data[seq->len-1] = x;
  999. let seqAppendPattern = if not p.module.compileToCpp:
  1000. "$1 = ($2) #incrSeqV2(&($1)->Sup, sizeof($3));$n"
  1001. else:
  1002. "$1 = ($2) #incrSeqV2($1, sizeof($3));$n"
  1003. var a, b, dest, tmpL: TLoc
  1004. initLocExpr(p, e.sons[1], a)
  1005. initLocExpr(p, e.sons[2], b)
  1006. let bt = skipTypes(e.sons[2].typ, {tyVar})
  1007. lineCg(p, cpsStmts, seqAppendPattern, [
  1008. rdLoc(a),
  1009. getTypeDesc(p.module, e.sons[1].typ),
  1010. getTypeDesc(p.module, bt)])
  1011. #if bt != b.t:
  1012. # echo "YES ", e.info, " new: ", typeToString(bt), " old: ", typeToString(b.t)
  1013. initLoc(dest, locExpr, bt, OnHeap)
  1014. getIntTemp(p, tmpL)
  1015. lineCg(p, cpsStmts, "$1 = $2->$3++;$n", tmpL.r, rdLoc(a), lenField(p))
  1016. dest.r = rfmt(nil, "$1->data[$2]", rdLoc(a), tmpL.r)
  1017. genAssignment(p, dest, b, {needToCopy, afDestIsNil})
  1018. gcUsage(e)
  1019. proc genReset(p: BProc, n: PNode) =
  1020. var a: TLoc
  1021. initLocExpr(p, n.sons[1], a)
  1022. linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n",
  1023. addrLoc(a), genTypeInfo(p.module, skipTypes(a.t, {tyVar})))
  1024. proc rawGenNew(p: BProc, a: TLoc, sizeExpr: Rope) =
  1025. var sizeExpr = sizeExpr
  1026. let typ = a.t
  1027. var b: TLoc
  1028. initLoc(b, locExpr, a.t, OnHeap)
  1029. let refType = typ.skipTypes(abstractInst)
  1030. assert refType.kind == tyRef
  1031. let bt = refType.lastSon
  1032. if sizeExpr.isNil:
  1033. sizeExpr = "sizeof($1)" %
  1034. [getTypeDesc(p.module, bt)]
  1035. let args = [getTypeDesc(p.module, typ),
  1036. genTypeInfo(p.module, typ),
  1037. sizeExpr]
  1038. if a.s == OnHeap and usesNativeGC():
  1039. # use newObjRC1 as an optimization
  1040. if canFormAcycle(a.t):
  1041. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", a.rdLoc)
  1042. else:
  1043. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", a.rdLoc)
  1044. b.r = ropecg(p.module, "($1) #newObjRC1($2, $3)", args)
  1045. linefmt(p, cpsStmts, "$1 = $2;$n", a.rdLoc, b.rdLoc)
  1046. else:
  1047. b.r = ropecg(p.module, "($1) #newObj($2, $3)", args)
  1048. genAssignment(p, a, b, {}) # set the object type:
  1049. genObjectInit(p, cpsStmts, bt, a, false)
  1050. proc genNew(p: BProc, e: PNode) =
  1051. var a: TLoc
  1052. initLocExpr(p, e.sons[1], a)
  1053. # 'genNew' also handles 'unsafeNew':
  1054. if e.len == 3:
  1055. var se: TLoc
  1056. initLocExpr(p, e.sons[2], se)
  1057. rawGenNew(p, a, se.rdLoc)
  1058. else:
  1059. rawGenNew(p, a, nil)
  1060. gcUsage(e)
  1061. proc genNewSeqAux(p: BProc, dest: TLoc, length: Rope) =
  1062. let seqtype = skipTypes(dest.t, abstractVarRange)
  1063. let args = [getTypeDesc(p.module, seqtype),
  1064. genTypeInfo(p.module, seqtype), length]
  1065. var call: TLoc
  1066. initLoc(call, locExpr, dest.t, OnHeap)
  1067. if dest.s == OnHeap and usesNativeGC():
  1068. if canFormAcycle(dest.t):
  1069. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefRC1($1); $1 = NIM_NIL; }$n", dest.rdLoc)
  1070. else:
  1071. linefmt(p, cpsStmts, "if ($1) { #nimGCunrefNoCycle($1); $1 = NIM_NIL; }$n", dest.rdLoc)
  1072. call.r = ropecg(p.module, "($1) #newSeqRC1($2, $3)", args)
  1073. linefmt(p, cpsStmts, "$1 = $2;$n", dest.rdLoc, call.rdLoc)
  1074. else:
  1075. call.r = ropecg(p.module, "($1) #newSeq($2, $3)", args)
  1076. genAssignment(p, dest, call, {})
  1077. proc genNewSeq(p: BProc, e: PNode) =
  1078. var a, b: TLoc
  1079. initLocExpr(p, e.sons[1], a)
  1080. initLocExpr(p, e.sons[2], b)
  1081. genNewSeqAux(p, a, b.rdLoc)
  1082. gcUsage(e)
  1083. proc genNewSeqOfCap(p: BProc; e: PNode; d: var TLoc) =
  1084. let seqtype = skipTypes(e.typ, abstractVarRange)
  1085. var a: TLoc
  1086. initLocExpr(p, e.sons[1], a)
  1087. putIntoDest(p, d, e.typ, ropecg(p.module,
  1088. "($1)#nimNewSeqOfCap($2, $3)", [
  1089. getTypeDesc(p.module, seqtype),
  1090. genTypeInfo(p.module, seqtype), a.rdLoc]))
  1091. gcUsage(e)
  1092. proc genConstExpr(p: BProc, n: PNode): Rope
  1093. proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool =
  1094. if d.k == locNone and n.len > ord(n.kind == nkObjConstr) and n.isDeepConstExpr:
  1095. let t = n.typ
  1096. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1097. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1098. fillLoc(d, locData, t, p.module.tmpBase & rope(id), OnStatic)
  1099. if id == p.module.labels:
  1100. # expression not found in the cache:
  1101. inc(p.module.labels)
  1102. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  1103. [getTypeDesc(p.module, t), d.r, genConstExpr(p, n)])
  1104. result = true
  1105. else:
  1106. result = false
  1107. proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
  1108. #echo rendertree e, " ", e.isDeepConstExpr
  1109. # inheritance in C++ does not allow struct initialization so
  1110. # we skip this step here:
  1111. if not p.module.compileToCpp:
  1112. if handleConstExpr(p, e, d): return
  1113. var tmp: TLoc
  1114. var t = e.typ.skipTypes(abstractInst)
  1115. getTemp(p, t, tmp)
  1116. let isRef = t.kind == tyRef
  1117. var r = rdLoc(tmp)
  1118. if isRef:
  1119. rawGenNew(p, tmp, nil)
  1120. t = t.lastSon.skipTypes(abstractInst)
  1121. r = "(*$1)" % [r]
  1122. gcUsage(e)
  1123. else:
  1124. constructLoc(p, tmp)
  1125. discard getTypeDesc(p.module, t)
  1126. let ty = getUniqueType(t)
  1127. for i in 1 .. <e.len:
  1128. let it = e.sons[i]
  1129. var tmp2: TLoc
  1130. tmp2.r = r
  1131. let field = lookupFieldAgain(p, ty, it.sons[0].sym, tmp2.r)
  1132. if field.loc.r == nil: fillObjectFields(p.module, ty)
  1133. if field.loc.r == nil: internalError(e.info, "genObjConstr")
  1134. if it.len == 3 and optFieldCheck in p.options:
  1135. genFieldCheck(p, it.sons[2], r, field, ty)
  1136. add(tmp2.r, ".")
  1137. add(tmp2.r, field.loc.r)
  1138. tmp2.k = locTemp
  1139. tmp2.t = field.loc.t
  1140. tmp2.s = if isRef: OnHeap else: OnStack
  1141. expr(p, it.sons[1], tmp2)
  1142. if d.k == locNone:
  1143. d = tmp
  1144. else:
  1145. genAssignment(p, d, tmp, {})
  1146. proc genSeqConstr(p: BProc, t: PNode, d: var TLoc) =
  1147. var arr: TLoc
  1148. if d.k == locNone:
  1149. getTemp(p, t.typ, d)
  1150. # generate call to newSeq before adding the elements per hand:
  1151. genNewSeqAux(p, d, intLiteral(sonsLen(t)))
  1152. for i in countup(0, sonsLen(t) - 1):
  1153. initLoc(arr, locExpr, elemType(skipTypes(t.typ, typedescInst)), OnHeap)
  1154. arr.r = rfmt(nil, "$1->data[$2]", rdLoc(d), intLiteral(i))
  1155. arr.s = OnHeap # we know that sequences are on the heap
  1156. expr(p, t.sons[i], arr)
  1157. gcUsage(t)
  1158. proc genArrToSeq(p: BProc, t: PNode, d: var TLoc) =
  1159. var elem, a, arr: TLoc
  1160. if t.sons[1].kind == nkBracket:
  1161. t.sons[1].typ = t.typ
  1162. genSeqConstr(p, t.sons[1], d)
  1163. return
  1164. if d.k == locNone:
  1165. getTemp(p, t.typ, d)
  1166. # generate call to newSeq before adding the elements per hand:
  1167. var L = int(lengthOrd(t.sons[1].typ))
  1168. genNewSeqAux(p, d, intLiteral(L))
  1169. initLocExpr(p, t.sons[1], a)
  1170. for i in countup(0, L - 1):
  1171. initLoc(elem, locExpr, elemType(skipTypes(t.typ, abstractInst)), OnHeap)
  1172. elem.r = rfmt(nil, "$1->data[$2]", rdLoc(d), intLiteral(i))
  1173. elem.s = OnHeap # we know that sequences are on the heap
  1174. initLoc(arr, locExpr, elemType(skipTypes(t.sons[1].typ, abstractInst)), a.s)
  1175. arr.r = rfmt(nil, "$1[$2]", rdLoc(a), intLiteral(i))
  1176. genAssignment(p, elem, arr, {afDestIsNil, needToCopy})
  1177. proc genNewFinalize(p: BProc, e: PNode) =
  1178. var
  1179. a, b, f: TLoc
  1180. refType, bt: PType
  1181. ti: Rope
  1182. refType = skipTypes(e.sons[1].typ, abstractVarRange)
  1183. initLocExpr(p, e.sons[1], a)
  1184. initLocExpr(p, e.sons[2], f)
  1185. initLoc(b, locExpr, a.t, OnHeap)
  1186. ti = genTypeInfo(p.module, refType)
  1187. addf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)])
  1188. b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [
  1189. getTypeDesc(p.module, refType),
  1190. ti, getTypeDesc(p.module, skipTypes(refType.lastSon, abstractRange))])
  1191. genAssignment(p, a, b, {}) # set the object type:
  1192. bt = skipTypes(refType.lastSon, abstractRange)
  1193. genObjectInit(p, cpsStmts, bt, a, false)
  1194. gcUsage(e)
  1195. proc genOfHelper(p: BProc; dest: PType; a: Rope): Rope =
  1196. # unfortunately 'genTypeInfo' sets tfObjHasKids as a side effect, so we
  1197. # have to call it here first:
  1198. let ti = genTypeInfo(p.module, dest)
  1199. if tfFinal in dest.flags or (objHasKidsValid in p.module.flags and
  1200. tfObjHasKids notin dest.flags):
  1201. result = "$1.m_type == $2" % [a, ti]
  1202. else:
  1203. discard cgsym(p.module, "TNimType")
  1204. inc p.module.labels
  1205. let cache = "Nim_OfCheck_CACHE" & p.module.labels.rope
  1206. addf(p.module.s[cfsVars], "static TNimType* $#[2];$n", [cache])
  1207. result = rfmt(p.module, "#isObjWithCache($#.m_type, $#, $#)", a, ti, cache)
  1208. when false:
  1209. # former version:
  1210. result = rfmt(p.module, "#isObj($1.m_type, $2)",
  1211. a, genTypeInfo(p.module, dest))
  1212. proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) =
  1213. var a: TLoc
  1214. initLocExpr(p, x, a)
  1215. var dest = skipTypes(typ, typedescPtrs)
  1216. var r = rdLoc(a)
  1217. var nilCheck: Rope = nil
  1218. var t = skipTypes(a.t, abstractInst)
  1219. while t.kind in {tyVar, tyPtr, tyRef}:
  1220. if t.kind != tyVar: nilCheck = r
  1221. if t.kind != tyVar or not p.module.compileToCpp:
  1222. r = rfmt(nil, "(*$1)", r)
  1223. t = skipTypes(t.lastSon, typedescInst)
  1224. if not p.module.compileToCpp:
  1225. while t.kind == tyObject and t.sons[0] != nil:
  1226. add(r, ~".Sup")
  1227. t = skipTypes(t.sons[0], skipPtrs)
  1228. if isObjLackingTypeField(t):
  1229. globalError(x.info, errGenerated,
  1230. "no 'of' operator available for pure objects")
  1231. if nilCheck != nil:
  1232. r = rfmt(p.module, "(($1) && ($2))", nilCheck, genOfHelper(p, dest, r))
  1233. else:
  1234. r = rfmt(p.module, "($1)", genOfHelper(p, dest, r))
  1235. putIntoDest(p, d, getSysType(tyBool), r, a.s)
  1236. proc genOf(p: BProc, n: PNode, d: var TLoc) =
  1237. genOf(p, n.sons[1], n.sons[2].typ, d)
  1238. proc genRepr(p: BProc, e: PNode, d: var TLoc) =
  1239. var a: TLoc
  1240. initLocExpr(p, e.sons[1], a)
  1241. var t = skipTypes(e.sons[1].typ, abstractVarRange)
  1242. case t.kind
  1243. of tyInt..tyInt64, tyUInt..tyUInt64:
  1244. putIntoDest(p, d, e.typ,
  1245. ropecg(p.module, "#reprInt((NI64)$1)", [rdLoc(a)]), a.s)
  1246. of tyFloat..tyFloat128:
  1247. putIntoDest(p, d, e.typ, ropecg(p.module, "#reprFloat($1)", [rdLoc(a)]), a.s)
  1248. of tyBool:
  1249. putIntoDest(p, d, e.typ, ropecg(p.module, "#reprBool($1)", [rdLoc(a)]), a.s)
  1250. of tyChar:
  1251. putIntoDest(p, d, e.typ, ropecg(p.module, "#reprChar($1)", [rdLoc(a)]), a.s)
  1252. of tyEnum, tyOrdinal:
  1253. putIntoDest(p, d, e.typ,
  1254. ropecg(p.module, "#reprEnum((NI)$1, $2)", [
  1255. rdLoc(a), genTypeInfo(p.module, t)]), a.s)
  1256. of tyString:
  1257. putIntoDest(p, d, e.typ, ropecg(p.module, "#reprStr($1)", [rdLoc(a)]), a.s)
  1258. of tySet:
  1259. putIntoDest(p, d, e.typ, ropecg(p.module, "#reprSet($1, $2)", [
  1260. addrLoc(a), genTypeInfo(p.module, t)]), a.s)
  1261. of tyOpenArray, tyVarargs:
  1262. var b: TLoc
  1263. case a.t.kind
  1264. of tyOpenArray, tyVarargs:
  1265. putIntoDest(p, b, e.typ, "$1, $1Len_0" % [rdLoc(a)], a.s)
  1266. of tyString, tySequence:
  1267. putIntoDest(p, b, e.typ,
  1268. "$1->data, $1->$2" % [rdLoc(a), lenField(p)], a.s)
  1269. of tyArray:
  1270. putIntoDest(p, b, e.typ,
  1271. "$1, $2" % [rdLoc(a), rope(lengthOrd(a.t))], a.s)
  1272. else: internalError(e.sons[0].info, "genRepr()")
  1273. putIntoDest(p, d, e.typ,
  1274. ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b),
  1275. genTypeInfo(p.module, elemType(t))]), a.s)
  1276. of tyCString, tyArray, tyRef, tyPtr, tyPointer, tyNil, tySequence:
  1277. putIntoDest(p, d, e.typ,
  1278. ropecg(p.module, "#reprAny($1, $2)", [
  1279. rdLoc(a), genTypeInfo(p.module, t)]), a.s)
  1280. of tyEmpty, tyVoid:
  1281. localError(e.info, "'repr' doesn't support 'void' type")
  1282. else:
  1283. putIntoDest(p, d, e.typ, ropecg(p.module, "#reprAny($1, $2)",
  1284. [addrLoc(a), genTypeInfo(p.module, t)]), a.s)
  1285. gcUsage(e)
  1286. proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) =
  1287. let t = e.sons[1].typ
  1288. putIntoDest(p, d, e.typ, genTypeInfo(p.module, t))
  1289. proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
  1290. var a: TLoc
  1291. initLocExpr(p, n.sons[1], a)
  1292. a.r = ropecg(p.module, frmt, [rdLoc(a)])
  1293. if d.k == locNone: getTemp(p, n.typ, d)
  1294. genAssignment(p, d, a, {})
  1295. gcUsage(n)
  1296. proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1297. var a = e.sons[1]
  1298. if a.kind == nkHiddenAddr: a = a.sons[0]
  1299. var typ = skipTypes(a.typ, abstractVar + tyUserTypeClasses)
  1300. case typ.kind
  1301. of tyOpenArray, tyVarargs:
  1302. if op == mHigh: unaryExpr(p, e, d, "($1Len_0-1)")
  1303. else: unaryExpr(p, e, d, "$1Len_0")
  1304. of tyCString:
  1305. useStringh(p.module)
  1306. if op == mHigh: unaryExpr(p, e, d, "($1 ? (strlen($1)-1) : -1)")
  1307. else: unaryExpr(p, e, d, "($1 ? strlen($1) : 0)")
  1308. of tyString:
  1309. if not p.module.compileToCpp:
  1310. if op == mHigh: unaryExpr(p, e, d, "($1 ? ($1->Sup.len-1) : -1)")
  1311. else: unaryExpr(p, e, d, "($1 ? $1->Sup.len : 0)")
  1312. else:
  1313. if op == mHigh: unaryExpr(p, e, d, "($1 ? ($1->len-1) : -1)")
  1314. else: unaryExpr(p, e, d, "($1 ? $1->len : 0)")
  1315. of tySequence:
  1316. var a, tmp: TLoc
  1317. initLocExpr(p, e[1], a)
  1318. getIntTemp(p, tmp)
  1319. var frmt: FormatStr
  1320. if not p.module.compileToCpp:
  1321. if op == mHigh:
  1322. frmt = "$1 = ($2 ? ($2->Sup.len-1) : -1);$n"
  1323. else:
  1324. frmt = "$1 = ($2 ? $2->Sup.len : 0);$n"
  1325. else:
  1326. if op == mHigh:
  1327. frmt = "$1 = ($2 ? ($2->len-1) : -1);$n"
  1328. else:
  1329. frmt = "$1 = ($2 ? $2->len : 0);$n"
  1330. lineCg(p, cpsStmts, frmt, tmp.r, rdLoc(a))
  1331. putIntoDest(p, d, e.typ, tmp.r)
  1332. of tyArray:
  1333. # YYY: length(sideeffect) is optimized away incorrectly?
  1334. if op == mHigh: putIntoDest(p, d, e.typ, rope(lastOrd(typ)))
  1335. else: putIntoDest(p, d, e.typ, rope(lengthOrd(typ)))
  1336. else: internalError(e.info, "genArrayLen()")
  1337. proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) =
  1338. var a, b: TLoc
  1339. assert(d.k == locNone)
  1340. var x = e.sons[1]
  1341. if x.kind in {nkAddr, nkHiddenAddr}: x = x[0]
  1342. initLocExpr(p, x, a)
  1343. initLocExpr(p, e.sons[2], b)
  1344. let t = skipTypes(e.sons[1].typ, {tyVar})
  1345. let setLenPattern = if not p.module.compileToCpp:
  1346. "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n"
  1347. else:
  1348. "$1 = ($3) #setLengthSeq($1, sizeof($4), $2);$n"
  1349. lineCg(p, cpsStmts, setLenPattern, [
  1350. rdLoc(a), rdLoc(b), getTypeDesc(p.module, t),
  1351. getTypeDesc(p.module, t.skipTypes(abstractInst).sons[0])])
  1352. gcUsage(e)
  1353. proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) =
  1354. binaryStmt(p, e, d, "$1 = #setLengthStr($1, $2);$n")
  1355. gcUsage(e)
  1356. proc genSwap(p: BProc, e: PNode, d: var TLoc) =
  1357. # swap(a, b) -->
  1358. # temp = a
  1359. # a = b
  1360. # b = temp
  1361. var a, b, tmp: TLoc
  1362. getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp)
  1363. initLocExpr(p, e.sons[1], a) # eval a
  1364. initLocExpr(p, e.sons[2], b) # eval b
  1365. genAssignment(p, tmp, a, {})
  1366. genAssignment(p, a, b, {})
  1367. genAssignment(p, b, tmp, {})
  1368. proc rdSetElemLoc(a: TLoc, setType: PType): Rope =
  1369. # read a location of an set element; it may need a subtraction operation
  1370. # before the set operation
  1371. result = rdCharLoc(a)
  1372. assert(setType.kind == tySet)
  1373. if firstOrd(setType) != 0:
  1374. result = "($1- $2)" % [result, rope(firstOrd(setType))]
  1375. proc fewCmps(s: PNode): bool =
  1376. # this function estimates whether it is better to emit code
  1377. # for constructing the set or generating a bunch of comparisons directly
  1378. if s.kind != nkCurly: internalError(s.info, "fewCmps")
  1379. if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags):
  1380. result = false # it is better to emit the set generation code
  1381. elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
  1382. result = true # better not emit the set if int is basetype!
  1383. else:
  1384. result = sonsLen(s) <= 8 # 8 seems to be a good value
  1385. proc binaryExprIn(p: BProc, e: PNode, a, b, d: var TLoc, frmt: string) =
  1386. putIntoDest(p, d, e.typ, frmt % [rdLoc(a), rdSetElemLoc(b, a.t)])
  1387. proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) =
  1388. case int(getSize(skipTypes(e.sons[1].typ, abstractVar)))
  1389. of 1: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&7U)))!=0)")
  1390. of 2: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&15U)))!=0)")
  1391. of 4: binaryExprIn(p, e, a, b, d, "(($1 &(1U<<((NU)($2)&31U)))!=0)")
  1392. of 8: binaryExprIn(p, e, a, b, d, "(($1 &((NU64)1<<((NU)($2)&63U)))!=0)")
  1393. else: binaryExprIn(p, e, a, b, d, "(($1[(NU)($2)>>3] &(1U<<((NU)($2)&7U)))!=0)")
  1394. proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
  1395. var a, b: TLoc
  1396. assert(d.k == locNone)
  1397. initLocExpr(p, e.sons[1], a)
  1398. initLocExpr(p, e.sons[2], b)
  1399. lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(b, a.t)])
  1400. proc genInOp(p: BProc, e: PNode, d: var TLoc) =
  1401. var a, b, x, y: TLoc
  1402. if (e.sons[1].kind == nkCurly) and fewCmps(e.sons[1]):
  1403. # a set constructor but not a constant set:
  1404. # do not emit the set, but generate a bunch of comparisons; and if we do
  1405. # so, we skip the unnecessary range check: This is a semantical extension
  1406. # that code now relies on. :-/ XXX
  1407. let ea = if e.sons[2].kind in {nkChckRange, nkChckRange64}:
  1408. e.sons[2].sons[0]
  1409. else:
  1410. e.sons[2]
  1411. initLocExpr(p, ea, a)
  1412. initLoc(b, locExpr, e.typ, OnUnknown)
  1413. b.r = rope("(")
  1414. var length = sonsLen(e.sons[1])
  1415. for i in countup(0, length - 1):
  1416. if e.sons[1].sons[i].kind == nkRange:
  1417. initLocExpr(p, e.sons[1].sons[i].sons[0], x)
  1418. initLocExpr(p, e.sons[1].sons[i].sons[1], y)
  1419. addf(b.r, "$1 >= $2 && $1 <= $3",
  1420. [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)])
  1421. else:
  1422. initLocExpr(p, e.sons[1].sons[i], x)
  1423. addf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)])
  1424. if i < length - 1: add(b.r, " || ")
  1425. add(b.r, ")")
  1426. putIntoDest(p, d, e.typ, b.r)
  1427. else:
  1428. assert(e.sons[1].typ != nil)
  1429. assert(e.sons[2].typ != nil)
  1430. initLocExpr(p, e.sons[1], a)
  1431. initLocExpr(p, e.sons[2], b)
  1432. genInExprAux(p, e, a, b, d)
  1433. proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1434. const
  1435. lookupOpr: array[mLeSet..mSymDiffSet, string] = [
  1436. "for ($1 = 0; $1 < $2; $1++) { $n" &
  1437. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" &
  1438. " if (!$3) break;}$n", "for ($1 = 0; $1 < $2; $1++) { $n" &
  1439. " $3 = (($4[$1] & ~ $5[$1]) == 0);$n" & " if (!$3) break;}$n" &
  1440. "if ($3) $3 = (memcmp($4, $5, $2) != 0);$n",
  1441. "&", "|", "& ~", "^"]
  1442. var a, b, i: TLoc
  1443. var setType = skipTypes(e.sons[1].typ, abstractVar)
  1444. var size = int(getSize(setType))
  1445. case size
  1446. of 1, 2, 4, 8:
  1447. case op
  1448. of mIncl:
  1449. var ts = "NU" & $(size * 8)
  1450. binaryStmtInExcl(p, e, d,
  1451. "$1 |= ((" & ts & ")1)<<(($2)%(sizeof(" & ts & ")*8));$n")
  1452. of mExcl:
  1453. var ts = "NU" & $(size * 8)
  1454. binaryStmtInExcl(p, e, d, "$1 &= ~(((" & ts & ")1) << (($2) % (sizeof(" &
  1455. ts & ")*8)));$n")
  1456. of mCard:
  1457. if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)")
  1458. else: unaryExprChar(p, e, d, "#countBits64($1)")
  1459. of mLtSet: binaryExprChar(p, e, d, "(($1 & ~ $2 ==0)&&($1 != $2))")
  1460. of mLeSet: binaryExprChar(p, e, d, "(($1 & ~ $2)==0)")
  1461. of mEqSet: binaryExpr(p, e, d, "($1 == $2)")
  1462. of mMulSet: binaryExpr(p, e, d, "($1 & $2)")
  1463. of mPlusSet: binaryExpr(p, e, d, "($1 | $2)")
  1464. of mMinusSet: binaryExpr(p, e, d, "($1 & ~ $2)")
  1465. of mSymDiffSet: binaryExpr(p, e, d, "($1 ^ $2)")
  1466. of mInSet:
  1467. genInOp(p, e, d)
  1468. else: internalError(e.info, "genSetOp()")
  1469. else:
  1470. case op
  1471. of mIncl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] |=(1U<<($2&7U));$n")
  1472. of mExcl: binaryStmtInExcl(p, e, d, "$1[(NU)($2)>>3] &= ~(1U<<($2&7U));$n")
  1473. of mCard: unaryExprChar(p, e, d, "#cardSet($1, " & $size & ')')
  1474. of mLtSet, mLeSet:
  1475. getTemp(p, getSysType(tyInt), i) # our counter
  1476. initLocExpr(p, e.sons[1], a)
  1477. initLocExpr(p, e.sons[2], b)
  1478. if d.k == locNone: getTemp(p, getSysType(tyBool), d)
  1479. lineF(p, cpsStmts, lookupOpr[op],
  1480. [rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b)])
  1481. of mEqSet:
  1482. useStringh(p.module)
  1483. binaryExprChar(p, e, d, "(memcmp($1, $2, " & $(size) & ")==0)")
  1484. of mMulSet, mPlusSet, mMinusSet, mSymDiffSet:
  1485. # we inline the simple for loop for better code generation:
  1486. getTemp(p, getSysType(tyInt), i) # our counter
  1487. initLocExpr(p, e.sons[1], a)
  1488. initLocExpr(p, e.sons[2], b)
  1489. if d.k == locNone: getTemp(p, a.t, d)
  1490. lineF(p, cpsStmts,
  1491. "for ($1 = 0; $1 < $2; $1++) $n" &
  1492. " $3[$1] = $4[$1] $6 $5[$1];$n", [
  1493. rdLoc(i), rope(size), rdLoc(d), rdLoc(a), rdLoc(b),
  1494. rope(lookupOpr[op])])
  1495. of mInSet: genInOp(p, e, d)
  1496. else: internalError(e.info, "genSetOp")
  1497. proc genOrd(p: BProc, e: PNode, d: var TLoc) =
  1498. unaryExprChar(p, e, d, "$1")
  1499. proc genSomeCast(p: BProc, e: PNode, d: var TLoc) =
  1500. const
  1501. ValueTypes = {tyTuple, tyObject, tyArray, tyOpenArray, tyVarargs}
  1502. # we use whatever C gives us. Except if we have a value-type, we need to go
  1503. # through its address:
  1504. var a: TLoc
  1505. initLocExpr(p, e.sons[1], a)
  1506. let etyp = skipTypes(e.typ, abstractRange)
  1507. if etyp.kind in ValueTypes and lfIndirect notin a.flags:
  1508. putIntoDest(p, d, e.typ, "(*($1*) ($2))" %
  1509. [getTypeDesc(p.module, e.typ), addrLoc(a)], a.s)
  1510. elif etyp.kind == tyProc and etyp.callConv == ccClosure:
  1511. putIntoDest(p, d, e.typ, "(($1) ($2))" %
  1512. [getClosureType(p.module, etyp, clHalfWithEnv), rdCharLoc(a)], a.s)
  1513. else:
  1514. putIntoDest(p, d, e.typ, "(($1) ($2))" %
  1515. [getTypeDesc(p.module, e.typ), rdCharLoc(a)], a.s)
  1516. proc genCast(p: BProc, e: PNode, d: var TLoc) =
  1517. const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  1518. let
  1519. destt = skipTypes(e.typ, abstractRange)
  1520. srct = skipTypes(e.sons[1].typ, abstractRange)
  1521. if destt.kind in ValueTypes or srct.kind in ValueTypes:
  1522. # 'cast' and some float type involved? --> use a union.
  1523. inc(p.labels)
  1524. var lbl = p.labels.rope
  1525. var tmp: TLoc
  1526. tmp.r = "LOC$1.source" % [lbl]
  1527. linefmt(p, cpsLocals, "union { $1 source; $2 dest; } LOC$3;$n",
  1528. getTypeDesc(p.module, e.sons[1].typ), getTypeDesc(p.module, e.typ), lbl)
  1529. tmp.k = locExpr
  1530. tmp.t = srct
  1531. tmp.s = OnStack
  1532. tmp.flags = {}
  1533. expr(p, e.sons[1], tmp)
  1534. putIntoDest(p, d, e.typ, "LOC$#.dest" % [lbl], tmp.s)
  1535. else:
  1536. # I prefer the shorter cast version for pointer types -> generate less
  1537. # C code; plus it's the right thing to do for closures:
  1538. genSomeCast(p, e, d)
  1539. proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) =
  1540. var a: TLoc
  1541. var dest = skipTypes(n.typ, abstractVar)
  1542. # range checks for unsigned turned out to be buggy and annoying:
  1543. if optRangeCheck notin p.options or dest.skipTypes({tyRange}).kind in
  1544. {tyUInt..tyUInt64}:
  1545. initLocExpr(p, n.sons[0], a)
  1546. putIntoDest(p, d, n.typ, "(($1) ($2))" %
  1547. [getTypeDesc(p.module, dest), rdCharLoc(a)], a.s)
  1548. else:
  1549. initLocExpr(p, n.sons[0], a)
  1550. putIntoDest(p, d, dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [
  1551. getTypeDesc(p.module, dest), rdCharLoc(a),
  1552. genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest),
  1553. rope(magic)]), a.s)
  1554. proc genConv(p: BProc, e: PNode, d: var TLoc) =
  1555. let destType = e.typ.skipTypes({tyVar, tyGenericInst, tyAlias})
  1556. if compareTypes(destType, e.sons[1].typ, dcEqIgnoreDistinct):
  1557. expr(p, e.sons[1], d)
  1558. else:
  1559. genSomeCast(p, e, d)
  1560. proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  1561. var a: TLoc
  1562. initLocExpr(p, n.sons[0], a)
  1563. putIntoDest(p, d, skipTypes(n.typ, abstractVar), "$1->data" % [rdLoc(a)], a.s)
  1564. proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  1565. var a: TLoc
  1566. initLocExpr(p, n.sons[0], a)
  1567. putIntoDest(p, d, skipTypes(n.typ, abstractVar),
  1568. ropecg(p.module, "#cstrToNimstr($1)", [rdLoc(a)]), a.s)
  1569. gcUsage(n)
  1570. proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  1571. var x: TLoc
  1572. var a = e.sons[1]
  1573. var b = e.sons[2]
  1574. if (a.kind == nkNilLit) or (b.kind == nkNilLit):
  1575. binaryExpr(p, e, d, "($1 == $2)")
  1576. elif (a.kind in {nkStrLit..nkTripleStrLit}) and (a.strVal == ""):
  1577. initLocExpr(p, e.sons[2], x)
  1578. putIntoDest(p, d, e.typ,
  1579. rfmt(nil, "(($1) && ($1)->$2 == 0)", rdLoc(x), lenField(p)))
  1580. elif (b.kind in {nkStrLit..nkTripleStrLit}) and (b.strVal == ""):
  1581. initLocExpr(p, e.sons[1], x)
  1582. putIntoDest(p, d, e.typ,
  1583. rfmt(nil, "(($1) && ($1)->$2 == 0)", rdLoc(x), lenField(p)))
  1584. else:
  1585. binaryExpr(p, e, d, "#eqStrings($1, $2)")
  1586. proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  1587. if {optNaNCheck, optInfCheck} * p.options != {}:
  1588. const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
  1589. var a, b: TLoc
  1590. assert(e.sons[1].typ != nil)
  1591. assert(e.sons[2].typ != nil)
  1592. initLocExpr(p, e.sons[1], a)
  1593. initLocExpr(p, e.sons[2], b)
  1594. putIntoDest(p, d, e.typ, rfmt(nil, "(($4)($2) $1 ($4)($3))",
  1595. rope(opr[m]), rdLoc(a), rdLoc(b),
  1596. getSimpleTypeDesc(p.module, e[1].typ)))
  1597. if optNaNCheck in p.options:
  1598. linefmt(p, cpsStmts, "#nanCheck($1);$n", rdLoc(d))
  1599. if optInfCheck in p.options:
  1600. linefmt(p, cpsStmts, "#infCheck($1);$n", rdLoc(d))
  1601. else:
  1602. binaryArith(p, e, d, m)
  1603. proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  1604. case op
  1605. of mOr, mAnd: genAndOr(p, e, d, op)
  1606. of mNot..mToBiggestInt: unaryArith(p, e, d, op)
  1607. of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  1608. of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  1609. of mShrI..mXor: binaryArith(p, e, d, op)
  1610. of mEqProc: genEqProc(p, e, d)
  1611. of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  1612. of mRepr: genRepr(p, e, d)
  1613. of mGetTypeInfo: genGetTypeInfo(p, e, d)
  1614. of mSwap: genSwap(p, e, d)
  1615. of mUnaryLt:
  1616. if optOverflowCheck notin p.options: unaryExpr(p, e, d, "($1 - 1)")
  1617. else: unaryExpr(p, e, d, "#subInt($1, 1)")
  1618. of mInc, mDec:
  1619. const opr: array[mInc..mDec, string] = ["$1 += $2;$n", "$1 -= $2;$n"]
  1620. const fun64: array[mInc..mDec, string] = ["$# = #addInt64($#, $#);$n",
  1621. "$# = #subInt64($#, $#);$n"]
  1622. const fun: array[mInc..mDec, string] = ["$# = #addInt($#, $#);$n",
  1623. "$# = #subInt($#, $#);$n"]
  1624. let underlying = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tyVar, tyRange})
  1625. if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
  1626. binaryStmt(p, e, d, opr[op])
  1627. else:
  1628. var a, b: TLoc
  1629. assert(e.sons[1].typ != nil)
  1630. assert(e.sons[2].typ != nil)
  1631. initLocExpr(p, e.sons[1], a)
  1632. initLocExpr(p, e.sons[2], b)
  1633. let ranged = skipTypes(e.sons[1].typ, {tyGenericInst, tyAlias, tyVar})
  1634. let res = binaryArithOverflowRaw(p, ranged, a, b,
  1635. if underlying.kind == tyInt64: fun64[op] else: fun[op])
  1636. putIntoDest(p, a, ranged, "($#)($#)" % [
  1637. getTypeDesc(p.module, ranged), res])
  1638. of mConStrStr: genStrConcat(p, e, d)
  1639. of mAppendStrCh: binaryStmt(p, e, d, "$1 = #addChar($1, $2);$n")
  1640. of mAppendStrStr: genStrAppend(p, e, d)
  1641. of mAppendSeqElem: genSeqElemAppend(p, e, d)
  1642. of mEqStr: genStrEquals(p, e, d)
  1643. of mLeStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) <= 0)")
  1644. of mLtStr: binaryExpr(p, e, d, "(#cmpStrings($1, $2) < 0)")
  1645. of mIsNil: genIsNil(p, e, d)
  1646. of mIntToStr: genDollar(p, e, d, "#nimIntToStr($1)")
  1647. of mInt64ToStr: genDollar(p, e, d, "#nimInt64ToStr($1)")
  1648. of mBoolToStr: genDollar(p, e, d, "#nimBoolToStr($1)")
  1649. of mCharToStr: genDollar(p, e, d, "#nimCharToStr($1)")
  1650. of mFloatToStr: genDollar(p, e, d, "#nimFloatToStr($1)")
  1651. of mCStrToStr: genDollar(p, e, d, "#cstrToNimstr($1)")
  1652. of mStrToStr: expr(p, e.sons[1], d)
  1653. of mEnumToStr: genRepr(p, e, d)
  1654. of mOf: genOf(p, e, d)
  1655. of mNew: genNew(p, e)
  1656. of mNewFinalize: genNewFinalize(p, e)
  1657. of mNewSeq: genNewSeq(p, e)
  1658. of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  1659. of mSizeOf:
  1660. let t = e.sons[1].typ.skipTypes({tyTypeDesc})
  1661. putIntoDest(p, d, e.typ, "((NI)sizeof($1))" % [getTypeDesc(p.module, t)])
  1662. of mChr: genSomeCast(p, e, d)
  1663. of mOrd: genOrd(p, e, d)
  1664. of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
  1665. genArrayLen(p, e, d, op)
  1666. of mXLenStr:
  1667. if not p.module.compileToCpp:
  1668. unaryExpr(p, e, d, "($1->Sup.len)")
  1669. else:
  1670. unaryExpr(p, e, d, "$1->len")
  1671. of mXLenSeq:
  1672. # see 'taddhigh.nim' for why we need to use a temporary here:
  1673. var a, tmp: TLoc
  1674. initLocExpr(p, e[1], a)
  1675. getIntTemp(p, tmp)
  1676. var frmt: FormatStr
  1677. if not p.module.compileToCpp:
  1678. frmt = "$1 = $2->Sup.len;$n"
  1679. else:
  1680. frmt = "$1 = $2->len;$n"
  1681. lineCg(p, cpsStmts, frmt, tmp.r, rdLoc(a))
  1682. putIntoDest(p, d, e.typ, tmp.r)
  1683. of mGCref: unaryStmt(p, e, d, "#nimGCref($1);$n")
  1684. of mGCunref: unaryStmt(p, e, d, "#nimGCunref($1);$n")
  1685. of mSetLengthStr: genSetLengthStr(p, e, d)
  1686. of mSetLengthSeq: genSetLengthSeq(p, e, d)
  1687. of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
  1688. mInSet:
  1689. genSetOp(p, e, d, op)
  1690. of mNewString, mNewStringOfCap, mCopyStr, mCopyStrLast, mExit,
  1691. mParseBiggestFloat:
  1692. var opr = e.sons[0].sym
  1693. if lfNoDecl notin opr.loc.flags:
  1694. discard cgsym(p.module, $opr.loc.r)
  1695. genCall(p, e, d)
  1696. of mReset: genReset(p, e)
  1697. of mEcho: genEcho(p, e[1].skipConv)
  1698. of mArrToSeq: genArrToSeq(p, e, d)
  1699. of mNLen..mNError, mSlurp..mQuoteAst:
  1700. localError(e.info, errXMustBeCompileTime, e.sons[0].sym.name.s)
  1701. of mSpawn:
  1702. let n = lowerings.wrapProcForSpawn(p.module.module, e, e.typ, nil, nil)
  1703. expr(p, n, d)
  1704. of mParallel:
  1705. let n = semparallel.liftParallel(p.module.module, e)
  1706. expr(p, n, d)
  1707. of mDeepCopy:
  1708. var a, b: TLoc
  1709. let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1]
  1710. initLocExpr(p, x, a)
  1711. initLocExpr(p, e.sons[2], b)
  1712. genDeepCopy(p, a, b)
  1713. of mDotDot, mEqCString: genCall(p, e, d)
  1714. else: internalError(e.info, "genMagicExpr: " & $op)
  1715. proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  1716. # example: { a..b, c, d, e, f..g }
  1717. # we have to emit an expression of the form:
  1718. # memset(tmp, 0, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  1719. # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  1720. var
  1721. a, b, idx: TLoc
  1722. if nfAllConst in e.flags:
  1723. putIntoDest(p, d, e.typ, genSetNode(p, e))
  1724. else:
  1725. if d.k == locNone: getTemp(p, e.typ, d)
  1726. if getSize(e.typ) > 8:
  1727. # big set:
  1728. useStringh(p.module)
  1729. lineF(p, cpsStmts, "memset($1, 0, sizeof($1));$n", [rdLoc(d)])
  1730. for i in countup(0, sonsLen(e) - 1):
  1731. if e.sons[i].kind == nkRange:
  1732. getTemp(p, getSysType(tyInt), idx) # our counter
  1733. initLocExpr(p, e.sons[i].sons[0], a)
  1734. initLocExpr(p, e.sons[i].sons[1], b)
  1735. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  1736. "$2[(NU)($1)>>3] |=(1U<<((NU)($1)&7U));$n", [rdLoc(idx), rdLoc(d),
  1737. rdSetElemLoc(a, e.typ), rdSetElemLoc(b, e.typ)])
  1738. else:
  1739. initLocExpr(p, e.sons[i], a)
  1740. lineF(p, cpsStmts, "$1[(NU)($2)>>3] |=(1U<<((NU)($2)&7U));$n",
  1741. [rdLoc(d), rdSetElemLoc(a, e.typ)])
  1742. else:
  1743. # small set
  1744. var ts = "NU" & $(getSize(e.typ) * 8)
  1745. lineF(p, cpsStmts, "$1 = 0;$n", [rdLoc(d)])
  1746. for i in countup(0, sonsLen(e) - 1):
  1747. if e.sons[i].kind == nkRange:
  1748. getTemp(p, getSysType(tyInt), idx) # our counter
  1749. initLocExpr(p, e.sons[i].sons[0], a)
  1750. initLocExpr(p, e.sons[i].sons[1], b)
  1751. lineF(p, cpsStmts, "for ($1 = $3; $1 <= $4; $1++) $n" &
  1752. "$2 |=((" & ts & ")(1)<<(($1)%(sizeof(" & ts & ")*8)));$n", [
  1753. rdLoc(idx), rdLoc(d), rdSetElemLoc(a, e.typ),
  1754. rdSetElemLoc(b, e.typ)])
  1755. else:
  1756. initLocExpr(p, e.sons[i], a)
  1757. lineF(p, cpsStmts,
  1758. "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n",
  1759. [rdLoc(d), rdSetElemLoc(a, e.typ)])
  1760. proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  1761. var rec: TLoc
  1762. if not handleConstExpr(p, n, d):
  1763. let t = n.typ
  1764. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1765. if d.k == locNone: getTemp(p, t, d)
  1766. for i in countup(0, sonsLen(n) - 1):
  1767. var it = n.sons[i]
  1768. if it.kind == nkExprColonExpr: it = it.sons[1]
  1769. initLoc(rec, locExpr, it.typ, d.s)
  1770. rec.r = "$1.Field$2" % [rdLoc(d), rope(i)]
  1771. expr(p, it, rec)
  1772. proc isConstClosure(n: PNode): bool {.inline.} =
  1773. result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and
  1774. n.sons[1].kind == nkNilLit
  1775. proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  1776. assert n.kind == nkClosure
  1777. if isConstClosure(n):
  1778. inc(p.module.labels)
  1779. var tmp = "CNSTCLOSURE" & rope(p.module.labels)
  1780. addf(p.module.s[cfsData], "static NIM_CONST $1 $2 = $3;$n",
  1781. [getTypeDesc(p.module, n.typ), tmp, genConstExpr(p, n)])
  1782. putIntoDest(p, d, n.typ, tmp, OnStatic)
  1783. else:
  1784. var tmp, a, b: TLoc
  1785. initLocExpr(p, n.sons[0], a)
  1786. initLocExpr(p, n.sons[1], b)
  1787. if n.sons[0].skipConv.kind == nkClosure:
  1788. internalError(n.info, "closure to closure created")
  1789. # tasyncawait.nim breaks with this optimization:
  1790. when false:
  1791. if d.k != locNone:
  1792. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  1793. d.rdLoc, a.rdLoc, b.rdLoc)
  1794. else:
  1795. getTemp(p, n.typ, tmp)
  1796. linefmt(p, cpsStmts, "$1.ClP_0 = $2; $1.ClE_0 = $3;$n",
  1797. tmp.rdLoc, a.rdLoc, b.rdLoc)
  1798. putLocIntoDest(p, d, tmp)
  1799. proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  1800. var arr: TLoc
  1801. if not handleConstExpr(p, n, d):
  1802. if d.k == locNone: getTemp(p, n.typ, d)
  1803. for i in countup(0, sonsLen(n) - 1):
  1804. initLoc(arr, locExpr, elemType(skipTypes(n.typ, abstractInst)), d.s)
  1805. arr.r = "$1[$2]" % [rdLoc(d), intLiteral(i)]
  1806. expr(p, n.sons[i], arr)
  1807. proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  1808. requestConstImpl(p, sym)
  1809. assert((sym.loc.r != nil) and (sym.loc.t != nil))
  1810. putLocIntoDest(p, d, sym.loc)
  1811. proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  1812. var length = sonsLen(n)
  1813. for i in countup(0, length - 2): genStmts(p, n.sons[i])
  1814. if length > 0: expr(p, n.sons[length - 1], d)
  1815. proc upConv(p: BProc, n: PNode, d: var TLoc) =
  1816. var a: TLoc
  1817. initLocExpr(p, n.sons[0], a)
  1818. let dest = skipTypes(n.typ, abstractPtrs)
  1819. if optObjCheck in p.options and not isObjLackingTypeField(dest):
  1820. var r = rdLoc(a)
  1821. var nilCheck: Rope = nil
  1822. var t = skipTypes(a.t, abstractInst)
  1823. while t.kind in {tyVar, tyPtr, tyRef}:
  1824. if t.kind != tyVar: nilCheck = r
  1825. if t.kind != tyVar or not p.module.compileToCpp:
  1826. r = "(*$1)" % [r]
  1827. t = skipTypes(t.lastSon, abstractInst)
  1828. if not p.module.compileToCpp:
  1829. while t.kind == tyObject and t.sons[0] != nil:
  1830. add(r, ".Sup")
  1831. t = skipTypes(t.sons[0], skipPtrs)
  1832. if nilCheck != nil:
  1833. linefmt(p, cpsStmts, "if ($1) #chckObj($2.m_type, $3);$n",
  1834. nilCheck, r, genTypeInfo(p.module, dest))
  1835. else:
  1836. linefmt(p, cpsStmts, "#chckObj($1.m_type, $2);$n",
  1837. r, genTypeInfo(p.module, dest))
  1838. if n.sons[0].typ.kind != tyObject:
  1839. putIntoDest(p, d, n.typ,
  1840. "(($1) ($2))" % [getTypeDesc(p.module, n.typ), rdLoc(a)], a.s)
  1841. else:
  1842. putIntoDest(p, d, n.typ, "(*($1*) ($2))" %
  1843. [getTypeDesc(p.module, dest), addrLoc(a)], a.s)
  1844. proc downConv(p: BProc, n: PNode, d: var TLoc) =
  1845. if p.module.compileToCpp:
  1846. expr(p, n.sons[0], d) # downcast does C++ for us
  1847. else:
  1848. var dest = skipTypes(n.typ, abstractPtrs)
  1849. var arg = n.sons[0]
  1850. while arg.kind == nkObjDownConv: arg = arg.sons[0]
  1851. var src = skipTypes(arg.typ, abstractPtrs)
  1852. var a: TLoc
  1853. initLocExpr(p, arg, a)
  1854. var r = rdLoc(a)
  1855. let isRef = skipTypes(arg.typ, abstractInst).kind in {tyRef, tyPtr, tyVar}
  1856. if isRef:
  1857. add(r, "->Sup")
  1858. else:
  1859. add(r, ".Sup")
  1860. for i in countup(2, abs(inheritanceDiff(dest, src))): add(r, ".Sup")
  1861. if isRef:
  1862. # it can happen that we end up generating '&&x->Sup' here, so we pack
  1863. # the '&x->Sup' into a temporary and then those address is taken
  1864. # (see bug #837). However sometimes using a temporary is not correct:
  1865. # init(TFigure(my)) # where it is passed to a 'var TFigure'. We test
  1866. # this by ensuring the destination is also a pointer:
  1867. if d.k == locNone and skipTypes(n.typ, abstractInst).kind in {tyRef, tyPtr, tyVar}:
  1868. getTemp(p, n.typ, d)
  1869. linefmt(p, cpsStmts, "$1 = &$2;$n", rdLoc(d), r)
  1870. else:
  1871. r = "&" & r
  1872. putIntoDest(p, d, n.typ, r, a.s)
  1873. else:
  1874. putIntoDest(p, d, n.typ, r, a.s)
  1875. proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) =
  1876. let t = n.typ
  1877. discard getTypeDesc(p.module, t) # so that any fields are initialized
  1878. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  1879. let tmp = p.module.tmpBase & rope(id)
  1880. if id == p.module.labels:
  1881. # expression not found in the cache:
  1882. inc(p.module.labels)
  1883. addf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n",
  1884. [getTypeDesc(p.module, t), tmp, genConstExpr(p, n)])
  1885. if d.k == locNone:
  1886. fillLoc(d, locData, t, tmp, OnStatic)
  1887. else:
  1888. putDataIntoDest(p, d, t, tmp)
  1889. # This fixes bug #4551, but we really need better dataflow
  1890. # analysis to make this 100% safe.
  1891. if t.kind notin {tySequence, tyString}:
  1892. d.s = OnStatic
  1893. proc expr(p: BProc, n: PNode, d: var TLoc) =
  1894. p.currLineInfo = n.info
  1895. case n.kind
  1896. of nkSym:
  1897. var sym = n.sym
  1898. case sym.kind
  1899. of skMethod:
  1900. if {sfDispatcher, sfForward} * sym.flags != {}:
  1901. # we cannot produce code for the dispatcher yet:
  1902. fillProcLoc(p.module, sym)
  1903. genProcPrototype(p.module, sym)
  1904. else:
  1905. genProc(p.module, sym)
  1906. putLocIntoDest(p, d, sym.loc)
  1907. of skProc, skConverter, skIterator:
  1908. #if sym.kind == skIterator:
  1909. # echo renderTree(sym.getBody, {renderIds})
  1910. if sfCompileTime in sym.flags:
  1911. localError(n.info, "request to generate code for .compileTime proc: " &
  1912. sym.name.s)
  1913. genProc(p.module, sym)
  1914. if sym.loc.r == nil or sym.loc.t == nil:
  1915. internalError(n.info, "expr: proc not init " & sym.name.s)
  1916. putLocIntoDest(p, d, sym.loc)
  1917. of skConst:
  1918. if isSimpleConst(sym.typ):
  1919. putIntoDest(p, d, n.typ, genLiteral(p, sym.ast, sym.typ), OnStatic)
  1920. else:
  1921. genComplexConst(p, sym, d)
  1922. of skEnumField:
  1923. putIntoDest(p, d, n.typ, rope(sym.position))
  1924. of skVar, skForVar, skResult, skLet:
  1925. if {sfGlobal, sfThread} * sym.flags != {}:
  1926. genVarPrototype(p.module, sym)
  1927. if sym.loc.r == nil or sym.loc.t == nil:
  1928. #echo "FAILED FOR PRCO ", p.prc.name.s
  1929. #echo renderTree(p.prc.ast, {renderIds})
  1930. internalError n.info, "expr: var not init " & sym.name.s & "_" & $sym.id
  1931. if sfThread in sym.flags:
  1932. accessThreadLocalVar(p, sym)
  1933. if emulatedThreadVars():
  1934. putIntoDest(p, d, sym.loc.t, "NimTV_->" & sym.loc.r)
  1935. else:
  1936. putLocIntoDest(p, d, sym.loc)
  1937. else:
  1938. putLocIntoDest(p, d, sym.loc)
  1939. of skTemp:
  1940. if sym.loc.r == nil or sym.loc.t == nil:
  1941. #echo "FAILED FOR PRCO ", p.prc.name.s
  1942. #echo renderTree(p.prc.ast, {renderIds})
  1943. internalError(n.info, "expr: temp not init " & sym.name.s & "_" & $sym.id)
  1944. putLocIntoDest(p, d, sym.loc)
  1945. of skParam:
  1946. if sym.loc.r == nil or sym.loc.t == nil:
  1947. # echo "FAILED FOR PRCO ", p.prc.name.s
  1948. # debug p.prc.typ.n
  1949. # echo renderTree(p.prc.ast, {renderIds})
  1950. internalError(n.info, "expr: param not init " & sym.name.s & "_" & $sym.id)
  1951. putLocIntoDest(p, d, sym.loc)
  1952. else: internalError(n.info, "expr(" & $sym.kind & "); unknown symbol")
  1953. of nkNilLit:
  1954. if not isEmptyType(n.typ):
  1955. putIntoDest(p, d, n.typ, genLiteral(p, n))
  1956. of nkStrLit..nkTripleStrLit:
  1957. putDataIntoDest(p, d, n.typ, genLiteral(p, n))
  1958. of nkIntLit..nkUInt64Lit,
  1959. nkFloatLit..nkFloat128Lit, nkCharLit:
  1960. putIntoDest(p, d, n.typ, genLiteral(p, n))
  1961. of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkPostfix, nkCommand,
  1962. nkCallStrLit:
  1963. genLineDir(p, n)
  1964. let op = n.sons[0]
  1965. if n.typ.isNil:
  1966. # discard the value:
  1967. var a: TLoc
  1968. if op.kind == nkSym and op.sym.magic != mNone:
  1969. genMagicExpr(p, n, a, op.sym.magic)
  1970. else:
  1971. genCall(p, n, a)
  1972. else:
  1973. # load it into 'd':
  1974. if op.kind == nkSym and op.sym.magic != mNone:
  1975. genMagicExpr(p, n, d, op.sym.magic)
  1976. else:
  1977. genCall(p, n, d)
  1978. of nkCurly:
  1979. if isDeepConstExpr(n) and n.len != 0:
  1980. putIntoDest(p, d, n.typ, genSetNode(p, n))
  1981. else:
  1982. genSetConstr(p, n, d)
  1983. of nkBracket:
  1984. if isDeepConstExpr(n) and n.len != 0:
  1985. exprComplexConst(p, n, d)
  1986. elif skipTypes(n.typ, abstractVarRange).kind == tySequence:
  1987. genSeqConstr(p, n, d)
  1988. else:
  1989. genArrayConstr(p, n, d)
  1990. of nkPar:
  1991. if isDeepConstExpr(n) and n.len != 0:
  1992. exprComplexConst(p, n, d)
  1993. else:
  1994. genTupleConstr(p, n, d)
  1995. of nkObjConstr: genObjConstr(p, n, d)
  1996. of nkCast: genCast(p, n, d)
  1997. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, d)
  1998. of nkHiddenAddr, nkAddr: genAddr(p, n, d)
  1999. of nkBracketExpr: genBracketExpr(p, n, d)
  2000. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, d)
  2001. of nkDotExpr: genRecordField(p, n, d)
  2002. of nkCheckedFieldExpr: genCheckedRecordField(p, n, d)
  2003. of nkBlockExpr, nkBlockStmt: genBlock(p, n, d)
  2004. of nkStmtListExpr: genStmtListExpr(p, n, d)
  2005. of nkStmtList:
  2006. for i in countup(0, sonsLen(n) - 1): genStmts(p, n.sons[i])
  2007. of nkIfExpr, nkIfStmt: genIf(p, n, d)
  2008. of nkWhen:
  2009. # This should be a "when nimvm" node.
  2010. expr(p, n.sons[1].sons[0], d)
  2011. of nkObjDownConv: downConv(p, n, d)
  2012. of nkObjUpConv: upConv(p, n, d)
  2013. of nkChckRangeF: genRangeChck(p, n, d, "chckRangeF")
  2014. of nkChckRange64: genRangeChck(p, n, d, "chckRange64")
  2015. of nkChckRange: genRangeChck(p, n, d, "chckRange")
  2016. of nkStringToCString: convStrToCStr(p, n, d)
  2017. of nkCStringToString: convCStrToStr(p, n, d)
  2018. of nkLambdaKinds:
  2019. var sym = n.sons[namePos].sym
  2020. genProc(p.module, sym)
  2021. if sym.loc.r == nil or sym.loc.t == nil:
  2022. internalError(n.info, "expr: proc not init " & sym.name.s)
  2023. putLocIntoDest(p, d, sym.loc)
  2024. of nkClosure: genClosure(p, n, d)
  2025. of nkEmpty: discard
  2026. of nkWhileStmt: genWhileStmt(p, n)
  2027. of nkVarSection, nkLetSection: genVarStmt(p, n)
  2028. of nkConstSection: genConstStmt(p, n)
  2029. of nkForStmt: internalError(n.info, "for statement not eliminated")
  2030. of nkCaseStmt: genCase(p, n, d)
  2031. of nkReturnStmt: genReturnStmt(p, n)
  2032. of nkBreakStmt: genBreakStmt(p, n)
  2033. of nkAsgn:
  2034. if nfPreventCg notin n.flags:
  2035. genAsgn(p, n, fastAsgn=false)
  2036. of nkFastAsgn:
  2037. if nfPreventCg notin n.flags:
  2038. # transf is overly aggressive with 'nkFastAsgn', so we work around here.
  2039. # See tests/run/tcnstseq3 for an example that would fail otherwise.
  2040. genAsgn(p, n, fastAsgn=p.prc != nil)
  2041. of nkDiscardStmt:
  2042. let ex = n[0]
  2043. if ex.kind != nkEmpty:
  2044. genLineDir(p, n)
  2045. var a: TLoc
  2046. if ex.kind in nkCallKinds and (ex[0].kind != nkSym or
  2047. ex[0].sym.magic == mNone):
  2048. # bug #6037: do not assign to a temp in C++ mode:
  2049. incl a.flags, lfSingleUse
  2050. genCall(p, ex, a)
  2051. if lfSingleUse notin a.flags:
  2052. line(p, cpsStmts, a.r & ";" & tnl)
  2053. else:
  2054. initLocExpr(p, ex, a)
  2055. of nkAsmStmt: genAsmStmt(p, n)
  2056. of nkTryStmt:
  2057. if p.module.compileToCpp and optNoCppExceptions notin gGlobalOptions:
  2058. genTryCpp(p, n, d)
  2059. else:
  2060. genTry(p, n, d)
  2061. of nkRaiseStmt: genRaiseStmt(p, n)
  2062. of nkTypeSection:
  2063. # we have to emit the type information for object types here to support
  2064. # separate compilation:
  2065. genTypeSection(p.module, n)
  2066. of nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  2067. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  2068. nkFromStmt, nkTemplateDef, nkMacroDef:
  2069. discard
  2070. of nkPragma: genPragma(p, n)
  2071. of nkPragmaBlock: expr(p, n.lastSon, d)
  2072. of nkProcDef, nkMethodDef, nkConverterDef:
  2073. if n.sons[genericParamsPos].kind == nkEmpty:
  2074. var prc = n.sons[namePos].sym
  2075. # due to a bug/limitation in the lambda lifting, unused inner procs
  2076. # are not transformed correctly. We work around this issue (#411) here
  2077. # by ensuring it's no inner proc (owner is a module):
  2078. if prc.skipGenericOwner.kind == skModule and sfCompileTime notin prc.flags:
  2079. if (not emitLazily(prc)) or
  2080. ({sfExportc, sfCompilerProc} * prc.flags == {sfExportc}) or
  2081. (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or
  2082. (prc.kind == skMethod):
  2083. # we have not only the header:
  2084. if prc.getBody.kind != nkEmpty or lfDynamicLib in prc.loc.flags:
  2085. genProc(p.module, prc)
  2086. of nkParForStmt: genParForStmt(p, n)
  2087. of nkState: genState(p, n)
  2088. of nkGotoState: genGotoState(p, n)
  2089. of nkBreakState: genBreakState(p, n)
  2090. else: internalError(n.info, "expr(" & $n.kind & "); unknown node kind")
  2091. proc genNamedConstExpr(p: BProc, n: PNode): Rope =
  2092. if n.kind == nkExprColonExpr: result = genConstExpr(p, n.sons[1])
  2093. else: result = genConstExpr(p, n)
  2094. proc getDefaultValue(p: BProc; typ: PType; info: TLineInfo): Rope =
  2095. var t = skipTypes(typ, abstractRange-{tyTypeDesc})
  2096. case t.kind
  2097. of tyBool: result = rope"NIM_FALSE"
  2098. of tyEnum, tyChar, tyInt..tyInt64, tyUInt..tyUInt64: result = rope"0"
  2099. of tyFloat..tyFloat128: result = rope"0.0"
  2100. of tyCString, tyString, tyVar, tyPointer, tyPtr, tySequence, tyExpr,
  2101. tyStmt, tyTypeDesc, tyStatic, tyRef, tyNil:
  2102. result = rope"NIM_NIL"
  2103. of tyProc:
  2104. if t.callConv != ccClosure:
  2105. result = rope"NIM_NIL"
  2106. else:
  2107. result = rope"{NIM_NIL, NIM_NIL}"
  2108. of tyObject:
  2109. if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2110. result = "{{$1}}" % [genTypeInfo(p.module, t)]
  2111. else:
  2112. result = rope"{}"
  2113. of tyArray, tyTuple: result = rope"{}"
  2114. of tySet:
  2115. if mapType(t) == ctArray: result = rope"{}"
  2116. else: result = rope"0"
  2117. else:
  2118. globalError(info, "cannot create null element for: " & $t.kind)
  2119. proc getNullValueAux(p: BProc; t: PType; obj, cons: PNode, result: var Rope; count: var int) =
  2120. case obj.kind
  2121. of nkRecList:
  2122. for i in countup(0, sonsLen(obj) - 1):
  2123. getNullValueAux(p, t, obj.sons[i], cons, result, count)
  2124. of nkRecCase:
  2125. getNullValueAux(p, t, obj.sons[0], cons, result, count)
  2126. for i in countup(1, sonsLen(obj) - 1):
  2127. getNullValueAux(p, t, lastSon(obj.sons[i]), cons, result, count)
  2128. of nkSym:
  2129. if count > 0: result.add ", "
  2130. inc count
  2131. let field = obj.sym
  2132. for i in 1..<cons.len:
  2133. if cons[i].kind == nkExprColonExpr:
  2134. if cons[i][0].sym.name.id == field.name.id:
  2135. result.add genConstExpr(p, cons[i][1])
  2136. return
  2137. elif i == field.position:
  2138. result.add genConstExpr(p, cons[i])
  2139. return
  2140. # not found, produce default value:
  2141. result.add getDefaultValue(p, field.typ, cons.info)
  2142. else:
  2143. localError(cons.info, "cannot create null element for: " & $obj)
  2144. proc getNullValueAuxT(p: BProc; orig, t: PType; obj, cons: PNode, result: var Rope; count: var int) =
  2145. var base = t.sons[0]
  2146. let oldRes = result
  2147. if not p.module.compileToCpp: result.add "{"
  2148. let oldcount = count
  2149. if base != nil:
  2150. base = skipTypes(base, skipPtrs)
  2151. getNullValueAuxT(p, orig, base, base.n, cons, result, count)
  2152. elif not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2153. addf(result, "$1", [genTypeInfo(p.module, orig)])
  2154. inc count
  2155. getNullValueAux(p, t, obj, cons, result, count)
  2156. # do not emit '{}' as that is not valid C:
  2157. if oldcount == count: result = oldres
  2158. elif not p.module.compileToCpp: result.add "}"
  2159. proc genConstObjConstr(p: BProc; n: PNode): Rope =
  2160. result = nil
  2161. let t = n.typ.skipTypes(abstractInst)
  2162. var count = 0
  2163. #if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  2164. # addf(result, "{$1}", [genTypeInfo(p.module, t)])
  2165. # inc count
  2166. getNullValueAuxT(p, t, t, t.n, n, result, count)
  2167. if p.module.compileToCpp:
  2168. result = "{$1}$n" % [result]
  2169. proc genConstSimpleList(p: BProc, n: PNode): Rope =
  2170. var length = sonsLen(n)
  2171. result = rope("{")
  2172. let t = n.typ.skipTypes(abstractInst)
  2173. for i in countup(0, length - 2):
  2174. addf(result, "$1,$n", [genNamedConstExpr(p, n.sons[i])])
  2175. if length > 0:
  2176. add(result, genNamedConstExpr(p, n.sons[length - 1]))
  2177. addf(result, "}$n", [])
  2178. proc genConstSeq(p: BProc, n: PNode, t: PType): Rope =
  2179. var data = "{{$1, $1}" % [n.len.rope]
  2180. if n.len > 0:
  2181. # array part needs extra curlies:
  2182. data.add(", {")
  2183. for i in countup(0, n.len - 1):
  2184. if i > 0: data.addf(",$n", [])
  2185. data.add genConstExpr(p, n.sons[i])
  2186. data.add("}")
  2187. data.add("}")
  2188. result = getTempName(p.module)
  2189. let base = t.skipTypes(abstractInst).sons[0]
  2190. appcg(p.module, cfsData,
  2191. "NIM_CONST struct {$n" &
  2192. " #TGenericSeq Sup;$n" &
  2193. " $1 data[$2];$n" &
  2194. "} $3 = $4;$n", [
  2195. getTypeDesc(p.module, base), n.len.rope, result, data])
  2196. result = "(($1)&$2)" % [getTypeDesc(p.module, t), result]
  2197. proc genConstExpr(p: BProc, n: PNode): Rope =
  2198. case n.kind
  2199. of nkHiddenStdConv, nkHiddenSubConv:
  2200. result = genConstExpr(p, n.sons[1])
  2201. of nkCurly:
  2202. var cs: TBitSet
  2203. toBitSet(n, cs)
  2204. result = genRawSetData(cs, int(getSize(n.typ)))
  2205. of nkBracket, nkPar, nkClosure:
  2206. var t = skipTypes(n.typ, abstractInst)
  2207. if t.kind == tySequence:
  2208. result = genConstSeq(p, n, n.typ)
  2209. elif t.kind == tyProc and t.callConv == ccClosure and not n.sons.isNil and
  2210. n.sons[0].kind == nkNilLit and n.sons[1].kind == nkNilLit:
  2211. # this hack fixes issue that nkNilLit is expanded to {NIM_NIL,NIM_NIL}
  2212. # this behaviour is needed since closure_var = nil must be
  2213. # expanded to {NIM_NIL,NIM_NIL}
  2214. # in VM closures are initialized with nkPar(nkNilLit, nkNilLit)
  2215. # leading to duplicate code like this:
  2216. # "{NIM_NIL,NIM_NIL}, {NIM_NIL,NIM_NIL}"
  2217. result = ~"{NIM_NIL,NIM_NIL}"
  2218. else:
  2219. result = genConstSimpleList(p, n)
  2220. of nkObjConstr:
  2221. result = genConstObjConstr(p, n)
  2222. else:
  2223. var d: TLoc
  2224. initLocExpr(p, n, d)
  2225. result = rdLoc(d)