ccgexprs.nim 150 KB

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