ccgexprs.nim 129 KB

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