ccgexprs.nim 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034
  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. else:
  2385. if etyp.kind == tyPtr:
  2386. # generates the definition of structs for casts like cast[ptr object](addr x)[]
  2387. let internalType = etyp.skipTypes({tyPtr})
  2388. if internalType.kind == tyObject:
  2389. discard getTypeDesc(p.module, internalType)
  2390. let destTyp = getTypeDesc(p.module, e.typ)
  2391. let val = rdCharLoc(a)
  2392. putIntoDest(p, d, e, cCast(destTyp, wrapPar(val)), a.storage)
  2393. proc genCast(p: BProc, e: PNode, d: var TLoc) =
  2394. const ValueTypes = {tyFloat..tyFloat128, tyTuple, tyObject, tyArray}
  2395. let
  2396. destt = skipTypes(e.typ, abstractRange)
  2397. srct = skipTypes(e[1].typ, abstractRange)
  2398. if destt.kind in ValueTypes or srct.kind in ValueTypes:
  2399. # 'cast' and some float type involved? --> use a union.
  2400. inc(p.labels)
  2401. var lbl = p.labels.rope
  2402. var tmp: TLoc = default(TLoc)
  2403. tmp.snippet = dotField("LOC" & lbl, "source")
  2404. let destsize = getSize(p.config, destt)
  2405. let srcsize = getSize(p.config, srct)
  2406. let srcTyp = getTypeDesc(p.module, e[1].typ)
  2407. let destTyp = getTypeDesc(p.module, e.typ)
  2408. if destsize > srcsize:
  2409. p.s(cpsLocals).addVarWithType(kind = Local, name = "LOC" & lbl):
  2410. p.s(cpsLocals).addUnionType():
  2411. p.s(cpsLocals).addField(name = "dest", typ = destTyp)
  2412. p.s(cpsLocals).addField(name = "source", typ = srcTyp)
  2413. p.s(cpsLocals).addCallStmt(cgsymValue(p.module, "nimZeroMem"),
  2414. cAddr("LOC" & lbl),
  2415. cSizeof("LOC" & lbl))
  2416. else:
  2417. p.s(cpsLocals).addVarWithType(kind = Local, name = "LOC" & lbl):
  2418. p.s(cpsLocals).addUnionType():
  2419. p.s(cpsLocals).addField(name = "source", typ = srcTyp)
  2420. p.s(cpsLocals).addField(name = "dest", typ = destTyp)
  2421. tmp.k = locExpr
  2422. tmp.lode = lodeTyp srct
  2423. tmp.storage = OnStack
  2424. tmp.flags = {}
  2425. expr(p, e[1], tmp)
  2426. putIntoDest(p, d, e, dotField("LOC" & lbl, "dest"), tmp.storage)
  2427. else:
  2428. # I prefer the shorter cast version for pointer types -> generate less
  2429. # C code; plus it's the right thing to do for closures:
  2430. genSomeCast(p, e, d)
  2431. proc genRangeChck(p: BProc, n: PNode, d: var TLoc) =
  2432. var a: TLoc = initLocExpr(p, n[0])
  2433. var dest = skipTypes(n.typ, abstractVar)
  2434. if optRangeCheck notin p.options or (dest.kind in {tyUInt..tyUInt64} and
  2435. checkUnsignedConversions notin p.config.legacyFeatures):
  2436. discard "no need to generate a check because it was disabled"
  2437. else:
  2438. let n0t = n[0].typ
  2439. # emit range check:
  2440. if n0t.kind in {tyUInt, tyUInt64}:
  2441. var first = newBuilder("")
  2442. genLiteral(p, n[1], dest, first)
  2443. var last = newBuilder("")
  2444. genLiteral(p, n[2], dest, last)
  2445. let rca = rdCharLoc(a)
  2446. let rt = getTypeDesc(p.module, n0t)
  2447. p.s(cpsStmts).addSingleIfStmt(cOp(GreaterThan, rca, cCast(rt, extract(last)))):
  2448. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "raiseRangeErrorNoArgs"))
  2449. raiseInstr(p, p.s(cpsStmts))
  2450. else:
  2451. let raiser =
  2452. case skipTypes(n.typ, abstractVarRange).kind
  2453. of tyUInt..tyUInt64, tyChar: "raiseRangeErrorU"
  2454. of tyFloat..tyFloat128: "raiseRangeErrorF"
  2455. else: "raiseRangeErrorI"
  2456. cgsym(p.module, raiser)
  2457. var first = newBuilder("")
  2458. genLiteral(p, n[1], dest, first)
  2459. var last = newBuilder("")
  2460. genLiteral(p, n[2], dest, last)
  2461. let rca = rdCharLoc(a)
  2462. let boundRca =
  2463. if n0t.skipTypes(abstractVarRange).kind in {tyUInt, tyUInt32, tyUInt64}:
  2464. cCast(NimInt64, rca)
  2465. else:
  2466. rca
  2467. let firstVal = extract(first)
  2468. let lastVal = extract(last)
  2469. p.s(cpsStmts).addSingleIfStmt(cOp(Or,
  2470. cOp(LessThan, boundRca, firstVal),
  2471. cOp(GreaterThan, boundRca, lastVal))):
  2472. p.s(cpsStmts).addCallStmt(raiser, rca, firstVal, lastVal)
  2473. raiseInstr(p, p.s(cpsStmts))
  2474. if sameBackendTypeIgnoreRange(dest, n[0].typ):
  2475. # don't cast so an address can be taken for `var` conversions
  2476. let val = rdCharLoc(a)
  2477. putIntoDest(p, d, n, wrapPar(val), a.storage)
  2478. else:
  2479. let destType = getTypeDesc(p.module, dest)
  2480. let val = rdCharLoc(a)
  2481. putIntoDest(p, d, n, cCast(destType, wrapPar(val)), a.storage)
  2482. proc genConv(p: BProc, e: PNode, d: var TLoc) =
  2483. let destType = e.typ.skipTypes({tyVar, tyLent, tyGenericInst, tyAlias, tySink})
  2484. if sameBackendTypeIgnoreRange(destType, e[1].typ):
  2485. expr(p, e[1], d)
  2486. else:
  2487. genSomeCast(p, e, d)
  2488. proc convStrToCStr(p: BProc, n: PNode, d: var TLoc) =
  2489. var a: TLoc = initLocExpr(p, n[0])
  2490. putIntoDest(p, d, n,
  2491. cgCall(p, "nimToCStringConv", rdLoc(a)),
  2492. # "($1 ? $1->data : (NCSTRING)\"\")" % [a.rdLoc],
  2493. a.storage)
  2494. proc convCStrToStr(p: BProc, n: PNode, d: var TLoc) =
  2495. var a: TLoc = initLocExpr(p, n[0])
  2496. if p.module.compileToCpp:
  2497. # fixes for const qualifier; bug #12703; bug #19588
  2498. putIntoDest(p, d, n,
  2499. cgCall(p, "cstrToNimstr", cCast(NimCstring, rdLoc(a))),
  2500. a.storage)
  2501. else:
  2502. putIntoDest(p, d, n,
  2503. cgCall(p, "cstrToNimstr", rdLoc(a)),
  2504. a.storage)
  2505. gcUsage(p.config, n)
  2506. proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
  2507. var x: TLoc
  2508. var a = e[1]
  2509. var b = e[2]
  2510. if a.kind in {nkStrLit..nkTripleStrLit} and a.strVal == "":
  2511. x = initLocExpr(p, e[2])
  2512. let lx = lenExpr(p, x)
  2513. putIntoDest(p, d, e, cOp(Equal, lx, cIntValue(0)))
  2514. elif b.kind in {nkStrLit..nkTripleStrLit} and b.strVal == "":
  2515. x = initLocExpr(p, e[1])
  2516. let lx = lenExpr(p, x)
  2517. putIntoDest(p, d, e, cOp(Equal, lx, cIntValue(0)))
  2518. else:
  2519. binaryExpr(p, e, d, cgCall(p, "eqStrings", ra, rb))
  2520. proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
  2521. if {optNaNCheck, optInfCheck} * p.options != {}:
  2522. const opr: array[mAddF64..mDivF64, TypedBinaryOp] = [Add, Sub, Mul, Div]
  2523. assert(e[1].typ != nil)
  2524. assert(e[2].typ != nil)
  2525. var a = initLocExpr(p, e[1])
  2526. var b = initLocExpr(p, e[2])
  2527. let ra = rdLoc(a)
  2528. let rb = rdLoc(b)
  2529. let rt = getSimpleTypeDesc(p.module, e[1].typ)
  2530. putIntoDest(p, d, e, cOp(opr[m], rt, cCast(rt, ra), cCast(rt, rb)))
  2531. if optNaNCheck in p.options:
  2532. let rd = rdLoc(d)
  2533. p.s(cpsStmts).addSingleIfStmt(cOp(NotEqual, rd, rd)):
  2534. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "raiseFloatInvalidOp"))
  2535. raiseInstr(p, p.s(cpsStmts))
  2536. if optInfCheck in p.options:
  2537. let rd = rdLoc(d)
  2538. p.s(cpsStmts).addSingleIfStmt(cOp(And,
  2539. cOp(NotEqual, rd, cFloatValue(0.0)),
  2540. cOp(Equal, cOp(Mul, rt, rd, cFloatValue(0.5)), rd))):
  2541. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "raiseFloatOverflow"), rd)
  2542. raiseInstr(p, p.s(cpsStmts))
  2543. else:
  2544. binaryArith(p, e, d, m)
  2545. proc genWasMoved(p: BProc; n: PNode) =
  2546. var a: TLoc
  2547. let n1 = n[1].skipAddr
  2548. if p.withinBlockLeaveActions > 0 and notYetAlive(n1):
  2549. discard
  2550. else:
  2551. a = initLocExpr(p, n1, {lfEnforceDeref})
  2552. resetLoc(p, a)
  2553. #linefmt(p, cpsStmts, "#nimZeroMem((void*)$1, sizeof($2));$n",
  2554. # [addrLoc(p.config, a), getTypeDesc(p.module, a.t)])
  2555. proc genMove(p: BProc; n: PNode; d: var TLoc) =
  2556. var a: TLoc = initLocExpr(p, n[1].skipAddr, {lfEnforceDeref})
  2557. if n.len == 4:
  2558. # generated by liftdestructors:
  2559. var src: TLoc = initLocExpr(p, n[2])
  2560. let destVal = rdLoc(a)
  2561. let srcVal = rdLoc(src)
  2562. p.s(cpsStmts).addSingleIfStmt(
  2563. cOp(NotEqual,
  2564. dotField(destVal, "p"),
  2565. dotField(srcVal, "p"))):
  2566. genStmts(p, n[3])
  2567. p.s(cpsStmts).addFieldAssignment(destVal, "len", dotField(srcVal, "len"))
  2568. p.s(cpsStmts).addFieldAssignment(destVal, "p", dotField(srcVal, "p"))
  2569. else:
  2570. if d.k == locNone: d = getTemp(p, n.typ)
  2571. if p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc}:
  2572. genAssignment(p, d, a, {})
  2573. var op = getAttachedOp(p.module.g.graph, n.typ, attachedWasMoved)
  2574. if op == nil:
  2575. resetLoc(p, a)
  2576. else:
  2577. var b = initLocExpr(p, newSymNode(op))
  2578. case skipTypes(a.t, abstractVar+{tyStatic}).kind
  2579. of tyOpenArray, tyVarargs: # todo fixme generated `wasMoved` hooks for
  2580. # openarrays, but it probably shouldn't?
  2581. let ra = rdLoc(a)
  2582. var s: string
  2583. if reifiedOpenArray(a.lode):
  2584. if a.t.kind in {tyVar, tyLent}:
  2585. s = derefField(ra, "Field0") & cArgumentSeparator & derefField(ra, "Field1")
  2586. else:
  2587. s = dotField(ra, "Field0") & cArgumentSeparator & dotField(ra, "Field1")
  2588. else:
  2589. s = ra & cArgumentSeparator & ra & "Len_0"
  2590. p.s(cpsStmts).addCallStmt(rdLoc(b), s)
  2591. else:
  2592. let val = if p.module.compileToCpp: rdLoc(a) else: byRefLoc(p, a)
  2593. p.s(cpsStmts).addCallStmt(rdLoc(b), val)
  2594. else:
  2595. if n[1].kind == nkSym and isSinkParam(n[1].sym):
  2596. var tmp = getTemp(p, n[1].typ.skipTypes({tySink}))
  2597. genAssignment(p, tmp, a, {needToCopySinkParam})
  2598. genAssignment(p, d, tmp, {})
  2599. resetLoc(p, tmp)
  2600. else:
  2601. genAssignment(p, d, a, {})
  2602. resetLoc(p, a)
  2603. proc genDestroy(p: BProc; n: PNode) =
  2604. if optSeqDestructors in p.config.globalOptions:
  2605. let arg = n[1].skipAddr
  2606. let t = arg.typ.skipTypes(abstractInst)
  2607. case t.kind
  2608. of tyString:
  2609. var a: TLoc = initLocExpr(p, arg)
  2610. let ra = rdLoc(a)
  2611. let rp = dotField(ra, "p")
  2612. p.s(cpsStmts).addSingleIfStmt(
  2613. cOp(And, rp,
  2614. cOp(Not, cOp(BitAnd, NimInt,
  2615. derefField(rp, "cap"),
  2616. NimStrlitFlag)))):
  2617. let fn = if optThreads in p.config.globalOptions: "deallocShared" else: "dealloc"
  2618. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, fn), rp)
  2619. of tySequence:
  2620. var a: TLoc = initLocExpr(p, arg)
  2621. let ra = rdLoc(a)
  2622. let rp = dotField(ra, "p")
  2623. let rt = getTypeDesc(p.module, t.elementType)
  2624. p.s(cpsStmts).addSingleIfStmt(
  2625. cOp(And, rp,
  2626. cOp(Not, cOp(BitAnd, NimInt,
  2627. derefField(rp, "cap"),
  2628. NimStrlitFlag)))):
  2629. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "alignedDealloc"),
  2630. rp,
  2631. cAlignof(rt))
  2632. else: discard "nothing to do"
  2633. else:
  2634. let t = n[1].typ.skipTypes(abstractVar)
  2635. let op = getAttachedOp(p.module.g.graph, t, attachedDestructor)
  2636. if op != nil and getBody(p.module.g.graph, op).len != 0:
  2637. internalError(p.config, n.info, "destructor turned out to be not trivial")
  2638. discard "ignore calls to the default destructor"
  2639. proc genDispose(p: BProc; n: PNode) =
  2640. when false:
  2641. let elemType = n[1].typ.skipTypes(abstractVar).elementType
  2642. var a: TLoc = initLocExpr(p, n[1].skipAddr)
  2643. if isFinal(elemType):
  2644. if elemType.destructor != nil:
  2645. var destroyCall = newNodeI(nkCall, n.info)
  2646. genStmts(p, destroyCall)
  2647. lineFmt(p, cpsStmts, "#nimRawDispose($1, NIM_ALIGNOF($2))", [rdLoc(a), getTypeDesc(p.module, elemType)])
  2648. else:
  2649. # ``nimRawDisposeVirtual`` calls the ``finalizer`` which is the same as the
  2650. # destructor, but it uses the runtime type. Afterwards the memory is freed:
  2651. lineCg(p, cpsStmts, ["#nimDestroyAndDispose($#)", rdLoc(a)])
  2652. proc genSlice(p: BProc; e: PNode; d: var TLoc) =
  2653. let (x, y) = genOpenArraySlice(p, e, e.typ, e.typ.elementType,
  2654. prepareForMutation = e[1].kind == nkHiddenDeref and
  2655. e[1].typ.skipTypes(abstractInst).kind == tyString and
  2656. p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc})
  2657. if d.k == locNone: d = getTemp(p, e.typ)
  2658. let dest = rdLoc(d)
  2659. p.s(cpsStmts).addFieldAssignment(dest, "Field0", x)
  2660. p.s(cpsStmts).addFieldAssignment(dest, "Field1", y)
  2661. when false:
  2662. localError(p.config, e.info, "invalid context for 'toOpenArray'; " &
  2663. "'toOpenArray' is only valid within a call expression")
  2664. proc genEnumToStr(p: BProc, e: PNode, d: var TLoc) =
  2665. let t = e[1].typ.skipTypes(abstractInst+{tyRange})
  2666. let toStrProc = getToStringProc(p.module.g.graph, t)
  2667. # XXX need to modify this logic for IC.
  2668. var n = copyTree(e)
  2669. n[0] = newSymNode(toStrProc)
  2670. expr(p, n, d)
  2671. proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
  2672. case op
  2673. of mOr, mAnd: genAndOr(p, e, d, op)
  2674. of mNot..mUnaryMinusF64: unaryArith(p, e, d, op)
  2675. of mUnaryMinusI..mAbsI: unaryArithOverflow(p, e, d, op)
  2676. of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
  2677. of mShrI..mXor: binaryArith(p, e, d, op)
  2678. of mEqProc: genEqProc(p, e, d)
  2679. of mAddI..mPred: binaryArithOverflow(p, e, d, op)
  2680. of mRepr: genRepr(p, e, d)
  2681. of mGetTypeInfo: genGetTypeInfo(p, e, d)
  2682. of mGetTypeInfoV2: genGetTypeInfoV2(p, e, d)
  2683. of mSwap: genSwap(p, e, d)
  2684. of mInc, mDec:
  2685. const opr: array[mInc..mDec, TypedBinaryOp] = [Add, Sub]
  2686. const fun64: array[mInc..mDec, string] = ["nimAddInt64", "nimSubInt64"]
  2687. const fun: array[mInc..mDec, string] = ["nimAddInt","nimSubInt"]
  2688. let underlying = skipTypes(e[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent, tyRange, tyDistinct})
  2689. if optOverflowCheck notin p.options or underlying.kind in {tyUInt..tyUInt64}:
  2690. binaryStmt(p, e, d, opr[op])
  2691. else:
  2692. assert(e[1].typ != nil)
  2693. assert(e[2].typ != nil)
  2694. var a = initLocExpr(p, e[1])
  2695. var b = initLocExpr(p, e[2])
  2696. let ranged = skipTypes(e[1].typ, {tyGenericInst, tyAlias, tySink, tyVar, tyLent, tyDistinct})
  2697. let res = binaryArithOverflowRaw(p, ranged, a, b,
  2698. if underlying.kind == tyInt64: fun64[op] else: fun[op])
  2699. let destTyp = getTypeDesc(p.module, ranged)
  2700. putIntoDest(p, a, e[1], cCast(destTyp, wrapPar(res)))
  2701. of mConStrStr: genStrConcat(p, e, d)
  2702. of mAppendStrCh:
  2703. if optSeqDestructors in p.config.globalOptions:
  2704. binaryStmtAddr(p, e, d, "nimAddCharV1")
  2705. else:
  2706. var call = initLoc(locCall, e, OnHeap)
  2707. var dest = initLocExpr(p, e[1])
  2708. var b = initLocExpr(p, e[2])
  2709. call.snippet = cgCall(p, "addChar", rdLoc(dest), rdLoc(b))
  2710. genAssignment(p, dest, call, {})
  2711. of mAppendStrStr: genStrAppend(p, e, d)
  2712. of mAppendSeqElem:
  2713. if optSeqDestructors in p.config.globalOptions:
  2714. e[1] = makeAddr(e[1], p.module.idgen)
  2715. genCall(p, e, d)
  2716. else:
  2717. genSeqElemAppend(p, e, d)
  2718. of mEqStr: genStrEquals(p, e, d)
  2719. of mLeStr:
  2720. binaryExpr(p, e, d, cOp(LessEqual,
  2721. cgCall(p, "cmpStrings", ra, rb),
  2722. cIntValue(0)))
  2723. of mLtStr:
  2724. binaryExpr(p, e, d, cOp(LessThan,
  2725. cgCall(p, "cmpStrings", ra, rb),
  2726. cIntValue(0)))
  2727. of mIsNil: genIsNil(p, e, d)
  2728. of mBoolToStr:
  2729. genDollarIt(p, e, d, cgCall(p, "nimBoolToStr", it))
  2730. of mCharToStr:
  2731. genDollarIt(p, e, d, cgCall(p, "nimCharToStr", it))
  2732. of mCStrToStr:
  2733. if p.module.compileToCpp:
  2734. # fixes for const qualifier; bug #12703; bug #19588
  2735. genDollarIt(p, e, d, cgCall(p, "cstrToNimstr", cCast(NimCstring, it)))
  2736. else:
  2737. genDollarIt(p, e, d, cgCall(p, "cstrToNimstr", it))
  2738. of mStrToStr, mUnown: expr(p, e[1], d)
  2739. of generatedMagics: genCall(p, e, d)
  2740. of mEnumToStr:
  2741. if optTinyRtti in p.config.globalOptions:
  2742. genEnumToStr(p, e, d)
  2743. else:
  2744. genRepr(p, e, d)
  2745. of mOf: genOf(p, e, d)
  2746. of mNew: genNew(p, e)
  2747. of mNewFinalize:
  2748. if optTinyRtti in p.config.globalOptions:
  2749. var a: TLoc = initLocExpr(p, e[1])
  2750. rawGenNew(p, a, "", needsInit = true)
  2751. gcUsage(p.config, e)
  2752. else:
  2753. genNewFinalize(p, e)
  2754. of mNewSeq:
  2755. if optSeqDestructors in p.config.globalOptions:
  2756. e[1] = makeAddr(e[1], p.module.idgen)
  2757. genCall(p, e, d)
  2758. else:
  2759. genNewSeq(p, e)
  2760. of mNewSeqOfCap: genNewSeqOfCap(p, e, d)
  2761. of mSizeOf:
  2762. let t = e[1].typ.skipTypes({tyTypeDesc})
  2763. putIntoDest(p, d, e, cCast(NimInt, cSizeof(getTypeDesc(p.module, t, dkVar))))
  2764. of mAlignOf:
  2765. let t = e[1].typ.skipTypes({tyTypeDesc})
  2766. putIntoDest(p, d, e, cCast(NimInt, cAlignof(getTypeDesc(p.module, t, dkVar))))
  2767. of mOffsetOf:
  2768. var dotExpr: PNode
  2769. if e[1].kind == nkDotExpr:
  2770. dotExpr = e[1]
  2771. elif e[1].kind == nkCheckedFieldExpr:
  2772. dotExpr = e[1][0]
  2773. else:
  2774. dotExpr = nil
  2775. internalError(p.config, e.info, "unknown ast")
  2776. let t = dotExpr[0].typ.skipTypes({tyTypeDesc})
  2777. let tname = getTypeDesc(p.module, t, dkVar)
  2778. let member =
  2779. if t.kind == tyTuple:
  2780. "Field" & rope(dotExpr[1].sym.position)
  2781. else: dotExpr[1].sym.loc.snippet
  2782. putIntoDest(p,d,e, cCast(NimInt, cOffsetof(tname, member)))
  2783. of mChr: genSomeCast(p, e, d)
  2784. of mOrd: genOrd(p, e, d)
  2785. of mLengthArray, mHigh, mLengthStr, mLengthSeq, mLengthOpenArray:
  2786. genArrayLen(p, e, d, op)
  2787. of mGCref:
  2788. # only a magic for the old GCs
  2789. var a: TLoc = initLocExpr(p, e[1])
  2790. let ra = rdLoc(a)
  2791. p.s(cpsStmts).addSingleIfStmt(ra):
  2792. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimGCref"), ra)
  2793. of mGCunref:
  2794. # only a magic for the old GCs
  2795. var a: TLoc = initLocExpr(p, e[1])
  2796. let ra = rdLoc(a)
  2797. p.s(cpsStmts).addSingleIfStmt(ra):
  2798. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimGCunref"), ra)
  2799. of mSetLengthStr: genSetLengthStr(p, e, d)
  2800. of mSetLengthSeq: genSetLengthSeq(p, e, d)
  2801. of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet,
  2802. mInSet, mXorSet:
  2803. genSetOp(p, e, d, op)
  2804. of mNewString, mNewStringOfCap, mExit, mParseBiggestFloat:
  2805. var opr = e[0].sym
  2806. # Why would anyone want to set nodecl to one of these hardcoded magics?
  2807. # - not sure, and it wouldn't work if the symbol behind the magic isn't
  2808. # somehow forward-declared from some other usage, but it is *possible*
  2809. if lfNoDecl notin opr.loc.flags:
  2810. let prc = magicsys.getCompilerProc(p.module.g.graph, $opr.loc.snippet)
  2811. assert prc != nil, $opr.loc.snippet
  2812. # HACK:
  2813. # Explicitly add this proc as declared here so the cgsym call doesn't
  2814. # add a forward declaration - without this we could end up with the same
  2815. # 2 forward declarations. That happens because the magic symbol and the original
  2816. # one that shall be used have different ids (even though a call to one is
  2817. # actually a call to the other) so checking into m.declaredProtos with the 2 different ids doesn't work.
  2818. # Why would 2 identical forward declarations be a problem?
  2819. # - in the case of hot code-reloading we generate function pointers instead
  2820. # of forward declarations and in C++ it is an error to redefine a global
  2821. let wasDeclared = containsOrIncl(p.module.declaredProtos, prc.id)
  2822. # Make the function behind the magic get actually generated - this will
  2823. # not lead to a forward declaration! The genCall will lead to one.
  2824. cgsym(p.module, $opr.loc.snippet)
  2825. # make sure we have pointer-initialising code for hot code reloading
  2826. if not wasDeclared and p.hcrOn:
  2827. let name = mangleDynLibProc(prc)
  2828. let rt = getTypeDesc(p.module, prc.loc.t)
  2829. p.module.s[cfsDynLibInit].add('\t')
  2830. p.module.s[cfsDynLibInit].addAssignmentWithValue(name):
  2831. p.module.s[cfsDynLibInit].addCast(rt):
  2832. p.module.s[cfsDynLibInit].addCall("hcrGetProc",
  2833. getModuleDllPath(p.module, prc),
  2834. '"' & name & '"')
  2835. genCall(p, e, d)
  2836. of mDefault, mZeroDefault: genDefault(p, e, d)
  2837. of mEcho: genEcho(p, e[1].skipConv)
  2838. of mArrToSeq: genArrToSeq(p, e, d)
  2839. of mNLen..mNError, mSlurp..mQuoteAst:
  2840. localError(p.config, e.info, strutils.`%`(errXMustBeCompileTime, e[0].sym.name.s))
  2841. of mSpawn:
  2842. when defined(leanCompiler):
  2843. p.config.quitOrRaise "compiler built without support for the 'spawn' statement"
  2844. else:
  2845. let n = spawn.wrapProcForSpawn(p.module.g.graph, p.module.idgen, p.module.module, e, e.typ, nil, nil)
  2846. expr(p, n, d)
  2847. of mParallel:
  2848. when defined(leanCompiler):
  2849. p.config.quitOrRaise "compiler built without support for the 'parallel' statement"
  2850. else:
  2851. let n = semparallel.liftParallel(p.module.g.graph, p.module.idgen, p.module.module, e)
  2852. expr(p, n, d)
  2853. of mDeepCopy:
  2854. if p.config.selectedGC in {gcArc, gcAtomicArc, gcOrc} and optEnableDeepCopy notin p.config.globalOptions:
  2855. localError(p.config, e.info,
  2856. "for --mm:arc|atomicArc|orc 'deepcopy' support has to be enabled with --deepcopy:on")
  2857. let x = if e[1].kind in {nkAddr, nkHiddenAddr}: e[1][0] else: e[1]
  2858. var a = initLocExpr(p, x)
  2859. var b = initLocExpr(p, e[2])
  2860. genDeepCopy(p, a, b)
  2861. of mDotDot, mEqCString: genCall(p, e, d)
  2862. of mWasMoved: genWasMoved(p, e)
  2863. of mMove: genMove(p, e, d)
  2864. of mDestroy: genDestroy(p, e)
  2865. of mAccessEnv: unaryExpr(p, e, d, dotField(ra, "ClE_0"))
  2866. of mAccessTypeField: genAccessTypeField(p, e, d)
  2867. of mSlice: genSlice(p, e, d)
  2868. of mTrace: discard "no code to generate"
  2869. of mEnsureMove:
  2870. expr(p, e[1], d)
  2871. of mDup:
  2872. expr(p, e[1], d)
  2873. else:
  2874. when defined(debugMagics):
  2875. echo p.prc.name.s, " ", p.prc.id, " ", p.prc.flags, " ", p.prc.ast[genericParamsPos].kind
  2876. internalError(p.config, e.info, "genMagicExpr: " & $op)
  2877. proc genSetConstr(p: BProc, e: PNode, d: var TLoc) =
  2878. # example: { a..b, c, d, e, f..g }
  2879. # we have to emit an expression of the form:
  2880. # nimZeroMem(tmp, sizeof(tmp)); inclRange(tmp, a, b); incl(tmp, c);
  2881. # incl(tmp, d); incl(tmp, e); inclRange(tmp, f, g);
  2882. var
  2883. a, b: TLoc
  2884. var idx: TLoc
  2885. if nfAllConst in e.flags:
  2886. var elem = newBuilder("")
  2887. genSetNode(p, e, elem)
  2888. putIntoDest(p, d, e, extract(elem))
  2889. else:
  2890. if d.k == locNone: d = getTemp(p, e.typ)
  2891. let size = getSize(p.config, e.typ)
  2892. if size > 8:
  2893. # big set:
  2894. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "nimZeroMem"),
  2895. rdLoc(d),
  2896. cSizeof(getTypeDesc(p.module, e.typ)))
  2897. for it in e.sons:
  2898. if it.kind == nkRange:
  2899. idx = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt)) # our counter
  2900. a = initLocExpr(p, it[0])
  2901. b = initLocExpr(p, it[1])
  2902. var aa: Snippet = ""
  2903. rdSetElemLoc(p.config, a, e.typ, aa)
  2904. var bb: Snippet = ""
  2905. rdSetElemLoc(p.config, b, e.typ, bb)
  2906. let ri = rdLoc(idx)
  2907. let rd = rdLoc(d)
  2908. p.s(cpsStmts).addForRangeInclusive(ri, aa, bb):
  2909. p.s(cpsStmts).addInPlaceOp(BitOr, NimUint8,
  2910. subscript(rd, cOp(Shr, NimUint, cCast(NimUint, ri), cIntValue(3))),
  2911. cOp(Shl, NimUint8, cUintValue(1),
  2912. cOp(BitAnd, NimUint, cCast(NimUint, ri), cUintValue(7))))
  2913. else:
  2914. a = initLocExpr(p, it)
  2915. var aa: Snippet = ""
  2916. rdSetElemLoc(p.config, a, e.typ, aa)
  2917. let rd = rdLoc(d)
  2918. p.s(cpsStmts).addInPlaceOp(BitOr, NimUint8,
  2919. subscript(rd, cOp(Shr, NimUint, cCast(NimUint, aa), cIntValue(3))),
  2920. cOp(Shl, NimUint8, cUintValue(1),
  2921. cOp(BitAnd, NimUint, cCast(NimUint, aa), cUintValue(7))))
  2922. else:
  2923. # small set
  2924. var ts = cUintType(size * 8)
  2925. p.s(cpsStmts).addAssignment(rdLoc(d), cIntValue(0))
  2926. for it in e.sons:
  2927. if it.kind == nkRange:
  2928. idx = getTemp(p, getSysType(p.module.g.graph, unknownLineInfo, tyInt)) # our counter
  2929. a = initLocExpr(p, it[0])
  2930. b = initLocExpr(p, it[1])
  2931. var aa: Snippet = ""
  2932. rdSetElemLoc(p.config, a, e.typ, aa)
  2933. var bb: Snippet = ""
  2934. rdSetElemLoc(p.config, b, e.typ, bb)
  2935. let ri = rdLoc(idx)
  2936. let rd = rdLoc(d)
  2937. p.s(cpsStmts).addForRangeInclusive(ri, aa, bb):
  2938. p.s(cpsStmts).addInPlaceOp(BitOr, ts, rd,
  2939. cOp(Shl, ts, cCast(ts, cIntValue(1)),
  2940. cOp(Mod, ts, ri, cOp(Mul, ts, cIntValue(size), cIntValue(8)))))
  2941. else:
  2942. a = initLocExpr(p, it)
  2943. var aa: Snippet = ""
  2944. rdSetElemLoc(p.config, a, e.typ, aa)
  2945. let rd = rdLoc(d)
  2946. p.s(cpsStmts).addInPlaceOp(BitOr, ts, rd,
  2947. cOp(Shl, ts, cCast(ts, cIntValue(1)),
  2948. cOp(Mod, ts, aa, cOp(Mul, ts, cIntValue(size), cIntValue(8)))))
  2949. proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) =
  2950. var rec: TLoc
  2951. if not handleConstExpr(p, n, d):
  2952. let t = n.typ
  2953. discard getTypeDesc(p.module, t) # so that any fields are initialized
  2954. var tmp: TLoc = default(TLoc)
  2955. # bug #16331
  2956. let doesAlias = lhsDoesAlias(d.lode, n)
  2957. let dest = if doesAlias: addr(tmp) else: addr(d)
  2958. if doesAlias:
  2959. tmp = getTemp(p, n.typ)
  2960. elif d.k == locNone:
  2961. d = getTemp(p, n.typ)
  2962. for i in 0..<n.len:
  2963. var it = n[i]
  2964. if it.kind == nkExprColonExpr: it = it[1]
  2965. rec = initLoc(locExpr, it, dest[].storage)
  2966. rec.snippet = dotField(rdLoc(dest[]), "Field" & rope(i))
  2967. rec.flags.incl(lfEnforceDeref)
  2968. expr(p, it, rec)
  2969. if doesAlias:
  2970. if d.k == locNone:
  2971. d = tmp
  2972. else:
  2973. genAssignment(p, d, tmp, {})
  2974. proc isConstClosure(n: PNode): bool {.inline.} =
  2975. result = n[0].kind == nkSym and isRoutine(n[0].sym) and
  2976. n[1].kind == nkNilLit
  2977. proc genClosure(p: BProc, n: PNode, d: var TLoc) =
  2978. assert n.kind in {nkPar, nkTupleConstr, nkClosure}
  2979. if isConstClosure(n):
  2980. inc(p.module.labels)
  2981. var tmp = "CNSTCLOSURE" & rope(p.module.labels)
  2982. let td = getTypeDesc(p.module, n.typ)
  2983. var data = newBuilder("")
  2984. data.addVarWithInitializer(kind = Const, name = tmp, typ = td):
  2985. genBracedInit(p, n, isConst = true, n.typ, data)
  2986. p.module.s[cfsData].add(extract(data))
  2987. putIntoDest(p, d, n, tmp, OnStatic)
  2988. else:
  2989. var tmp: TLoc
  2990. var a = initLocExpr(p, n[0])
  2991. var b = initLocExpr(p, n[1])
  2992. if n[0].skipConv.kind == nkClosure:
  2993. internalError(p.config, n.info, "closure to closure created")
  2994. # tasyncawait.nim breaks with this optimization:
  2995. when false:
  2996. if d.k != locNone:
  2997. let dest = d.rdLoc
  2998. p.s(cpsStmts).addFieldAssignment(dest, "ClP_0", a.rdLoc)
  2999. p.s(cpsStmts).addFieldAssignment(dest, "ClE_0", b.rdLoc)
  3000. else:
  3001. tmp = getTemp(p, n.typ)
  3002. let dest = tmp.rdLoc
  3003. p.s(cpsStmts).addFieldAssignment(dest, "ClP_0", a.rdLoc)
  3004. p.s(cpsStmts).addFieldAssignment(dest, "ClE_0", b.rdLoc)
  3005. putLocIntoDest(p, d, tmp)
  3006. proc genArrayConstr(p: BProc, n: PNode, d: var TLoc) =
  3007. var arr: TLoc
  3008. if not handleConstExpr(p, n, d):
  3009. if d.k == locNone: d = getTemp(p, n.typ)
  3010. for i in 0..<n.len:
  3011. arr = initLoc(locExpr, lodeTyp elemType(skipTypes(n.typ, abstractInst)), d.storage)
  3012. let lit = cIntLiteral(i)
  3013. arr.snippet = subscript(rdLoc(d), lit)
  3014. expr(p, n[i], arr)
  3015. proc genComplexConst(p: BProc, sym: PSym, d: var TLoc) =
  3016. requestConstImpl(p, sym)
  3017. assert((sym.loc.snippet != "") and (sym.loc.t != nil))
  3018. putLocIntoDest(p, d, sym.loc)
  3019. template genStmtListExprImpl(exprOrStmt) {.dirty.} =
  3020. #let hasNimFrame = magicsys.getCompilerProc("nimFrame") != nil
  3021. let hasNimFrame = p.prc != nil and
  3022. sfSystemModule notin p.module.module.flags and
  3023. optStackTrace in p.prc.options
  3024. var frameName: Rope = ""
  3025. for i in 0..<n.len - 1:
  3026. let it = n[i]
  3027. if it.kind == nkComesFrom:
  3028. if hasNimFrame and frameName == "":
  3029. inc p.labels
  3030. frameName = "FR" & rope(p.labels) & "_"
  3031. let theMacro = it[0].sym
  3032. add p.s(cpsStmts), initFrameNoDebug(p, frameName,
  3033. makeCString theMacro.name.s,
  3034. quotedFilename(p.config, theMacro.info), it.info.line.int)
  3035. else:
  3036. genStmts(p, it)
  3037. if n.len > 0: exprOrStmt
  3038. if frameName != "":
  3039. p.s(cpsStmts).add deinitFrameNoDebug(p, frameName)
  3040. proc genStmtListExpr(p: BProc, n: PNode, d: var TLoc) =
  3041. genStmtListExprImpl:
  3042. expr(p, n[^1], d)
  3043. proc genStmtList(p: BProc, n: PNode) =
  3044. genStmtListExprImpl:
  3045. genStmts(p, n[^1])
  3046. from parampatterns import isLValue
  3047. proc upConv(p: BProc, n: PNode, d: var TLoc) =
  3048. var a: TLoc = initLocExpr(p, n[0])
  3049. let dest = skipTypes(n.typ, abstractPtrs)
  3050. if optObjCheck in p.options and not isObjLackingTypeField(dest):
  3051. var nilCheck = ""
  3052. var r: Snippet = ""
  3053. rdMType(p, a, nilCheck, r)
  3054. if optTinyRtti in p.config.globalOptions:
  3055. let checkFor = $getObjDepth(dest)
  3056. let token = $genDisplayElem(MD5Digest(hashType(dest, p.config)))
  3057. let objCheck = cOp(Not, cgCall(p, "isObjDisplayCheck", r, checkFor, token))
  3058. let check = if nilCheck != "": cOp(And, nilCheck, objCheck) else: objCheck
  3059. p.s(cpsStmts).addSingleIfStmt(check):
  3060. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "raiseObjectConversionError"))
  3061. raiseInstr(p, p.s(cpsStmts))
  3062. else:
  3063. let checkFor = genTypeInfoV1(p.module, dest, n.info)
  3064. let objCheck = cOp(Not, cgCall(p, "isObj", r, checkFor))
  3065. let check = if nilCheck != "": cOp(And, nilCheck, objCheck) else: objCheck
  3066. p.s(cpsStmts).addSingleIfStmt(check):
  3067. p.s(cpsStmts).addCallStmt(cgsymValue(p.module, "raiseObjectConversionError"))
  3068. raiseInstr(p, p.s(cpsStmts))
  3069. if n[0].typ.kind != tyObject:
  3070. let destTyp = getTypeDesc(p.module, n.typ)
  3071. let val = rdLoc(a)
  3072. if n.isLValue:
  3073. # (*((destType) (&(val))))"
  3074. putIntoDest(p, d, n,
  3075. cDeref(
  3076. cCast(ptrType(destTyp),
  3077. wrapPar(cAddr(wrapPar(val))))),
  3078. a.storage)
  3079. else:
  3080. # ((destType) (val))"
  3081. putIntoDest(p, d, n, cCast(destTyp, wrapPar(val)), a.storage)
  3082. else:
  3083. let destTyp = getTypeDesc(p.module, dest)
  3084. let val = addrLoc(p.config, a)
  3085. # (* (destType*) val)
  3086. putIntoDest(p, d, n,
  3087. cDeref(
  3088. cCast(ptrType(destTyp),
  3089. wrapPar(val))),
  3090. a.storage)
  3091. proc downConv(p: BProc, n: PNode, d: var TLoc) =
  3092. var arg = n[0]
  3093. while arg.kind == nkObjDownConv: arg = arg[0]
  3094. let dest = skipTypes(n.typ, abstractPtrs)
  3095. let src = skipTypes(arg.typ, abstractPtrs)
  3096. discard getTypeDesc(p.module, src)
  3097. let isRef = skipTypes(arg.typ, abstractInstOwned).kind in {tyRef, tyPtr, tyVar, tyLent}
  3098. if isRef and d.k == locNone and n.typ.skipTypes(abstractInstOwned).kind in {tyRef, tyPtr} and n.isLValue:
  3099. # it can happen that we end up generating '&&x->Sup' here, so we pack
  3100. # the '&x->Sup' into a temporary and then those address is taken
  3101. # (see bug #837). However sometimes using a temporary is not correct:
  3102. # init(TFigure(my)) # where it is passed to a 'var TFigure'. We test
  3103. # this by ensuring the destination is also a pointer:
  3104. var a: TLoc = initLocExpr(p, arg)
  3105. let destType = getTypeDesc(p.module, n.typ)
  3106. let val = rdLoc(a)
  3107. # (* ((destType*) (&(val))))
  3108. putIntoDest(p, d, n,
  3109. cDeref(
  3110. cCast(ptrType(destType),
  3111. wrapPar(cAddr(wrapPar(val))))),
  3112. a.storage)
  3113. elif p.module.compileToCpp:
  3114. # C++ implicitly downcasts for us
  3115. expr(p, arg, d)
  3116. else:
  3117. var a: TLoc = initLocExpr(p, arg)
  3118. var r = rdLoc(a)
  3119. if isRef:
  3120. r = derefField(r, "Sup")
  3121. else:
  3122. r = dotField(r, "Sup")
  3123. for i in 2..abs(inheritanceDiff(dest, src)):
  3124. r = dotField(r, "Sup")
  3125. if isRef:
  3126. r = cAddr(r)
  3127. putIntoDest(p, d, n, r, a.storage)
  3128. proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) =
  3129. let t = n.typ
  3130. discard getTypeDesc(p.module, t) # so that any fields are initialized
  3131. let id = nodeTableTestOrSet(p.module.dataCache, n, p.module.labels)
  3132. let tmp = p.module.tmpBase & rope(id)
  3133. if id == p.module.labels:
  3134. # expression not found in the cache:
  3135. inc(p.module.labels)
  3136. let td = getTypeDesc(p.module, t, dkConst)
  3137. var data = newBuilder("")
  3138. data.addVarWithInitializer(
  3139. kind = Const, name = tmp, typ = td):
  3140. genBracedInit(p, n, isConst = true, t, data)
  3141. p.module.s[cfsData].add(extract(data))
  3142. if d.k == locNone:
  3143. fillLoc(d, locData, n, tmp, OnStatic)
  3144. else:
  3145. putDataIntoDest(p, d, n, tmp)
  3146. # This fixes bug #4551, but we really need better dataflow
  3147. # analysis to make this 100% safe.
  3148. if t.kind notin {tySequence, tyString}:
  3149. d.storage = OnStatic
  3150. proc genConstSetup(p: BProc; sym: PSym): bool =
  3151. let m = p.module
  3152. useHeader(m, sym)
  3153. if sym.loc.k == locNone:
  3154. fillBackendName(p.module, sym)
  3155. fillLoc(sym.loc, locData, sym.astdef, OnStatic)
  3156. if m.hcrOn: incl(sym.loc.flags, lfIndirect)
  3157. result = lfNoDecl notin sym.loc.flags
  3158. proc genConstHeader(m, q: BModule; p: BProc, sym: PSym) =
  3159. if sym.loc.snippet == "":
  3160. if not genConstSetup(p, sym): return
  3161. assert(sym.loc.snippet != "", $sym.name.s & $sym.itemId)
  3162. if m.hcrOn:
  3163. m.s[cfsVars].addVar(kind = Global, name = sym.loc.snippet,
  3164. typ = ptrType(getTypeDesc(m, sym.loc.t, dkVar)))
  3165. m.initProc.procSec(cpsLocals).add('\t')
  3166. m.initProc.procSec(cpsLocals).addAssignmentWithValue(sym.loc.snippet):
  3167. m.initProc.procSec(cpsLocals).addCast(ptrType(getTypeDesc(m, sym.loc.t, dkVar))):
  3168. var getGlobalCall: CallBuilder
  3169. m.initProc.procSec(cpsLocals).addCall("hcrGetGlobal",
  3170. getModuleDllPath(q, sym),
  3171. '"' & sym.loc.snippet & '"')
  3172. else:
  3173. var headerDecl = newBuilder("")
  3174. headerDecl.addDeclWithVisibility(Extern):
  3175. headerDecl.addVar(kind = Local, name = sym.loc.snippet,
  3176. typ = constType(getTypeDesc(m, sym.loc.t, dkVar)))
  3177. m.s[cfsData].add(extract(headerDecl))
  3178. if sfExportc in sym.flags and p.module.g.generatedHeader != nil:
  3179. p.module.g.generatedHeader.s[cfsData].add(extract(headerDecl))
  3180. proc genConstDefinition(q: BModule; p: BProc; sym: PSym) =
  3181. # add a suffix for hcr - will later init the global pointer with this data
  3182. let actualConstName = if q.hcrOn: sym.loc.snippet & "_const" else: sym.loc.snippet
  3183. let td = constType(getTypeDesc(q, sym.typ))
  3184. var data = newBuilder("")
  3185. data.addDeclWithVisibility(Private):
  3186. data.addVarWithInitializer(Local, actualConstName, typ = td):
  3187. genBracedInit(q.initProc, sym.astdef, isConst = true, sym.typ, data)
  3188. q.s[cfsData].add(extract(data))
  3189. if q.hcrOn:
  3190. # generate the global pointer with the real name
  3191. q.s[cfsVars].addVar(kind = Global, name = sym.loc.snippet,
  3192. typ = ptrType(getTypeDesc(q, sym.loc.t, dkVar)))
  3193. # register it (but ignore the boolean result of hcrRegisterGlobal)
  3194. q.initProc.procSec(cpsLocals).add('\t')
  3195. q.initProc.procSec(cpsLocals).addStmt():
  3196. var registerCall: CallBuilder
  3197. q.initProc.procSec(cpsLocals).addCall(registerCall, "hcrRegisterGlobal"):
  3198. q.initProc.procSec(cpsLocals).addArgument(registerCall):
  3199. q.initProc.procSec(cpsLocals).add(getModuleDllPath(q, sym))
  3200. q.initProc.procSec(cpsLocals).addArgument(registerCall):
  3201. q.initProc.procSec(cpsLocals).add('"' & sym.loc.snippet & '"')
  3202. q.initProc.procSec(cpsLocals).addArgument(registerCall):
  3203. q.initProc.procSec(cpsLocals).addSizeof(rdLoc(sym.loc))
  3204. q.initProc.procSec(cpsLocals).addArgument(registerCall):
  3205. q.initProc.procSec(cpsLocals).add(CNil)
  3206. q.initProc.procSec(cpsLocals).addArgument(registerCall):
  3207. q.initProc.procSec(cpsLocals).addCast(ptrType(CPointer)):
  3208. q.initProc.procSec(cpsLocals).add(cAddr(sym.loc.snippet))
  3209. # always copy over the contents of the actual constant with the _const
  3210. # suffix ==> this means that the constant is reloadable & updatable!
  3211. q.initProc.procSec(cpsLocals).add('\t')
  3212. q.initProc.procSec(cpsLocals).addStmt():
  3213. var copyCall: CallBuilder
  3214. q.initProc.procSec(cpsLocals).addCall(copyCall, cgsymValue(q, "nimCopyMem")):
  3215. q.initProc.procSec(cpsLocals).addArgument(copyCall):
  3216. q.initProc.procSec(cpsLocals).add(cCast(CPointer, sym.loc.snippet))
  3217. q.initProc.procSec(cpsLocals).addArgument(copyCall):
  3218. q.initProc.procSec(cpsLocals).add(cCast(CConstPointer, cAddr(actualConstName)))
  3219. q.initProc.procSec(cpsLocals).addArgument(copyCall):
  3220. q.initProc.procSec(cpsLocals).addSizeof(rdLoc(sym.loc))
  3221. proc genConstStmt(p: BProc, n: PNode) =
  3222. # This code is only used in the new DCE implementation.
  3223. assert useAliveDataFromDce in p.module.flags
  3224. let m = p.module
  3225. for it in n:
  3226. if it[0].kind == nkSym:
  3227. let sym = it[0].sym
  3228. if not isSimpleConst(sym.typ) and sym.itemId.item in m.alive and genConstSetup(p, sym):
  3229. genConstDefinition(m, p, sym)
  3230. proc expr(p: BProc, n: PNode, d: var TLoc) =
  3231. when defined(nimCompilerStacktraceHints):
  3232. setFrameMsg p.config$n.info & " " & $n.kind
  3233. p.currLineInfo = n.info
  3234. case n.kind
  3235. of nkSym:
  3236. var sym = n.sym
  3237. case sym.kind
  3238. of skMethod:
  3239. if useAliveDataFromDce in p.module.flags or {sfDispatcher, sfForward} * sym.flags != {}:
  3240. # we cannot produce code for the dispatcher yet:
  3241. fillProcLoc(p.module, n)
  3242. genProcPrototype(p.module, sym)
  3243. else:
  3244. genProc(p.module, sym)
  3245. putLocIntoDest(p, d, sym.loc)
  3246. of skProc, skConverter, skIterator, skFunc:
  3247. #if sym.kind == skIterator:
  3248. # echo renderTree(sym.getBody, {renderIds})
  3249. if sfCompileTime in sym.flags:
  3250. localError(p.config, n.info, "request to generate code for .compileTime proc: " &
  3251. sym.name.s)
  3252. if useAliveDataFromDce in p.module.flags and sym.typ.callConv != ccInline:
  3253. fillProcLoc(p.module, n)
  3254. genProcPrototype(p.module, sym)
  3255. else:
  3256. genProc(p.module, sym)
  3257. if sym.loc.snippet == "" or sym.loc.lode == nil:
  3258. internalError(p.config, n.info, "expr: proc not init " & sym.name.s)
  3259. putLocIntoDest(p, d, sym.loc)
  3260. of skConst:
  3261. if isSimpleConst(sym.typ):
  3262. var lit = newBuilder("")
  3263. genLiteral(p, sym.astdef, sym.typ, lit)
  3264. putIntoDest(p, d, n, extract(lit), OnStatic)
  3265. elif useAliveDataFromDce in p.module.flags:
  3266. genConstHeader(p.module, p.module, p, sym)
  3267. assert((sym.loc.snippet != "") and (sym.loc.t != nil))
  3268. putLocIntoDest(p, d, sym.loc)
  3269. else:
  3270. genComplexConst(p, sym, d)
  3271. of skEnumField:
  3272. # we never reach this case - as of the time of this comment,
  3273. # skEnumField is folded to an int in semfold.nim, but this code
  3274. # remains for robustness
  3275. putIntoDest(p, d, n, cIntValue(sym.position))
  3276. of skVar, skForVar, skResult, skLet:
  3277. if {sfGlobal, sfThread} * sym.flags != {}:
  3278. genVarPrototype(p.module, n)
  3279. if sfCompileTime in sym.flags:
  3280. genSingleVar(p, sym, n, astdef(sym))
  3281. if sym.loc.snippet == "" or sym.loc.t == nil:
  3282. #echo "FAILED FOR PRCO ", p.prc.name.s
  3283. #echo renderTree(p.prc.ast, {renderIds})
  3284. internalError p.config, n.info, "expr: var not init " & sym.name.s & "_" & $sym.id
  3285. if sfThread in sym.flags:
  3286. accessThreadLocalVar(p, sym)
  3287. if emulatedThreadVars(p.config):
  3288. putIntoDest(p, d, sym.loc.lode, derefField("NimTV_", sym.loc.snippet))
  3289. else:
  3290. putLocIntoDest(p, d, sym.loc)
  3291. else:
  3292. putLocIntoDest(p, d, sym.loc)
  3293. of skTemp:
  3294. when false:
  3295. # this is more harmful than helpful.
  3296. if sym.loc.snippet == "":
  3297. # we now support undeclared 'skTemp' variables for easier
  3298. # transformations in other parts of the compiler:
  3299. assignLocalVar(p, n)
  3300. if sym.loc.snippet == "" or sym.loc.t == nil:
  3301. #echo "FAILED FOR PRCO ", p.prc.name.s
  3302. #echo renderTree(p.prc.ast, {renderIds})
  3303. internalError(p.config, n.info, "expr: temp not init " & sym.name.s & "_" & $sym.id)
  3304. putLocIntoDest(p, d, sym.loc)
  3305. of skParam:
  3306. if sym.loc.snippet == "" or sym.loc.t == nil:
  3307. # echo "FAILED FOR PRCO ", p.prc.name.s
  3308. # debug p.prc.typ.n
  3309. # echo renderTree(p.prc.ast, {renderIds})
  3310. internalError(p.config, n.info, "expr: param not init " & sym.name.s & "_" & $sym.id)
  3311. putLocIntoDest(p, d, sym.loc)
  3312. else: internalError(p.config, n.info, "expr(" & $sym.kind & "); unknown symbol")
  3313. of nkNilLit:
  3314. if not isEmptyType(n.typ):
  3315. var lit = newBuilder("")
  3316. genLiteral(p, n, lit)
  3317. putIntoDest(p, d, n, extract(lit))
  3318. of nkStrLit..nkTripleStrLit:
  3319. var lit = newBuilder("")
  3320. genLiteral(p, n, lit)
  3321. putDataIntoDest(p, d, n, extract(lit))
  3322. of nkIntLit..nkUInt64Lit, nkFloatLit..nkFloat128Lit, nkCharLit:
  3323. var lit = newBuilder("")
  3324. genLiteral(p, n, lit)
  3325. putIntoDest(p, d, n, extract(lit))
  3326. of nkCall, nkHiddenCallConv, nkInfix, nkPrefix, nkPostfix, nkCommand,
  3327. nkCallStrLit:
  3328. genLineDir(p, n) # may be redundant, it is generated in fixupCall as well
  3329. let op = n[0]
  3330. if n.typ.isNil:
  3331. # discard the value:
  3332. var a: TLoc = default(TLoc)
  3333. if op.kind == nkSym and op.sym.magic != mNone:
  3334. genMagicExpr(p, n, a, op.sym.magic)
  3335. else:
  3336. genCall(p, n, a)
  3337. else:
  3338. # load it into 'd':
  3339. if op.kind == nkSym and op.sym.magic != mNone:
  3340. genMagicExpr(p, n, d, op.sym.magic)
  3341. else:
  3342. genCall(p, n, d)
  3343. of nkCurly:
  3344. if isDeepConstExpr(n) and n.len != 0:
  3345. var lit = newBuilder("")
  3346. genSetNode(p, n, lit)
  3347. putIntoDest(p, d, n, extract(lit))
  3348. else:
  3349. genSetConstr(p, n, d)
  3350. of nkBracket:
  3351. if isDeepConstExpr(n) and n.len != 0:
  3352. exprComplexConst(p, n, d)
  3353. elif skipTypes(n.typ, abstractVarRange).kind == tySequence:
  3354. genSeqConstr(p, n, d)
  3355. else:
  3356. genArrayConstr(p, n, d)
  3357. of nkPar, nkTupleConstr:
  3358. if n.typ != nil and n.typ.kind == tyProc and n.len == 2:
  3359. genClosure(p, n, d)
  3360. elif isDeepConstExpr(n) and n.len != 0:
  3361. exprComplexConst(p, n, d)
  3362. else:
  3363. genTupleConstr(p, n, d)
  3364. of nkObjConstr: genObjConstr(p, n, d)
  3365. of nkCast: genCast(p, n, d)
  3366. of nkHiddenStdConv, nkHiddenSubConv, nkConv: genConv(p, n, d)
  3367. of nkAddr, nkHiddenAddr: genAddr(p, n, d)
  3368. of nkBracketExpr: genBracketExpr(p, n, d)
  3369. of nkDerefExpr, nkHiddenDeref: genDeref(p, n, d)
  3370. of nkDotExpr: genRecordField(p, n, d)
  3371. of nkCheckedFieldExpr: genCheckedRecordField(p, n, d)
  3372. of nkBlockExpr, nkBlockStmt: genBlock(p, n, d)
  3373. of nkStmtListExpr: genStmtListExpr(p, n, d)
  3374. of nkStmtList: genStmtList(p, n)
  3375. of nkIfExpr, nkIfStmt: genIf(p, n, d)
  3376. of nkWhen:
  3377. # This should be a "when nimvm" node.
  3378. expr(p, n[1][0], d)
  3379. of nkObjDownConv: downConv(p, n, d)
  3380. of nkObjUpConv: upConv(p, n, d)
  3381. of nkChckRangeF, nkChckRange64, nkChckRange: genRangeChck(p, n, d)
  3382. of nkStringToCString: convStrToCStr(p, n, d)
  3383. of nkCStringToString: convCStrToStr(p, n, d)
  3384. of nkLambdaKinds:
  3385. var sym = n[namePos].sym
  3386. genProc(p.module, sym)
  3387. if sym.loc.snippet == "" or sym.loc.lode == nil:
  3388. internalError(p.config, n.info, "expr: proc not init " & sym.name.s)
  3389. putLocIntoDest(p, d, sym.loc)
  3390. of nkClosure: genClosure(p, n, d)
  3391. of nkEmpty: discard
  3392. of nkWhileStmt: genWhileStmt(p, n)
  3393. of nkVarSection, nkLetSection: genVarStmt(p, n)
  3394. of nkConstSection:
  3395. if useAliveDataFromDce in p.module.flags:
  3396. genConstStmt(p, n)
  3397. # else: consts generated lazily on use
  3398. of nkForStmt: internalError(p.config, n.info, "for statement not eliminated")
  3399. of nkCaseStmt: genCase(p, n, d)
  3400. of nkReturnStmt: genReturnStmt(p, n)
  3401. of nkBreakStmt: genBreakStmt(p, n)
  3402. of nkAsgn:
  3403. cow(p, n[1])
  3404. if nfPreventCg notin n.flags:
  3405. genAsgn(p, n, fastAsgn=false)
  3406. of nkFastAsgn, nkSinkAsgn:
  3407. cow(p, n[1])
  3408. if nfPreventCg notin n.flags:
  3409. # transf is overly aggressive with 'nkFastAsgn', so we work around here.
  3410. # See tests/run/tcnstseq3 for an example that would fail otherwise.
  3411. genAsgn(p, n, fastAsgn=p.prc != nil)
  3412. of nkDiscardStmt:
  3413. let ex = n[0]
  3414. if ex.kind != nkEmpty:
  3415. genLineDir(p, n)
  3416. var a: TLoc = initLocExprSingleUse(p, ex)
  3417. p.s(cpsStmts).addDiscard(a.snippet)
  3418. of nkAsmStmt: genAsmStmt(p, n)
  3419. of nkTryStmt, nkHiddenTryStmt:
  3420. case p.config.exc
  3421. of excGoto:
  3422. genTryGoto(p, n, d)
  3423. of excCpp:
  3424. genTryCpp(p, n, d)
  3425. else:
  3426. genTrySetjmp(p, n, d)
  3427. of nkRaiseStmt: genRaiseStmt(p, n)
  3428. of nkTypeSection:
  3429. # we have to emit the type information for object types here to support
  3430. # separate compilation:
  3431. genTypeSection(p.module, n)
  3432. of nkCommentStmt, nkIteratorDef, nkIncludeStmt,
  3433. nkImportStmt, nkImportExceptStmt, nkExportStmt, nkExportExceptStmt,
  3434. nkFromStmt, nkTemplateDef, nkMacroDef, nkStaticStmt:
  3435. discard
  3436. of nkPragma: genPragma(p, n)
  3437. of nkPragmaBlock:
  3438. var inUncheckedAssignSection = 0
  3439. let pragmaList = n[0]
  3440. for pi in pragmaList:
  3441. if whichPragma(pi) == wCast:
  3442. case whichPragma(pi[1])
  3443. of wUncheckedAssign:
  3444. inUncheckedAssignSection = 1
  3445. else:
  3446. discard
  3447. inc p.inUncheckedAssignSection, inUncheckedAssignSection
  3448. expr(p, n.lastSon, d)
  3449. dec p.inUncheckedAssignSection, inUncheckedAssignSection
  3450. of nkProcDef, nkFuncDef, nkMethodDef, nkConverterDef:
  3451. if n[genericParamsPos].kind == nkEmpty:
  3452. var prc = n[namePos].sym
  3453. if useAliveDataFromDce in p.module.flags:
  3454. if p.module.alive.contains(prc.itemId.item) and
  3455. prc.magic in generatedMagics:
  3456. genProc(p.module, prc)
  3457. elif prc.skipGenericOwner.kind == skModule and sfCompileTime notin prc.flags:
  3458. if ({sfExportc, sfCompilerProc} * prc.flags == {sfExportc}) or
  3459. (sfExportc in prc.flags and lfExportLib in prc.loc.flags) or
  3460. (prc.kind == skMethod):
  3461. # due to a bug/limitation in the lambda lifting, unused inner procs
  3462. # are not transformed correctly. We work around this issue (#411) here
  3463. # by ensuring it's no inner proc (owner is a module).
  3464. # Generate proc even if empty body, bugfix #11651.
  3465. genProc(p.module, prc)
  3466. of nkParForStmt: genParForStmt(p, n)
  3467. of nkState: genState(p, n)
  3468. of nkGotoState:
  3469. # simply never set it back to 0 here from here on...
  3470. inc p.splitDecls
  3471. genGotoState(p, n)
  3472. of nkBreakState: genBreakState(p, n, d)
  3473. of nkMixinStmt, nkBindStmt: discard
  3474. else: internalError(p.config, n.info, "expr(" & $n.kind & "); unknown node kind")
  3475. proc getDefaultValue(p: BProc; typ: PType; info: TLineInfo; result: var Builder) =
  3476. var t = skipTypes(typ, abstractRange+{tyOwned}-{tyTypeDesc})
  3477. case t.kind
  3478. of tyBool: result.add NimFalse
  3479. of tyEnum, tyChar, tyInt..tyInt64, tyUInt..tyUInt64: result.addIntValue(0)
  3480. of tyFloat..tyFloat128: result.addFloatValue(0.0)
  3481. of tyCstring, tyVar, tyLent, tyPointer, tyPtr, tyUntyped,
  3482. tyTyped, tyTypeDesc, tyStatic, tyRef, tyNil:
  3483. result.add NimNil
  3484. of tyString, tySequence:
  3485. if optSeqDestructors in p.config.globalOptions:
  3486. var seqInit: StructInitializer
  3487. result.addStructInitializer(seqInit, kind = siOrderedStruct):
  3488. result.addField(seqInit, name = "len"):
  3489. result.addIntValue(0)
  3490. result.addField(seqInit, name = "p"):
  3491. result.add(NimNil)
  3492. else:
  3493. result.add NimNil
  3494. of tyProc:
  3495. if t.callConv != ccClosure:
  3496. result.add NimNil
  3497. else:
  3498. var closureInit: StructInitializer
  3499. result.addStructInitializer(closureInit, kind = siOrderedStruct):
  3500. result.addField(closureInit, name = "ClP_0"):
  3501. result.add(NimNil)
  3502. result.addField(closureInit, name = "ClE_0"):
  3503. result.add(NimNil)
  3504. of tyObject:
  3505. var objInit: StructInitializer
  3506. result.addStructInitializer(objInit, kind = siOrderedStruct):
  3507. getNullValueAuxT(p, t, t, t.n, nil, result, objInit, true, info)
  3508. of tyTuple:
  3509. var tupleInit: StructInitializer
  3510. result.addStructInitializer(tupleInit, kind = siOrderedStruct):
  3511. if p.vccAndC and t.isEmptyTupleType:
  3512. result.addField(tupleInit, name = "dummy"):
  3513. result.addIntValue(0)
  3514. for i, a in t.ikids:
  3515. result.addField(tupleInit, name = "Field" & $i):
  3516. getDefaultValue(p, a, info, result)
  3517. of tyArray:
  3518. var arrInit: StructInitializer
  3519. result.addStructInitializer(arrInit, kind = siArray):
  3520. for i in 0..<toInt(lengthOrd(p.config, t.indexType)):
  3521. result.addField(arrInit, name = ""):
  3522. getDefaultValue(p, t.elementType, info, result)
  3523. #result = rope"{}"
  3524. of tyOpenArray, tyVarargs:
  3525. var openArrInit: StructInitializer
  3526. result.addStructInitializer(openArrInit, kind = siOrderedStruct):
  3527. result.addField(openArrInit, name = "Field0"):
  3528. result.add(NimNil)
  3529. result.addField(openArrInit, name = "Field1"):
  3530. result.addIntValue(0)
  3531. of tySet:
  3532. if mapSetType(p.config, t) == ctArray:
  3533. var setInit: StructInitializer
  3534. result.addStructInitializer(setInit, kind = siArray):
  3535. discard
  3536. else: result.addIntValue(0)
  3537. else:
  3538. globalError(p.config, info, "cannot create null element for: " & $t.kind)
  3539. proc isEmptyCaseObjectBranch(n: PNode): bool =
  3540. for it in n:
  3541. if it.kind == nkSym and not isEmptyType(it.sym.typ): return false
  3542. return true
  3543. proc getNullValueAux(p: BProc; t: PType; obj, constOrNil: PNode,
  3544. result: var Builder; init: var StructInitializer;
  3545. isConst: bool, info: TLineInfo) =
  3546. case obj.kind
  3547. of nkRecList:
  3548. let isUnion = tfUnion in t.flags
  3549. for it in obj.sons:
  3550. getNullValueAux(p, t, it, constOrNil, result, init, isConst, info)
  3551. if isUnion:
  3552. # generate only 1 field for default value of union
  3553. return
  3554. of nkRecCase:
  3555. getNullValueAux(p, t, obj[0], constOrNil, result, init, isConst, info)
  3556. var branch = Zero
  3557. if constOrNil != nil:
  3558. ## find kind value, default is zero if not specified
  3559. for i in 1..<constOrNil.len:
  3560. if constOrNil[i].kind == nkExprColonExpr:
  3561. if constOrNil[i][0].sym.name.id == obj[0].sym.name.id:
  3562. branch = getOrdValue(constOrNil[i][1])
  3563. break
  3564. elif i == obj[0].sym.position:
  3565. branch = getOrdValue(constOrNil[i])
  3566. break
  3567. let selectedBranch = caseObjDefaultBranch(obj, branch)
  3568. let b = lastSon(obj[selectedBranch])
  3569. # designated initilization is the only way to init non first element of unions
  3570. # branches are allowed to have no members (b.len == 0), in this case they don't need initializer
  3571. var fieldName: string = ""
  3572. if b.kind == nkRecList and not isEmptyCaseObjectBranch(b):
  3573. fieldName = "_" & mangleRecFieldName(p.module, obj[0].sym) & "_" & $selectedBranch
  3574. result.addField(init, name = "<anonymous union>"):
  3575. # XXX figure out name for the union, see use of `addAnonUnion`
  3576. var branchInit: StructInitializer
  3577. result.addStructInitializer(branchInit, kind = siNamedStruct):
  3578. result.addField(branchInit, name = fieldName):
  3579. var branchObjInit: StructInitializer
  3580. result.addStructInitializer(branchObjInit, kind = siOrderedStruct):
  3581. getNullValueAux(p, t, b, constOrNil, result, branchObjInit, isConst, info)
  3582. elif b.kind == nkSym:
  3583. fieldName = mangleRecFieldName(p.module, b.sym)
  3584. result.addField(init, name = "<anonymous union>"):
  3585. # XXX figure out name for the union, see use of `addAnonUnion`
  3586. var branchInit: StructInitializer
  3587. result.addStructInitializer(branchInit, kind = siNamedStruct):
  3588. result.addField(branchInit, name = fieldName):
  3589. # we need to generate the default value of the single sym,
  3590. # to do this create a dummy wrapper initializer and recurse
  3591. var branchFieldInit: StructInitializer
  3592. result.addStructInitializer(branchFieldInit, kind = siWrapper):
  3593. getNullValueAux(p, t, b, constOrNil, result, branchFieldInit, isConst, info)
  3594. else:
  3595. # no fields, don't initialize
  3596. return
  3597. of nkSym:
  3598. let field = obj.sym
  3599. let sname = mangleRecFieldName(p.module, field)
  3600. result.addField(init, name = sname):
  3601. block fieldInit:
  3602. if constOrNil != nil:
  3603. for i in 1..<constOrNil.len:
  3604. if constOrNil[i].kind == nkExprColonExpr:
  3605. assert constOrNil[i][0].kind == nkSym, "illformed object constr; the field is not a sym"
  3606. if constOrNil[i][0].sym.name.id == field.name.id:
  3607. genBracedInit(p, constOrNil[i][1], isConst, field.typ, result)
  3608. break fieldInit
  3609. elif i == field.position:
  3610. genBracedInit(p, constOrNil[i], isConst, field.typ, result)
  3611. break fieldInit
  3612. # not found, produce default value:
  3613. getDefaultValue(p, field.typ, info, result)
  3614. else:
  3615. localError(p.config, info, "cannot create null element for: " & $obj)
  3616. proc getNullValueAuxT(p: BProc; orig, t: PType; obj, constOrNil: PNode,
  3617. result: var Builder; init: var StructInitializer;
  3618. isConst: bool, info: TLineInfo) =
  3619. var base = t.baseClass
  3620. when false:
  3621. let oldRes = result
  3622. let oldcount = count
  3623. if base != nil:
  3624. base = skipTypes(base, skipPtrs)
  3625. result.addField(init, name = "Sup"):
  3626. var baseInit: StructInitializer
  3627. result.addStructInitializer(baseInit, kind = siOrderedStruct):
  3628. getNullValueAuxT(p, orig, base, base.n, constOrNil, result, baseInit, isConst, info)
  3629. elif not isObjLackingTypeField(t):
  3630. result.addField(init, name = "m_type"):
  3631. if optTinyRtti in p.config.globalOptions:
  3632. result.add genTypeInfoV2(p.module, orig, obj.info)
  3633. else:
  3634. result.add genTypeInfoV1(p.module, orig, obj.info)
  3635. getNullValueAux(p, t, obj, constOrNil, result, init, isConst, info)
  3636. when false: # referring to Sup field, hopefully not a problem
  3637. # do not emit '{}' as that is not valid C:
  3638. if oldcount == count: result = oldRes
  3639. proc genConstObjConstr(p: BProc; n: PNode; isConst: bool; result: var Builder) =
  3640. let t = n.typ.skipTypes(abstractInstOwned)
  3641. #if not isObjLackingTypeField(t) and not p.module.compileToCpp:
  3642. # result.addf("{$1}", [genTypeInfo(p.module, t)])
  3643. # inc count
  3644. var objInit: StructInitializer
  3645. result.addStructInitializer(objInit, kind = siOrderedStruct):
  3646. if t.kind == tyObject:
  3647. getNullValueAuxT(p, t, t, t.n, n, result, objInit, isConst, n.info)
  3648. proc genConstSimpleList(p: BProc, n: PNode; isConst: bool; result: var Builder) =
  3649. var arrInit: StructInitializer
  3650. result.addStructInitializer(arrInit, kind = siArray):
  3651. if p.vccAndC and n.len == 0 and n.typ.kind == tyArray:
  3652. result.addField(arrInit, name = ""):
  3653. getDefaultValue(p, n.typ.elementType, n.info, result)
  3654. for i in 0..<n.len:
  3655. let it = n[i]
  3656. var ind, val: PNode
  3657. if it.kind == nkExprColonExpr:
  3658. ind = it[0]
  3659. val = it[1]
  3660. else:
  3661. ind = it
  3662. val = it
  3663. result.addField(arrInit, name = ""):
  3664. genBracedInit(p, val, isConst, ind.typ, result)
  3665. proc genConstTuple(p: BProc, n: PNode; isConst: bool; tup: PType; result: var Builder) =
  3666. var tupleInit: StructInitializer
  3667. result.addStructInitializer(tupleInit, kind = siOrderedStruct):
  3668. if p.vccAndC and n.len == 0:
  3669. result.addField(tupleInit, name = "dummy"):
  3670. result.addIntValue(0)
  3671. for i in 0..<n.len:
  3672. var it = n[i]
  3673. if it.kind == nkExprColonExpr:
  3674. it = it[1]
  3675. result.addField(tupleInit, name = "Field" & $i):
  3676. genBracedInit(p, it, isConst, tup[i], result)
  3677. proc genConstSeq(p: BProc, n: PNode, t: PType; isConst: bool; result: var Builder) =
  3678. let base = t.skipTypes(abstractInst)[0]
  3679. let tmpName = getTempName(p.module)
  3680. # genBracedInit can modify cfsStrData, we need an intermediate builder:
  3681. var def = newBuilder("")
  3682. def.addVarWithTypeAndInitializer(
  3683. if isConst: Const else: Global,
  3684. name = tmpName):
  3685. def.addSimpleStruct(p.module, name = "", baseType = ""):
  3686. def.addField(name = "sup", typ = cgsymValue(p.module, "TGenericSeq"))
  3687. def.addArrayField(name = "data", elementType = getTypeDesc(p.module, base), len = n.len)
  3688. do:
  3689. var structInit: StructInitializer
  3690. def.addStructInitializer(structInit, kind = siOrderedStruct):
  3691. def.addField(structInit, name = "sup"):
  3692. var supInit: StructInitializer
  3693. def.addStructInitializer(supInit, kind = siOrderedStruct):
  3694. def.addField(supInit, name = "len"):
  3695. def.addIntValue(n.len)
  3696. def.addField(supInit, name = "reserved"):
  3697. def.add(cOp(BitOr, NimInt, cIntValue(n.len), NimStrlitFlag))
  3698. if n.len > 0:
  3699. def.addField(structInit, name = "data"):
  3700. var arrInit: StructInitializer
  3701. def.addStructInitializer(arrInit, kind = siArray):
  3702. for i in 0..<n.len:
  3703. def.addField(arrInit, name = ""):
  3704. genBracedInit(p, n[i], isConst, base, def)
  3705. p.module.s[cfsStrData].add extract(def)
  3706. result.add cCast(typ = getTypeDesc(p.module, t), value = cAddr(tmpName))
  3707. proc genConstSeqV2(p: BProc, n: PNode, t: PType; isConst: bool; result: var Builder) =
  3708. let base = t.skipTypes(abstractInst)[0]
  3709. let payload = getTempName(p.module)
  3710. # genBracedInit can modify cfsStrData, we need an intermediate builder:
  3711. var def = newBuilder("")
  3712. def.addVarWithTypeAndInitializer(
  3713. if isConst: AlwaysConst else: Global,
  3714. name = payload):
  3715. def.addSimpleStruct(p.module, name = "", baseType = ""):
  3716. def.addField(name = "cap", typ = NimInt)
  3717. def.addArrayField(name = "data", elementType = getTypeDesc(p.module, base), len = n.len)
  3718. do:
  3719. var structInit: StructInitializer
  3720. def.addStructInitializer(structInit, kind = siOrderedStruct):
  3721. def.addField(structInit, name = "cap"):
  3722. def.add(cOp(BitOr, NimInt, cIntValue(n.len), NimStrlitFlag))
  3723. if n.len > 0:
  3724. def.addField(structInit, name = "data"):
  3725. var arrInit: StructInitializer
  3726. def.addStructInitializer(arrInit, kind = siArray):
  3727. for i in 0..<n.len:
  3728. def.addField(arrInit, name = ""):
  3729. genBracedInit(p, n[i], isConst, base, def)
  3730. p.module.s[cfsStrData].add extract(def)
  3731. var resultInit: StructInitializer
  3732. result.addStructInitializer(resultInit, kind = siOrderedStruct):
  3733. result.addField(resultInit, name = "len"):
  3734. result.addIntValue(n.len)
  3735. result.addField(resultInit, name = "p"):
  3736. result.add cCast(typ = ptrType(getSeqPayloadType(p.module, t)), value = cAddr(payload))
  3737. proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; result: var Builder) =
  3738. case n.kind
  3739. of nkHiddenStdConv, nkHiddenSubConv:
  3740. genBracedInit(p, n[1], isConst, n.typ, result)
  3741. else:
  3742. var ty = tyNone
  3743. var typ: PType = nil
  3744. if optionalType == nil:
  3745. if n.kind in nkStrKinds:
  3746. ty = tyString
  3747. else:
  3748. internalError(p.config, n.info, "node has no type")
  3749. else:
  3750. typ = skipTypes(optionalType, abstractInstOwned + {tyStatic})
  3751. ty = typ.kind
  3752. case ty
  3753. of tySet:
  3754. let cs = toBitSet(p.config, n)
  3755. genRawSetData(cs, int(getSize(p.config, n.typ)), result)
  3756. of tySequence:
  3757. if optSeqDestructors in p.config.globalOptions:
  3758. genConstSeqV2(p, n, typ, isConst, result)
  3759. else:
  3760. genConstSeq(p, n, typ, isConst, result)
  3761. of tyProc:
  3762. if typ.callConv == ccClosure and n.safeLen > 1 and n[1].kind == nkNilLit:
  3763. # n.kind could be: nkClosure, nkTupleConstr and maybe others; `n.safeLen`
  3764. # guards against the case of `nkSym`, refs bug #14340.
  3765. # Conversion: nimcall -> closure.
  3766. # this hack fixes issue that nkNilLit is expanded to {NIM_NIL,NIM_NIL}
  3767. # this behaviour is needed since closure_var = nil must be
  3768. # expanded to {NIM_NIL,NIM_NIL}
  3769. # in VM closures are initialized with nkPar(nkNilLit, nkNilLit)
  3770. # leading to duplicate code like this:
  3771. # "{NIM_NIL,NIM_NIL}, {NIM_NIL,NIM_NIL}"
  3772. var closureInit: StructInitializer
  3773. result.addStructInitializer(closureInit, kind = siOrderedStruct):
  3774. result.addField(closureInit, name = "ClP_0"):
  3775. if n[0].kind == nkNilLit:
  3776. result.add(NimNil)
  3777. else:
  3778. var d: TLoc = initLocExpr(p, n[0])
  3779. result.add(cCast(typ = getClosureType(p.module, typ, clHalfWithEnv), value = rdLoc(d)))
  3780. result.addField(closureInit, name = "ClE_0"):
  3781. result.add(NimNil)
  3782. else:
  3783. var d: TLoc = initLocExpr(p, n)
  3784. result.add rdLoc(d)
  3785. of tyArray, tyVarargs:
  3786. genConstSimpleList(p, n, isConst, result)
  3787. of tyTuple:
  3788. genConstTuple(p, n, isConst, typ, result)
  3789. of tyOpenArray:
  3790. if n.kind != nkBracket:
  3791. internalError(p.config, n.info, "const openArray expression is not an array construction")
  3792. let payload = getTempName(p.module)
  3793. let ctype = getTypeDesc(p.module, typ.elementType)
  3794. let arrLen = n.len
  3795. # genConstSimpleList can modify cfsStrData, we need an intermediate builder:
  3796. var data = newBuilder("")
  3797. data.addArrayVarWithInitializer(
  3798. kind = if isConst: AlwaysConst else: Global,
  3799. name = payload, elementType = ctype, len = arrLen):
  3800. genConstSimpleList(p, n, isConst, data)
  3801. p.module.s[cfsStrData].add(extract(data))
  3802. var openArrInit: StructInitializer
  3803. result.addStructInitializer(openArrInit, kind = siOrderedStruct):
  3804. result.addField(openArrInit, name = "Field0"):
  3805. result.add(cCast(typ = ptrType(ctype), value = cAddr(payload)))
  3806. result.addField(openArrInit, name = "Field1"):
  3807. result.addIntValue(arrLen)
  3808. of tyObject:
  3809. genConstObjConstr(p, n, isConst, result)
  3810. of tyString, tyCstring:
  3811. if optSeqDestructors in p.config.globalOptions and n.kind != nkNilLit and ty == tyString:
  3812. genStringLiteralV2Const(p.module, n, isConst, result)
  3813. else:
  3814. var d: TLoc = initLocExpr(p, n)
  3815. result.add rdLoc(d)
  3816. else:
  3817. var d: TLoc = initLocExpr(p, n)
  3818. result.add rdLoc(d)