ccgexprs.nim 125 KB

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