ccgstmts.nim 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2015 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. const
  11. RangeExpandLimit = 256 # do not generate ranges
  12. # over 'RangeExpandLimit' elements
  13. stringCaseThreshold = 8
  14. # above X strings a hash-switch for strings is generated
  15. proc registerTraverseProc(p: BProc, v: PSym) =
  16. var traverseProc = ""
  17. if p.config.selectedGC in {gcMarkAndSweep, gcHooks, gcRefc} and
  18. optOwnedRefs notin p.config.globalOptions and
  19. containsGarbageCollectedRef(v.loc.t):
  20. # we register a specialized marked proc here; this has the advantage
  21. # that it works out of the box for thread local storage then :-)
  22. traverseProc = genTraverseProcForGlobal(p.module, v, v.info)
  23. if traverseProc.len != 0 and not p.hcrOn:
  24. if sfThread in v.flags:
  25. appcg(p.module, p.module.preInitProc.procSec(cpsInit),
  26. "$n\t#nimRegisterThreadLocalMarker($1);$n$n", [traverseProc])
  27. else:
  28. appcg(p.module, p.module.preInitProc.procSec(cpsInit),
  29. "$n\t#nimRegisterGlobalMarker($1);$n$n", [traverseProc])
  30. proc isAssignedImmediately(conf: ConfigRef; n: PNode): bool {.inline.} =
  31. if n.kind == nkEmpty:
  32. result = false
  33. elif n.kind in nkCallKinds and n[0] != nil and n[0].typ != nil and n[0].typ.skipTypes(abstractInst).kind == tyProc:
  34. if n[0].kind == nkSym and sfConstructor in n[0].sym.flags:
  35. result = true
  36. elif isInvalidReturnType(conf, n[0].typ, true):
  37. # var v = f()
  38. # is transformed into: var v; f(addr v)
  39. # where 'f' **does not** initialize the result!
  40. result = false
  41. else:
  42. result = true
  43. elif isInvalidReturnType(conf, n.typ, false):
  44. result = false
  45. else:
  46. result = true
  47. proc inExceptBlockLen(p: BProc): int =
  48. result = 0
  49. for x in p.nestedTryStmts:
  50. if x.inExcept: result.inc
  51. proc startBlockInternal(p: BProc): int {.discardable.} =
  52. inc(p.labels)
  53. result = p.blocks.len
  54. p.blocks.add initBlock()
  55. p.blocks[result].id = p.labels
  56. p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16
  57. p.blocks[result].nestedExceptStmts = p.inExceptBlockLen.int16
  58. template startBlock(p: BProc, start: FormatStr = "{$n",
  59. args: varargs[Rope]): int =
  60. lineCg(p, cpsStmts, start, args)
  61. startBlockInternal(p)
  62. proc endBlock(p: BProc)
  63. proc genVarTuple(p: BProc, n: PNode) =
  64. if n.kind != nkVarTuple: internalError(p.config, n.info, "genVarTuple")
  65. # if we have a something that's been captured, use the lowering instead:
  66. for i in 0..<n.len-2:
  67. if n[i].kind != nkSym:
  68. genStmts(p, lowerTupleUnpacking(p.module.g.graph, n, p.module.idgen, p.prc))
  69. return
  70. # check only the first son
  71. var forHcr = treatGlobalDifferentlyForHCR(p.module, n[0].sym)
  72. let hcrCond = if forHcr: getTempName(p.module) else: ""
  73. var hcrGlobals: seq[tuple[loc: TLoc, tp: Rope]] = @[]
  74. # determine if the tuple is constructed at top-level scope or inside of a block (if/while/block)
  75. let isGlobalInBlock = forHcr and p.blocks.len > 2
  76. # do not close and reopen blocks if this is a 'global' but inside of a block (if/while/block)
  77. forHcr = forHcr and not isGlobalInBlock
  78. if forHcr:
  79. # check with the boolean if the initializing code for the tuple should be ran
  80. lineCg(p, cpsStmts, "if ($1)$n", [hcrCond])
  81. startBlock(p)
  82. genLineDir(p, n)
  83. var tup = initLocExpr(p, n[^1])
  84. var t = tup.t.skipTypes(abstractInst)
  85. for i in 0..<n.len-2:
  86. let vn = n[i]
  87. let v = vn.sym
  88. if sfCompileTime in v.flags: continue
  89. if sfGlobal in v.flags:
  90. assignGlobalVar(p, vn, "")
  91. genObjectInit(p, cpsInit, v.typ, v.loc, constructObj)
  92. registerTraverseProc(p, v)
  93. else:
  94. assignLocalVar(p, vn)
  95. initLocalVar(p, v, immediateAsgn=isAssignedImmediately(p.config, n[^1]))
  96. var field = initLoc(locExpr, vn, tup.storage)
  97. if t.kind == tyTuple:
  98. field.r = "$1.Field$2" % [rdLoc(tup), rope(i)]
  99. else:
  100. if t.n[i].kind != nkSym: internalError(p.config, n.info, "genVarTuple")
  101. field.r = "$1.$2" % [rdLoc(tup), mangleRecFieldName(p.module, t.n[i].sym)]
  102. putLocIntoDest(p, v.loc, field)
  103. if forHcr or isGlobalInBlock:
  104. hcrGlobals.add((loc: v.loc, tp: "NULL"))
  105. if forHcr:
  106. # end the block where the tuple gets initialized
  107. endBlock(p)
  108. if forHcr or isGlobalInBlock:
  109. # insert the registration of the globals for the different parts of the tuple at the
  110. # start of the current scope (after they have been iterated) and init a boolean to
  111. # check if any of them is newly introduced and the initializing code has to be ran
  112. lineCg(p, cpsLocals, "NIM_BOOL $1 = NIM_FALSE;$n", [hcrCond])
  113. for curr in hcrGlobals:
  114. lineCg(p, cpsLocals, "$1 |= hcrRegisterGlobal($4, \"$2\", sizeof($3), $5, (void**)&$2);$N",
  115. [hcrCond, curr.loc.r, rdLoc(curr.loc), getModuleDllPath(p.module, n[0].sym), curr.tp])
  116. proc loadInto(p: BProc, le, ri: PNode, a: var TLoc) {.inline.} =
  117. if ri.kind in nkCallKinds and (ri[0].kind != nkSym or
  118. ri[0].sym.magic == mNone):
  119. genAsgnCall(p, le, ri, a)
  120. else:
  121. # this is a hacky way to fix #1181 (tmissingderef)::
  122. #
  123. # var arr1 = cast[ptr array[4, int8]](addr foo)[]
  124. #
  125. # However, fixing this properly really requires modelling 'array' as
  126. # a 'struct' in C to preserve dereferencing semantics completely. Not
  127. # worth the effort until version 1.0 is out.
  128. a.flags.incl(lfEnforceDeref)
  129. expr(p, ri, a)
  130. proc assignLabel(b: var TBlock; result: var Rope) {.inline.} =
  131. b.label = "LA" & b.id.rope
  132. result.add b.label
  133. proc blockBody(b: var TBlock; result: var Rope) =
  134. result.add b.sections[cpsLocals]
  135. if b.frameLen > 0:
  136. result.addf("FR_.len+=$1;$n", [b.frameLen.rope])
  137. result.add(b.sections[cpsInit])
  138. result.add(b.sections[cpsStmts])
  139. proc endBlock(p: BProc, blockEnd: Rope) =
  140. let topBlock = p.blocks.len-1
  141. # the block is merged into the parent block
  142. p.blocks[topBlock].blockBody(p.blocks[topBlock-1].sections[cpsStmts])
  143. setLen(p.blocks, topBlock)
  144. # this is done after the block is popped so $n is
  145. # properly indented when pretty printing is enabled
  146. line(p, cpsStmts, blockEnd)
  147. proc endBlock(p: BProc) =
  148. let topBlock = p.blocks.len - 1
  149. let frameLen = p.blocks[topBlock].frameLen
  150. var blockEnd: Rope = ""
  151. if frameLen > 0:
  152. blockEnd.addf("FR_.len-=$1;$n", [frameLen.rope])
  153. if p.blocks[topBlock].label.len != 0:
  154. blockEnd.addf("} $1: ;$n", [p.blocks[topBlock].label])
  155. else:
  156. blockEnd.addf("}$n", [])
  157. endBlock(p, blockEnd)
  158. proc genSimpleBlock(p: BProc, stmts: PNode) {.inline.} =
  159. startBlock(p)
  160. genStmts(p, stmts)
  161. endBlock(p)
  162. proc exprBlock(p: BProc, n: PNode, d: var TLoc) =
  163. startBlock(p)
  164. expr(p, n, d)
  165. endBlock(p)
  166. template preserveBreakIdx(body: untyped): untyped =
  167. var oldBreakIdx = p.breakIdx
  168. body
  169. p.breakIdx = oldBreakIdx
  170. proc genState(p: BProc, n: PNode) =
  171. internalAssert p.config, n.len == 1
  172. let n0 = n[0]
  173. if n0.kind == nkIntLit:
  174. let idx = n[0].intVal
  175. linefmt(p, cpsStmts, "STATE$1: ;$n", [idx])
  176. elif n0.kind == nkStrLit:
  177. linefmt(p, cpsStmts, "$1: ;$n", [n0.strVal])
  178. proc blockLeaveActions(p: BProc, howManyTrys, howManyExcepts: int) =
  179. # Called by return and break stmts.
  180. # Deals with issues faced when jumping out of try/except/finally stmts.
  181. var stack = newSeq[tuple[fin: PNode, inExcept: bool, label: Natural]](0)
  182. inc p.withinBlockLeaveActions
  183. for i in 1..howManyTrys:
  184. let tryStmt = p.nestedTryStmts.pop
  185. if p.config.exc == excSetjmp:
  186. # Pop safe points generated by try
  187. if not tryStmt.inExcept:
  188. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  189. # Pop this try-stmt of the list of nested trys
  190. # so we don't infinite recurse on it in the next step.
  191. stack.add(tryStmt)
  192. # Find finally-stmt for this try-stmt
  193. # and generate a copy of its sons
  194. var finallyStmt = tryStmt.fin
  195. if finallyStmt != nil:
  196. genStmts(p, finallyStmt[0])
  197. dec p.withinBlockLeaveActions
  198. # push old elements again:
  199. for i in countdown(howManyTrys-1, 0):
  200. p.nestedTryStmts.add(stack[i])
  201. # Pop exceptions that was handled by the
  202. # except-blocks we are in
  203. if noSafePoints notin p.flags:
  204. for i in countdown(howManyExcepts-1, 0):
  205. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  206. proc genGotoState(p: BProc, n: PNode) =
  207. # we resist the temptation to translate it into duff's device as it later
  208. # will be translated into computed gotos anyway for GCC at least:
  209. # switch (x.state) {
  210. # case 0: goto STATE0;
  211. # ...
  212. var a: TLoc = initLocExpr(p, n[0])
  213. lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)])
  214. p.flags.incl beforeRetNeeded
  215. lineF(p, cpsStmts, "case -1:$n", [])
  216. blockLeaveActions(p,
  217. howManyTrys = p.nestedTryStmts.len,
  218. howManyExcepts = p.inExceptBlockLen)
  219. lineF(p, cpsStmts, " goto BeforeRet_;$n", [])
  220. var statesCounter = lastOrd(p.config, n[0].typ)
  221. if n.len >= 2 and n[1].kind == nkIntLit:
  222. statesCounter = getInt(n[1])
  223. let prefix = if n.len == 3 and n[2].kind == nkStrLit: n[2].strVal.rope
  224. else: rope"STATE"
  225. for i in 0i64..toInt64(statesCounter):
  226. lineF(p, cpsStmts, "case $2: goto $1$2;$n", [prefix, rope(i)])
  227. lineF(p, cpsStmts, "}$n", [])
  228. proc genBreakState(p: BProc, n: PNode, d: var TLoc) =
  229. var a: TLoc
  230. d = initLoc(locExpr, n, OnUnknown)
  231. if n[0].kind == nkClosure:
  232. a = initLocExpr(p, n[0][1])
  233. d.r = "(((NI*) $1)[1] < 0)" % [rdLoc(a)]
  234. else:
  235. a = initLocExpr(p, n[0])
  236. # the environment is guaranteed to contain the 'state' field at offset 1:
  237. d.r = "((((NI*) $1.ClE_0)[1]) < 0)" % [rdLoc(a)]
  238. proc genGotoVar(p: BProc; value: PNode) =
  239. if value.kind notin {nkCharLit..nkUInt64Lit}:
  240. localError(p.config, value.info, "'goto' target must be a literal value")
  241. else:
  242. lineF(p, cpsStmts, "goto NIMSTATE_$#;$n", [value.intVal.rope])
  243. proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; result: var Rope)
  244. proc potentialValueInit(p: BProc; v: PSym; value: PNode; result: var Rope) =
  245. if lfDynamicLib in v.loc.flags or sfThread in v.flags or p.hcrOn:
  246. discard "nothing to do"
  247. elif sfGlobal in v.flags and value != nil and isDeepConstExpr(value, p.module.compileToCpp) and
  248. p.withinLoop == 0 and not containsGarbageCollectedRef(v.typ):
  249. #echo "New code produced for ", v.name.s, " ", p.config $ value.info
  250. genBracedInit(p, value, isConst = false, v.typ, result)
  251. proc genCppParamsForCtor(p: BProc; call: PNode; didGenTemp: var bool): string =
  252. result = ""
  253. var argsCounter = 0
  254. let typ = skipTypes(call[0].typ, abstractInst)
  255. assert(typ.kind == tyProc)
  256. for i in 1..<call.len:
  257. #if it's a type we can just generate here another initializer as we are in an initializer context
  258. if call[i].kind == nkCall and call[i][0].kind == nkSym and call[i][0].sym.kind == skType:
  259. if argsCounter > 0: result.add ","
  260. result.add genCppInitializer(p.module, p, call[i][0].sym.typ, didGenTemp)
  261. else:
  262. #We need to test for temp in globals, see: #23657
  263. let param =
  264. if typ[i].kind in {tyVar} and call[i].kind == nkHiddenAddr:
  265. call[i][0]
  266. else:
  267. call[i]
  268. if param.kind != nkBracketExpr or param.typ.kind in
  269. {tyRef, tyPtr, tyUncheckedArray, tyArray, tyOpenArray,
  270. tyVarargs, tySequence, tyString, tyCstring, tyTuple}:
  271. let tempLoc = initLocExprSingleUse(p, param)
  272. didGenTemp = didGenTemp or tempLoc.k == locTemp
  273. genOtherArg(p, call, i, typ, result, argsCounter)
  274. proc genCppVarForCtor(p: BProc; call: PNode; decl: var Rope, didGenTemp: var bool) =
  275. let params = genCppParamsForCtor(p, call, didGenTemp)
  276. if params.len == 0:
  277. decl = runtimeFormat("$#;\n", [decl])
  278. else:
  279. decl = runtimeFormat("$#($#);\n", [decl, params])
  280. proc genSingleVar(p: BProc, v: PSym; vn, value: PNode) =
  281. if sfGoto in v.flags:
  282. # translate 'var state {.goto.} = X' into 'goto LX':
  283. genGotoVar(p, value)
  284. return
  285. let imm = isAssignedImmediately(p.config, value)
  286. let isCppCtorCall = p.module.compileToCpp and imm and
  287. value.kind in nkCallKinds and value[0].kind == nkSym and
  288. v.typ.kind != tyPtr and sfConstructor in value[0].sym.flags
  289. var targetProc = p
  290. var valueAsRope = ""
  291. potentialValueInit(p, v, value, valueAsRope)
  292. if sfGlobal in v.flags:
  293. if v.flags * {sfImportc, sfExportc} == {sfImportc} and
  294. value.kind == nkEmpty and
  295. v.loc.flags * {lfHeader, lfNoDecl} != {}:
  296. return
  297. if sfPure in v.flags:
  298. # v.owner.kind != skModule:
  299. targetProc = p.module.preInitProc
  300. if isCppCtorCall and not containsHiddenPointer(v.typ):
  301. var didGenTemp = false
  302. callGlobalVarCppCtor(targetProc, v, vn, value, didGenTemp)
  303. if didGenTemp:
  304. message(p.config, vn.info, warnGlobalVarConstructorTemporary, vn.sym.name.s)
  305. #We fail to call the constructor in the global scope so we do the call inside the main proc
  306. assignGlobalVar(targetProc, vn, valueAsRope)
  307. var loc = initLocExprSingleUse(targetProc, value)
  308. genAssignment(targetProc, v.loc, loc, {})
  309. else:
  310. assignGlobalVar(targetProc, vn, valueAsRope)
  311. # XXX: be careful here.
  312. # Global variables should not be zeromem-ed within loops
  313. # (see bug #20).
  314. # That's why we are doing the construction inside the preInitProc.
  315. # genObjectInit relies on the C runtime's guarantees that
  316. # global variables will be initialized to zero.
  317. if valueAsRope.len == 0:
  318. var loc = v.loc
  319. # When the native TLS is unavailable, a global thread-local variable needs
  320. # one more layer of indirection in order to access the TLS block.
  321. # Only do this for complex types that may need a call to `objectInit`
  322. if sfThread in v.flags and emulatedThreadVars(p.config) and
  323. isComplexValueType(v.typ):
  324. loc = initLocExprSingleUse(p.module.preInitProc, vn)
  325. genObjectInit(p.module.preInitProc, cpsInit, v.typ, loc, constructObj)
  326. # Alternative construction using default constructor (which may zeromem):
  327. # if sfImportc notin v.flags: constructLoc(p.module.preInitProc, v.loc)
  328. if sfExportc in v.flags and p.module.g.generatedHeader != nil:
  329. genVarPrototype(p.module.g.generatedHeader, vn)
  330. registerTraverseProc(p, v)
  331. else:
  332. if imm and p.module.compileToCpp and p.splitDecls == 0 and
  333. not containsHiddenPointer(v.typ) and
  334. nimErrorFlagAccessed notin p.flags:
  335. # C++ really doesn't like things like 'Foo f; f = x' as that invokes a
  336. # parameterless constructor followed by an assignment operator. So we
  337. # generate better code here: 'Foo f = x;'
  338. genLineDir(p, vn)
  339. var decl = localVarDecl(p, vn)
  340. var tmp: TLoc
  341. if isCppCtorCall:
  342. var didGenTemp = false
  343. genCppVarForCtor(p, value, decl, didGenTemp)
  344. line(p, cpsStmts, decl)
  345. else:
  346. tmp = initLocExprSingleUse(p, value)
  347. if value.kind == nkEmpty:
  348. lineF(p, cpsStmts, "$#;\n", [decl])
  349. else:
  350. lineF(p, cpsStmts, "$# = $#;\n", [decl, tmp.rdLoc])
  351. return
  352. assignLocalVar(p, vn)
  353. initLocalVar(p, v, imm)
  354. let traverseProc = "NULL"
  355. # If the var is in a block (control flow like if/while or a block) in global scope just
  356. # register the so called "global" so it can be used later on. There is no need to close
  357. # and reopen of if (nim_hcr_do_init_) blocks because we are in one already anyway.
  358. var forHcr = treatGlobalDifferentlyForHCR(p.module, v)
  359. if forHcr and targetProc.blocks.len > 3 and v.owner.kind == skModule:
  360. # put it in the locals section - mainly because of loops which
  361. # use the var in a call to resetLoc() in the statements section
  362. lineCg(targetProc, cpsLocals, "hcrRegisterGlobal($3, \"$1\", sizeof($2), $4, (void**)&$1);$n",
  363. [v.loc.r, rdLoc(v.loc), getModuleDllPath(p.module, v), traverseProc])
  364. # nothing special left to do later on - let's avoid closing and reopening blocks
  365. forHcr = false
  366. # we close and reopen the global if (nim_hcr_do_init_) blocks in the main Init function
  367. # for the module so we can have globals and top-level code be interleaved and still
  368. # be able to re-run it but without the top level code - just the init of globals
  369. if forHcr:
  370. lineCg(targetProc, cpsStmts, "if (hcrRegisterGlobal($3, \"$1\", sizeof($2), $4, (void**)&$1))$N",
  371. [v.loc.r, rdLoc(v.loc), getModuleDllPath(p.module, v), traverseProc])
  372. startBlock(targetProc)
  373. if value.kind != nkEmpty and valueAsRope.len == 0:
  374. genLineDir(targetProc, vn)
  375. if not isCppCtorCall:
  376. loadInto(targetProc, vn, value, v.loc)
  377. if forHcr:
  378. endBlock(targetProc)
  379. proc genSingleVar(p: BProc, a: PNode) =
  380. let v = a[0].sym
  381. if sfCompileTime in v.flags:
  382. # fix issue #12640
  383. # {.global, compileTime.} pragma in proc
  384. if sfGlobal in v.flags and p.prc != nil and p.prc.kind == skProc:
  385. discard
  386. else:
  387. return
  388. genSingleVar(p, v, a[0], a[2])
  389. proc genClosureVar(p: BProc, a: PNode) =
  390. var immediateAsgn = a[2].kind != nkEmpty
  391. var v: TLoc = initLocExpr(p, a[0])
  392. genLineDir(p, a)
  393. if immediateAsgn:
  394. loadInto(p, a[0], a[2], v)
  395. elif sfNoInit notin a[0][1].sym.flags:
  396. constructLoc(p, v)
  397. proc genVarStmt(p: BProc, n: PNode) =
  398. for it in n.sons:
  399. if it.kind == nkCommentStmt: continue
  400. if it.kind == nkIdentDefs:
  401. # can be a lifted var nowadays ...
  402. if it[0].kind == nkSym:
  403. genSingleVar(p, it)
  404. else:
  405. genClosureVar(p, it)
  406. else:
  407. genVarTuple(p, it)
  408. proc genIf(p: BProc, n: PNode, d: var TLoc) =
  409. #
  410. # { if (!expr1) goto L1;
  411. # thenPart }
  412. # goto LEnd
  413. # L1:
  414. # { if (!expr2) goto L2;
  415. # thenPart2 }
  416. # goto LEnd
  417. # L2:
  418. # { elsePart }
  419. # Lend:
  420. var
  421. a: TLoc
  422. lelse: TLabel
  423. if not isEmptyType(n.typ) and d.k == locNone:
  424. d = getTemp(p, n.typ)
  425. genLineDir(p, n)
  426. let lend = getLabel(p)
  427. for it in n.sons:
  428. # bug #4230: avoid false sharing between branches:
  429. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  430. if it.len == 2:
  431. startBlock(p)
  432. a = initLocExprSingleUse(p, it[0])
  433. lelse = getLabel(p)
  434. inc(p.labels)
  435. lineF(p, cpsStmts, "if (!$1) goto $2;$n",
  436. [rdLoc(a), lelse])
  437. if p.module.compileToCpp:
  438. # avoid "jump to label crosses initialization" error:
  439. p.s(cpsStmts).add "{"
  440. expr(p, it[1], d)
  441. p.s(cpsStmts).add "}"
  442. else:
  443. expr(p, it[1], d)
  444. endBlock(p)
  445. if n.len > 1:
  446. lineF(p, cpsStmts, "goto $1;$n", [lend])
  447. fixLabel(p, lelse)
  448. elif it.len == 1:
  449. startBlock(p)
  450. expr(p, it[0], d)
  451. endBlock(p)
  452. else: internalError(p.config, n.info, "genIf()")
  453. if n.len > 1: fixLabel(p, lend)
  454. proc genReturnStmt(p: BProc, t: PNode) =
  455. if nfPreventCg in t.flags: return
  456. p.flags.incl beforeRetNeeded
  457. genLineDir(p, t)
  458. if (t[0].kind != nkEmpty): genStmts(p, t[0])
  459. blockLeaveActions(p,
  460. howManyTrys = p.nestedTryStmts.len,
  461. howManyExcepts = p.inExceptBlockLen)
  462. if (p.finallySafePoints.len > 0) and noSafePoints notin p.flags:
  463. # If we're in a finally block, and we came here by exception
  464. # consume it before we return.
  465. var safePoint = p.finallySafePoints[^1]
  466. linefmt(p, cpsStmts, "if ($1.status != 0) #popCurrentException();$n", [safePoint])
  467. lineF(p, cpsStmts, "goto BeforeRet_;$n", [])
  468. proc genGotoForCase(p: BProc; caseStmt: PNode) =
  469. for i in 1..<caseStmt.len:
  470. startBlock(p)
  471. let it = caseStmt[i]
  472. for j in 0..<it.len-1:
  473. if it[j].kind == nkRange:
  474. localError(p.config, it.info, "range notation not available for computed goto")
  475. return
  476. let val = getOrdValue(it[j])
  477. lineF(p, cpsStmts, "NIMSTATE_$#:$n", [val.rope])
  478. genStmts(p, it.lastSon)
  479. endBlock(p)
  480. iterator fieldValuePairs(n: PNode): tuple[memberSym, valueSym: PNode] =
  481. assert(n.kind in {nkLetSection, nkVarSection})
  482. for identDefs in n:
  483. if identDefs.kind == nkIdentDefs:
  484. let valueSym = identDefs[^1]
  485. for i in 0..<identDefs.len-2:
  486. let memberSym = identDefs[i]
  487. yield((memberSym: memberSym, valueSym: valueSym))
  488. proc genComputedGoto(p: BProc; n: PNode) =
  489. # first pass: Generate array of computed labels:
  490. # flatten the loop body because otherwise let and var sections
  491. # wrapped inside stmt lists by inject destructors won't be recognised
  492. let n = n.flattenStmts()
  493. var casePos = -1
  494. var arraySize: int = 0
  495. for i in 0..<n.len:
  496. let it = n[i]
  497. if it.kind == nkCaseStmt:
  498. if lastSon(it).kind != nkOfBranch:
  499. localError(p.config, it.info,
  500. "case statement must be exhaustive for computed goto"); return
  501. casePos = i
  502. if enumHasHoles(it[0].typ):
  503. localError(p.config, it.info,
  504. "case statement cannot work on enums with holes for computed goto"); return
  505. let aSize = lengthOrd(p.config, it[0].typ)
  506. if aSize > 10_000:
  507. localError(p.config, it.info,
  508. "case statement has too many cases for computed goto"); return
  509. arraySize = toInt(aSize)
  510. if firstOrd(p.config, it[0].typ) != 0:
  511. localError(p.config, it.info,
  512. "case statement has to start at 0 for computed goto"); return
  513. if casePos < 0:
  514. localError(p.config, n.info, "no case statement found for computed goto"); return
  515. var id = p.labels+1
  516. inc p.labels, arraySize+1
  517. let tmp = "TMP$1_" % [id.rope]
  518. var gotoArray = "static void* $#[$#] = {" % [tmp, arraySize.rope]
  519. for i in 1..arraySize-1:
  520. gotoArray.addf("&&TMP$#_, ", [rope(id+i)])
  521. gotoArray.addf("&&TMP$#_};$n", [rope(id+arraySize)])
  522. line(p, cpsLocals, gotoArray)
  523. for j in 0..<casePos:
  524. genStmts(p, n[j])
  525. let caseStmt = n[casePos]
  526. var a: TLoc = initLocExpr(p, caseStmt[0])
  527. # first goto:
  528. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  529. for i in 1..<caseStmt.len:
  530. startBlock(p)
  531. let it = caseStmt[i]
  532. for j in 0..<it.len-1:
  533. if it[j].kind == nkRange:
  534. localError(p.config, it.info, "range notation not available for computed goto")
  535. return
  536. let val = getOrdValue(it[j])
  537. var lit = newRopeAppender()
  538. intLiteral(toInt64(val)+id+1, lit)
  539. lineF(p, cpsStmts, "TMP$#_:$n", [lit])
  540. genStmts(p, it.lastSon)
  541. for j in casePos+1..<n.len:
  542. genStmts(p, n[j])
  543. for j in 0..<casePos:
  544. # prevent new local declarations
  545. # compile declarations as assignments
  546. let it = n[j]
  547. if it.kind in {nkLetSection, nkVarSection}:
  548. let asgn = copyNode(it)
  549. asgn.transitionSonsKind(nkAsgn)
  550. asgn.sons.setLen 2
  551. for sym, value in it.fieldValuePairs:
  552. if value.kind != nkEmpty:
  553. asgn[0] = sym
  554. asgn[1] = value
  555. genStmts(p, asgn)
  556. else:
  557. genStmts(p, it)
  558. var a: TLoc = initLocExpr(p, caseStmt[0])
  559. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  560. endBlock(p)
  561. for j in casePos+1..<n.len:
  562. genStmts(p, n[j])
  563. proc genWhileStmt(p: BProc, t: PNode) =
  564. # we don't generate labels here as for example GCC would produce
  565. # significantly worse code
  566. var
  567. a: TLoc
  568. assert(t.len == 2)
  569. inc(p.withinLoop)
  570. genLineDir(p, t)
  571. preserveBreakIdx:
  572. var loopBody = t[1]
  573. if loopBody.stmtsContainPragma(wComputedGoto) and
  574. hasComputedGoto in CC[p.config.cCompiler].props:
  575. # for closure support weird loop bodies are generated:
  576. if loopBody.len == 2 and loopBody[0].kind == nkEmpty:
  577. loopBody = loopBody[1]
  578. genComputedGoto(p, loopBody)
  579. else:
  580. p.breakIdx = startBlock(p, "while (1) {$n")
  581. p.blocks[p.breakIdx].isLoop = true
  582. a = initLocExpr(p, t[0])
  583. if (t[0].kind != nkIntLit) or (t[0].intVal == 0):
  584. lineF(p, cpsStmts, "if (!$1) goto ", [rdLoc(a)])
  585. assignLabel(p.blocks[p.breakIdx], p.s(cpsStmts))
  586. appcg(p, cpsStmts, ";$n", [])
  587. genStmts(p, loopBody)
  588. if optProfiler in p.options:
  589. # invoke at loop body exit:
  590. linefmt(p, cpsStmts, "#nimProfile();$n", [])
  591. endBlock(p)
  592. dec(p.withinLoop)
  593. proc genBlock(p: BProc, n: PNode, d: var TLoc) =
  594. if not isEmptyType(n.typ):
  595. # bug #4505: allocate the temp in the outer scope
  596. # so that it can escape the generated {}:
  597. if d.k == locNone:
  598. d = getTemp(p, n.typ)
  599. d.flags.incl(lfEnforceDeref)
  600. preserveBreakIdx:
  601. p.breakIdx = startBlock(p)
  602. if n[0].kind != nkEmpty:
  603. # named block?
  604. assert(n[0].kind == nkSym)
  605. var sym = n[0].sym
  606. sym.loc.k = locOther
  607. sym.position = p.breakIdx+1
  608. expr(p, n[1], d)
  609. endBlock(p)
  610. proc genParForStmt(p: BProc, t: PNode) =
  611. assert(t.len == 3)
  612. inc(p.withinLoop)
  613. genLineDir(p, t)
  614. preserveBreakIdx:
  615. let forLoopVar = t[0].sym
  616. assignLocalVar(p, t[0])
  617. #initLoc(forLoopVar.loc, locLocalVar, forLoopVar.typ, onStack)
  618. #discard mangleName(forLoopVar)
  619. let call = t[1]
  620. assert(call.len == 4 or call.len == 5)
  621. var rangeA = initLocExpr(p, call[1])
  622. var rangeB = initLocExpr(p, call[2])
  623. # $n at the beginning because of #9710
  624. if call.len == 4: # procName(a, b, annotation)
  625. if call[0].sym.name.s == "||": # `||`(a, b, annotation)
  626. lineF(p, cpsStmts, "$n#pragma omp $4$n" &
  627. "for ($1 = $2; $1 <= $3; ++$1)",
  628. [forLoopVar.loc.rdLoc,
  629. rangeA.rdLoc, rangeB.rdLoc,
  630. call[3].getStr.rope])
  631. else:
  632. lineF(p, cpsStmts, "$n#pragma $4$n" &
  633. "for ($1 = $2; $1 <= $3; ++$1)",
  634. [forLoopVar.loc.rdLoc,
  635. rangeA.rdLoc, rangeB.rdLoc,
  636. call[3].getStr.rope])
  637. else: # `||`(a, b, step, annotation)
  638. var step: TLoc = initLocExpr(p, call[3])
  639. lineF(p, cpsStmts, "$n#pragma omp $5$n" &
  640. "for ($1 = $2; $1 <= $3; $1 += $4)",
  641. [forLoopVar.loc.rdLoc,
  642. rangeA.rdLoc, rangeB.rdLoc, step.rdLoc,
  643. call[4].getStr.rope])
  644. p.breakIdx = startBlock(p)
  645. p.blocks[p.breakIdx].isLoop = true
  646. genStmts(p, t[2])
  647. endBlock(p)
  648. dec(p.withinLoop)
  649. proc genBreakStmt(p: BProc, t: PNode) =
  650. var idx = p.breakIdx
  651. if t[0].kind != nkEmpty:
  652. # named break?
  653. assert(t[0].kind == nkSym)
  654. var sym = t[0].sym
  655. doAssert(sym.loc.k == locOther)
  656. idx = sym.position-1
  657. else:
  658. # an unnamed 'break' can only break a loop after 'transf' pass:
  659. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  660. if idx < 0 or not p.blocks[idx].isLoop:
  661. internalError(p.config, t.info, "no loop to break")
  662. p.blocks[idx].label = "LA" & p.blocks[idx].id.rope
  663. blockLeaveActions(p,
  664. p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts,
  665. p.inExceptBlockLen - p.blocks[idx].nestedExceptStmts)
  666. genLineDir(p, t)
  667. lineF(p, cpsStmts, "goto $1;$n", [p.blocks[idx].label])
  668. proc raiseExit(p: BProc) =
  669. assert p.config.exc == excGoto
  670. if nimErrorFlagDisabled notin p.flags:
  671. p.flags.incl nimErrorFlagAccessed
  672. if p.nestedTryStmts.len == 0:
  673. p.flags.incl beforeRetNeeded
  674. # easy case, simply goto 'ret':
  675. lineCg(p, cpsStmts, "if (NIM_UNLIKELY(*nimErr_)) goto BeforeRet_;$n", [])
  676. else:
  677. lineCg(p, cpsStmts, "if (NIM_UNLIKELY(*nimErr_)) goto LA$1_;$n",
  678. [p.nestedTryStmts[^1].label])
  679. proc finallyActions(p: BProc) =
  680. if p.config.exc != excGoto and p.nestedTryStmts.len > 0 and p.nestedTryStmts[^1].inExcept:
  681. # if the current try stmt have a finally block,
  682. # we must execute it before reraising
  683. let finallyBlock = p.nestedTryStmts[^1].fin
  684. if finallyBlock != nil:
  685. genSimpleBlock(p, finallyBlock[0])
  686. proc raiseInstr(p: BProc; result: var Rope) =
  687. if p.config.exc == excGoto:
  688. let L = p.nestedTryStmts.len
  689. if L == 0:
  690. p.flags.incl beforeRetNeeded
  691. # easy case, simply goto 'ret':
  692. result.add ropecg(p.module, "goto BeforeRet_;$n", [])
  693. else:
  694. # raise inside an 'except' must go to the finally block,
  695. # raise outside an 'except' block must go to the 'except' list.
  696. result.add ropecg(p.module, "goto LA$1_;$n",
  697. [p.nestedTryStmts[L-1].label])
  698. # + ord(p.nestedTryStmts[L-1].inExcept)])
  699. proc genRaiseStmt(p: BProc, t: PNode) =
  700. if t[0].kind != nkEmpty:
  701. var a: TLoc = initLocExprSingleUse(p, t[0])
  702. finallyActions(p)
  703. var e = rdLoc(a)
  704. discard getTypeDesc(p.module, t[0].typ)
  705. var typ = skipTypes(t[0].typ, abstractPtrs)
  706. # XXX For reasons that currently escape me, this is only required by the new
  707. # C++ based exception handling:
  708. if p.config.exc == excCpp:
  709. blockLeaveActions(p, howManyTrys = 0, howManyExcepts = p.inExceptBlockLen)
  710. genLineDir(p, t)
  711. if isImportedException(typ, p.config):
  712. lineF(p, cpsStmts, "throw $1;$n", [e])
  713. else:
  714. lineCg(p, cpsStmts, "#raiseExceptionEx((#Exception*)$1, $2, $3, $4, $5);$n",
  715. [e, makeCString(typ.sym.name.s),
  716. makeCString(if p.prc != nil: p.prc.name.s else: p.module.module.name.s),
  717. quotedFilename(p.config, t.info), toLinenumber(t.info)])
  718. if optOwnedRefs in p.config.globalOptions:
  719. lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [e])
  720. else:
  721. finallyActions(p)
  722. genLineDir(p, t)
  723. linefmt(p, cpsStmts, "#reraiseException();$n", [])
  724. raiseInstr(p, p.s(cpsStmts))
  725. template genCaseGenericBranch(p: BProc, b: PNode, e: TLoc,
  726. rangeFormat, eqFormat: FormatStr, labl: TLabel) =
  727. var x, y: TLoc
  728. for i in 0..<b.len - 1:
  729. if b[i].kind == nkRange:
  730. x = initLocExpr(p, b[i][0])
  731. y = initLocExpr(p, b[i][1])
  732. lineCg(p, cpsStmts, rangeFormat,
  733. [rdCharLoc(e), rdCharLoc(x), rdCharLoc(y), labl])
  734. else:
  735. x = initLocExpr(p, b[i])
  736. lineCg(p, cpsStmts, eqFormat, [rdCharLoc(e), rdCharLoc(x), labl])
  737. proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc,
  738. labId, until: int): TLabel =
  739. var lend = getLabel(p)
  740. for i in 1..until:
  741. # bug #4230: avoid false sharing between branches:
  742. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  743. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(labId + i)])
  744. if t[i].kind == nkOfBranch:
  745. exprBlock(p, t[i][^1], d)
  746. lineF(p, cpsStmts, "goto $1;$n", [lend])
  747. else:
  748. exprBlock(p, t[i][0], d)
  749. result = lend
  750. template genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc,
  751. rangeFormat, eqFormat: FormatStr,
  752. until: int, a: TLoc): TLabel =
  753. # generate a C-if statement for a Nim case statement
  754. var res: TLabel
  755. var labId = p.labels
  756. for i in 1..until:
  757. inc(p.labels)
  758. if t[i].kind == nkOfBranch: # else statement
  759. genCaseGenericBranch(p, t[i], a, rangeFormat, eqFormat,
  760. "LA" & rope(p.labels) & "_")
  761. else:
  762. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  763. if until < t.len-1:
  764. inc(p.labels)
  765. var gotoTarget = p.labels
  766. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(gotoTarget)])
  767. res = genCaseSecondPass(p, t, d, labId, until)
  768. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(gotoTarget)])
  769. else:
  770. res = genCaseSecondPass(p, t, d, labId, until)
  771. res
  772. template genCaseGeneric(p: BProc, t: PNode, d: var TLoc,
  773. rangeFormat, eqFormat: FormatStr) =
  774. var a: TLoc = initLocExpr(p, t[0])
  775. var lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, t.len-1, a)
  776. fixLabel(p, lend)
  777. proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel,
  778. stringKind: TTypeKind,
  779. branches: var openArray[Rope]) =
  780. var x: TLoc
  781. for i in 0..<b.len - 1:
  782. assert(b[i].kind != nkRange)
  783. x = initLocExpr(p, b[i])
  784. var j: int = 0
  785. case b[i].kind
  786. of nkStrLit..nkTripleStrLit:
  787. j = int(hashString(p.config, b[i].strVal) and high(branches))
  788. of nkNilLit: j = 0
  789. else:
  790. assert false, "invalid string case branch node kind"
  791. if stringKind == tyCstring:
  792. appcg(p.module, branches[j], "if (#eqCstrings($1, $2)) goto $3;$n",
  793. [rdLoc(e), rdLoc(x), labl])
  794. else:
  795. appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
  796. [rdLoc(e), rdLoc(x), labl])
  797. proc genStringCase(p: BProc, t: PNode, stringKind: TTypeKind, d: var TLoc) =
  798. # count how many constant strings there are in the case:
  799. var strings = 0
  800. for i in 1..<t.len:
  801. if t[i].kind == nkOfBranch: inc(strings, t[i].len - 1)
  802. if strings > stringCaseThreshold:
  803. var bitMask = math.nextPowerOfTwo(strings) - 1
  804. var branches: seq[Rope]
  805. newSeq(branches, bitMask + 1)
  806. var a: TLoc = initLocExpr(p, t[0]) # first pass: generate ifs+goto:
  807. var labId = p.labels
  808. for i in 1..<t.len:
  809. inc(p.labels)
  810. if t[i].kind == nkOfBranch:
  811. genCaseStringBranch(p, t[i], a, "LA" & rope(p.labels) & "_",
  812. stringKind, branches)
  813. else:
  814. # else statement: nothing to do yet
  815. # but we reserved a label, which we use later
  816. discard
  817. if stringKind == tyCstring:
  818. linefmt(p, cpsStmts, "switch (#hashCstring($1) & $2) {$n",
  819. [rdLoc(a), bitMask])
  820. else:
  821. linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
  822. [rdLoc(a), bitMask])
  823. for j in 0..high(branches):
  824. if branches[j] != "":
  825. var lit = newRopeAppender()
  826. intLiteral(j, lit)
  827. lineF(p, cpsStmts, "case $1: $n$2break;$n",
  828. [lit, branches[j]])
  829. lineF(p, cpsStmts, "}$n", []) # else statement:
  830. if t[^1].kind != nkOfBranch:
  831. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  832. # third pass: generate statements
  833. var lend = genCaseSecondPass(p, t, d, labId, t.len-1)
  834. fixLabel(p, lend)
  835. else:
  836. if stringKind == tyCstring:
  837. genCaseGeneric(p, t, d, "", "if (#eqCstrings($1, $2)) goto $3;$n")
  838. else:
  839. genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
  840. proc branchHasTooBigRange(b: PNode): bool =
  841. result = false
  842. for it in b:
  843. # last son is block
  844. if (it.kind == nkRange) and
  845. it[1].intVal - it[0].intVal > RangeExpandLimit:
  846. return true
  847. proc ifSwitchSplitPoint(p: BProc, n: PNode): int =
  848. result = 0
  849. for i in 1..<n.len:
  850. var branch = n[i]
  851. var stmtBlock = lastSon(branch)
  852. if stmtBlock.stmtsContainPragma(wLinearScanEnd):
  853. result = i
  854. elif hasSwitchRange notin CC[p.config.cCompiler].props:
  855. if branch.kind == nkOfBranch and branchHasTooBigRange(branch):
  856. result = i
  857. proc genCaseRange(p: BProc, branch: PNode) =
  858. for j in 0..<branch.len-1:
  859. if branch[j].kind == nkRange:
  860. if hasSwitchRange in CC[p.config.cCompiler].props:
  861. var litA = newRopeAppender()
  862. var litB = newRopeAppender()
  863. genLiteral(p, branch[j][0], litA)
  864. genLiteral(p, branch[j][1], litB)
  865. lineF(p, cpsStmts, "case $1 ... $2:$n", [litA, litB])
  866. else:
  867. var v = copyNode(branch[j][0])
  868. while v.intVal <= branch[j][1].intVal:
  869. var litA = newRopeAppender()
  870. genLiteral(p, v, litA)
  871. lineF(p, cpsStmts, "case $1:$n", [litA])
  872. inc(v.intVal)
  873. else:
  874. var litA = newRopeAppender()
  875. genLiteral(p, branch[j], litA)
  876. lineF(p, cpsStmts, "case $1:$n", [litA])
  877. proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
  878. # analyse 'case' statement:
  879. var splitPoint = ifSwitchSplitPoint(p, n)
  880. # generate if part (might be empty):
  881. var a: TLoc = initLocExpr(p, n[0])
  882. var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d,
  883. rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  884. eqFormat = "if ($1 == $2) goto $3;$n",
  885. splitPoint, a) else: ""
  886. # generate switch part (might be empty):
  887. if splitPoint+1 < n.len:
  888. lineF(p, cpsStmts, "switch ($1) {$n", [rdCharLoc(a)])
  889. var hasDefault = false
  890. for i in splitPoint+1..<n.len:
  891. # bug #4230: avoid false sharing between branches:
  892. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  893. var branch = n[i]
  894. if branch.kind == nkOfBranch:
  895. genCaseRange(p, branch)
  896. else:
  897. # else part of case statement:
  898. lineF(p, cpsStmts, "default:$n", [])
  899. hasDefault = true
  900. exprBlock(p, branch.lastSon, d)
  901. lineF(p, cpsStmts, "break;$n", [])
  902. if not hasDefault:
  903. if hasBuiltinUnreachable in CC[p.config.cCompiler].props:
  904. lineF(p, cpsStmts, "default: __builtin_unreachable();$n", [])
  905. elif hasAssume in CC[p.config.cCompiler].props:
  906. lineF(p, cpsStmts, "default: __assume(0);$n", [])
  907. lineF(p, cpsStmts, "}$n", [])
  908. if lend != "": fixLabel(p, lend)
  909. proc genCase(p: BProc, t: PNode, d: var TLoc) =
  910. genLineDir(p, t)
  911. if not isEmptyType(t.typ) and d.k == locNone:
  912. d = getTemp(p, t.typ)
  913. case skipTypes(t[0].typ, abstractVarRange).kind
  914. of tyString:
  915. genStringCase(p, t, tyString, d)
  916. of tyCstring:
  917. genStringCase(p, t, tyCstring, d)
  918. of tyFloat..tyFloat128:
  919. genCaseGeneric(p, t, d, "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  920. "if ($1 == $2) goto $3;$n")
  921. else:
  922. if t[0].kind == nkSym and sfGoto in t[0].sym.flags:
  923. genGotoForCase(p, t)
  924. else:
  925. genOrdinalCase(p, t, d)
  926. proc genRestoreFrameAfterException(p: BProc) =
  927. if optStackTrace in p.module.config.options:
  928. if hasCurFramePointer notin p.flags:
  929. p.flags.incl hasCurFramePointer
  930. p.procSec(cpsLocals).add(ropecg(p.module, "\tTFrame* _nimCurFrame;$n", []))
  931. p.procSec(cpsInit).add(ropecg(p.module, "\t_nimCurFrame = #getFrame();$n", []))
  932. linefmt(p, cpsStmts, "#setFrame(_nimCurFrame);$n", [])
  933. proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
  934. #[ code to generate:
  935. std::exception_ptr error;
  936. try {
  937. body;
  938. } catch (Exception e) {
  939. error = std::current_exception();
  940. if (ofExpr(e, TypeHere)) {
  941. error = nullptr; // handled
  942. } else if (...) {
  943. } else {
  944. throw;
  945. }
  946. } catch(...) {
  947. // C++ exception occured, not under Nim's control.
  948. }
  949. {
  950. /* finally: */
  951. printf('fin!\n');
  952. if (error) std::rethrow_exception(error); // re-raise the exception
  953. }
  954. ]#
  955. p.module.includeHeader("<exception>")
  956. if not isEmptyType(t.typ) and d.k == locNone:
  957. d = getTemp(p, t.typ)
  958. genLineDir(p, t)
  959. inc(p.labels, 2)
  960. let etmp = p.labels
  961. #init on locals, fixes #23306
  962. lineCg(p, cpsLocals, "std::exception_ptr T$1_;$n", [etmp])
  963. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  964. p.nestedTryStmts.add((fin, false, 0.Natural))
  965. if t.kind == nkHiddenTryStmt:
  966. lineCg(p, cpsStmts, "try {$n", [])
  967. expr(p, t[0], d)
  968. lineCg(p, cpsStmts, "}$n", [])
  969. else:
  970. startBlock(p, "try {$n")
  971. expr(p, t[0], d)
  972. endBlock(p)
  973. # First pass: handle Nim based exceptions:
  974. lineCg(p, cpsStmts, "catch (#Exception* T$1_) {$n", [etmp+1])
  975. genRestoreFrameAfterException(p)
  976. # an unhandled exception happened!
  977. lineCg(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  978. p.nestedTryStmts[^1].inExcept = true
  979. var hasImportedCppExceptions = false
  980. var i = 1
  981. var hasIf = false
  982. var hasElse = false
  983. while (i < t.len) and (t[i].kind == nkExceptBranch):
  984. # bug #4230: avoid false sharing between branches:
  985. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  986. if t[i].len == 1:
  987. hasImportedCppExceptions = true
  988. # general except section:
  989. hasElse = true
  990. if hasIf: lineF(p, cpsStmts, "else ", [])
  991. startBlock(p)
  992. # we handled the error:
  993. expr(p, t[i][0], d)
  994. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  995. endBlock(p)
  996. else:
  997. var orExpr = newRopeAppender()
  998. var exvar = PNode(nil)
  999. for j in 0..<t[i].len - 1:
  1000. var typeNode = t[i][j]
  1001. if t[i][j].isInfixAs():
  1002. typeNode = t[i][j][1]
  1003. exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1004. assert(typeNode.kind == nkType)
  1005. if isImportedException(typeNode.typ, p.config):
  1006. hasImportedCppExceptions = true
  1007. else:
  1008. if orExpr.len != 0: orExpr.add("||")
  1009. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1010. if optTinyRtti in p.config.globalOptions:
  1011. let checkFor = $getObjDepth(typeNode.typ)
  1012. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(typeNode.typ, p.config)))])
  1013. else:
  1014. let checkFor = genTypeInfoV1(p.module, typeNode.typ, typeNode.info)
  1015. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1016. if orExpr.len != 0:
  1017. if hasIf:
  1018. startBlock(p, "else if ($1) {$n", [orExpr])
  1019. else:
  1020. startBlock(p, "if ($1) {$n", [orExpr])
  1021. hasIf = true
  1022. if exvar != nil:
  1023. fillLocalName(p, exvar.sym)
  1024. fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
  1025. linefmt(p, cpsStmts, "$1 $2 = T$3_;$n", [getTypeDesc(p.module, exvar.sym.typ),
  1026. rdLoc(exvar.sym.loc), rope(etmp+1)])
  1027. # we handled the error:
  1028. linefmt(p, cpsStmts, "T$1_ = nullptr;$n", [etmp])
  1029. expr(p, t[i][^1], d)
  1030. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1031. endBlock(p)
  1032. inc(i)
  1033. if hasIf and not hasElse:
  1034. linefmt(p, cpsStmts, "else throw;$n", [etmp])
  1035. linefmt(p, cpsStmts, "}$n", [])
  1036. # Second pass: handle C++ based exceptions:
  1037. template genExceptBranchBody(body: PNode) {.dirty.} =
  1038. genRestoreFrameAfterException(p)
  1039. #linefmt(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  1040. expr(p, body, d)
  1041. var catchAllPresent = false
  1042. incl p.flags, noSafePoints # mark as not needing 'popCurrentException'
  1043. if hasImportedCppExceptions:
  1044. for i in 1..<t.len:
  1045. if t[i].kind != nkExceptBranch: break
  1046. # bug #4230: avoid false sharing between branches:
  1047. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1048. if t[i].len == 1:
  1049. # general except section:
  1050. startBlock(p, "catch (...) {$n", [])
  1051. genExceptBranchBody(t[i][0])
  1052. endBlock(p)
  1053. catchAllPresent = true
  1054. else:
  1055. for j in 0..<t[i].len-1:
  1056. var typeNode = t[i][j]
  1057. if t[i][j].isInfixAs():
  1058. typeNode = t[i][j][1]
  1059. if isImportedException(typeNode.typ, p.config):
  1060. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1061. fillLocalName(p, exvar.sym)
  1062. fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
  1063. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, typeNode.typ), rdLoc(exvar.sym.loc))
  1064. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1065. endBlock(p)
  1066. elif isImportedException(typeNode.typ, p.config):
  1067. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  1068. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1069. endBlock(p)
  1070. excl p.flags, noSafePoints
  1071. discard pop(p.nestedTryStmts)
  1072. # general finally block:
  1073. if t.len > 0 and t[^1].kind == nkFinally:
  1074. if not catchAllPresent:
  1075. startBlock(p, "catch (...) {$n", [])
  1076. genRestoreFrameAfterException(p)
  1077. linefmt(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  1078. endBlock(p)
  1079. startBlock(p)
  1080. genStmts(p, t[^1][0])
  1081. linefmt(p, cpsStmts, "if (T$1_) std::rethrow_exception(T$1_);$n", [etmp])
  1082. endBlock(p)
  1083. proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
  1084. # There are two versions we generate, depending on whether we
  1085. # catch C++ exceptions, imported via .importcpp or not. The
  1086. # code can be easier if there are no imported C++ exceptions
  1087. # to deal with.
  1088. # code to generate:
  1089. #
  1090. # try
  1091. # {
  1092. # myDiv(4, 9);
  1093. # } catch (NimExceptionType1&) {
  1094. # body
  1095. # } catch (NimExceptionType2&) {
  1096. # finallyPart()
  1097. # raise;
  1098. # }
  1099. # catch(...) {
  1100. # general_handler_body
  1101. # }
  1102. # finallyPart();
  1103. template genExceptBranchBody(body: PNode) {.dirty.} =
  1104. genRestoreFrameAfterException(p)
  1105. expr(p, body, d)
  1106. if not isEmptyType(t.typ) and d.k == locNone:
  1107. d = getTemp(p, t.typ)
  1108. genLineDir(p, t)
  1109. cgsym(p.module, "popCurrentExceptionEx")
  1110. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1111. p.nestedTryStmts.add((fin, false, 0.Natural))
  1112. startBlock(p, "try {$n")
  1113. expr(p, t[0], d)
  1114. endBlock(p)
  1115. var catchAllPresent = false
  1116. p.nestedTryStmts[^1].inExcept = true
  1117. for i in 1..<t.len:
  1118. if t[i].kind != nkExceptBranch: break
  1119. # bug #4230: avoid false sharing between branches:
  1120. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1121. if t[i].len == 1:
  1122. # general except section:
  1123. catchAllPresent = true
  1124. startBlock(p, "catch (...) {$n")
  1125. genExceptBranchBody(t[i][0])
  1126. endBlock(p)
  1127. else:
  1128. for j in 0..<t[i].len-1:
  1129. if t[i][j].isInfixAs():
  1130. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1131. fillLocalName(p, exvar.sym)
  1132. fillLoc(exvar.sym.loc, locTemp, exvar, OnUnknown)
  1133. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, t[i][j][1].typ), rdLoc(exvar.sym.loc))
  1134. else:
  1135. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  1136. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1137. endBlock(p)
  1138. discard pop(p.nestedTryStmts)
  1139. if t[^1].kind == nkFinally:
  1140. # c++ does not have finally, therefore code needs to be generated twice
  1141. if not catchAllPresent:
  1142. # finally requires catch all presence
  1143. startBlock(p, "catch (...) {$n")
  1144. genStmts(p, t[^1][0])
  1145. line(p, cpsStmts, "throw;\n")
  1146. endBlock(p)
  1147. genSimpleBlock(p, t[^1][0])
  1148. proc bodyCanRaise(p: BProc; n: PNode): bool =
  1149. case n.kind
  1150. of nkCallKinds:
  1151. result = canRaiseDisp(p, n[0])
  1152. if not result:
  1153. # also check the arguments:
  1154. for i in 1 ..< n.len:
  1155. if bodyCanRaise(p, n[i]): return true
  1156. of nkRaiseStmt:
  1157. result = true
  1158. of nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef,
  1159. nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  1160. result = false
  1161. else:
  1162. for i in 0 ..< safeLen(n):
  1163. if bodyCanRaise(p, n[i]): return true
  1164. result = false
  1165. proc genTryGoto(p: BProc; t: PNode; d: var TLoc) =
  1166. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1167. inc p.labels
  1168. let lab = p.labels
  1169. let hasExcept = t[1].kind == nkExceptBranch
  1170. if hasExcept: inc p.withinTryWithExcept
  1171. p.nestedTryStmts.add((fin, false, Natural lab))
  1172. p.flags.incl nimErrorFlagAccessed
  1173. if not isEmptyType(t.typ) and d.k == locNone:
  1174. d = getTemp(p, t.typ)
  1175. expr(p, t[0], d)
  1176. if 1 < t.len and t[1].kind == nkExceptBranch:
  1177. startBlock(p, "if (NIM_UNLIKELY(*nimErr_)) {$n")
  1178. else:
  1179. startBlock(p)
  1180. linefmt(p, cpsStmts, "LA$1_:;$n", [lab])
  1181. p.nestedTryStmts[^1].inExcept = true
  1182. var i = 1
  1183. while (i < t.len) and (t[i].kind == nkExceptBranch):
  1184. inc p.labels
  1185. let nextExcept = p.labels
  1186. p.nestedTryStmts[^1].label = nextExcept
  1187. # bug #4230: avoid false sharing between branches:
  1188. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1189. if t[i].len == 1:
  1190. # general except section:
  1191. if i > 1: lineF(p, cpsStmts, "else", [])
  1192. startBlock(p)
  1193. # we handled the exception, remember this:
  1194. linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
  1195. expr(p, t[i][0], d)
  1196. else:
  1197. var orExpr = newRopeAppender()
  1198. for j in 0..<t[i].len - 1:
  1199. assert(t[i][j].kind == nkType)
  1200. if orExpr.len != 0: orExpr.add("||")
  1201. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1202. if optTinyRtti in p.config.globalOptions:
  1203. let checkFor = $getObjDepth(t[i][j].typ)
  1204. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)",
  1205. [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
  1206. else:
  1207. let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
  1208. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1209. if i > 1: line(p, cpsStmts, "else ")
  1210. startBlock(p, "if ($1) {$n", [orExpr])
  1211. # we handled the exception, remember this:
  1212. linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
  1213. expr(p, t[i][^1], d)
  1214. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1215. linefmt(p, cpsStmts, "LA$1_:;$n", [nextExcept])
  1216. endBlock(p)
  1217. inc(i)
  1218. discard pop(p.nestedTryStmts)
  1219. endBlock(p)
  1220. if i < t.len and t[i].kind == nkFinally:
  1221. startBlock(p)
  1222. if not bodyCanRaise(p, t[i][0]):
  1223. # this is an important optimization; most destroy blocks are detected not to raise an
  1224. # exception and so we help the C optimizer by not mutating nimErr_ pointlessly:
  1225. genStmts(p, t[i][0])
  1226. else:
  1227. # pretend we did handle the error for the safe execution of the 'finally' section:
  1228. p.procSec(cpsLocals).add(ropecg(p.module, "NIM_BOOL oldNimErrFin$1_;$n", [lab]))
  1229. linefmt(p, cpsStmts, "oldNimErrFin$1_ = *nimErr_; *nimErr_ = NIM_FALSE;$n", [lab])
  1230. genStmts(p, t[i][0])
  1231. # this is correct for all these cases:
  1232. # 1. finally is run during ordinary control flow
  1233. # 2. finally is run after 'except' block handling: these however set the
  1234. # error back to nil.
  1235. # 3. finally is run for exception handling code without any 'except'
  1236. # handler present or only handlers that did not match.
  1237. linefmt(p, cpsStmts, "*nimErr_ = oldNimErrFin$1_;$n", [lab])
  1238. endBlock(p)
  1239. raiseExit(p)
  1240. if hasExcept: inc p.withinTryWithExcept
  1241. proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
  1242. # code to generate:
  1243. #
  1244. # XXX: There should be a standard dispatch algorithm
  1245. # that's used both here and with multi-methods
  1246. #
  1247. # TSafePoint sp;
  1248. # pushSafePoint(&sp);
  1249. # sp.status = setjmp(sp.context);
  1250. # if (sp.status == 0) {
  1251. # myDiv(4, 9);
  1252. # popSafePoint();
  1253. # } else {
  1254. # popSafePoint();
  1255. # /* except DivisionByZero: */
  1256. # if (sp.status == DivisionByZero) {
  1257. # printf('Division by Zero\n');
  1258. # clearException();
  1259. # } else {
  1260. # clearException();
  1261. # }
  1262. # }
  1263. # {
  1264. # /* finally: */
  1265. # printf('fin!\n');
  1266. # }
  1267. # if (exception not cleared)
  1268. # propagateCurrentException();
  1269. #
  1270. if not isEmptyType(t.typ) and d.k == locNone:
  1271. d = getTemp(p, t.typ)
  1272. let quirkyExceptions = p.config.exc == excQuirky or
  1273. (t.kind == nkHiddenTryStmt and sfSystemModule in p.module.module.flags)
  1274. if not quirkyExceptions:
  1275. p.module.includeHeader("<setjmp.h>")
  1276. else:
  1277. p.flags.incl noSafePoints
  1278. genLineDir(p, t)
  1279. cgsym(p.module, "Exception")
  1280. var safePoint: Rope = ""
  1281. if not quirkyExceptions:
  1282. safePoint = getTempName(p.module)
  1283. linefmt(p, cpsLocals, "#TSafePoint $1;$n", [safePoint])
  1284. linefmt(p, cpsStmts, "#pushSafePoint(&$1);$n", [safePoint])
  1285. if isDefined(p.config, "nimStdSetjmp"):
  1286. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1287. elif isDefined(p.config, "nimSigSetjmp"):
  1288. linefmt(p, cpsStmts, "$1.status = sigsetjmp($1.context, 0);$n", [safePoint])
  1289. elif isDefined(p.config, "nimBuiltinSetjmp"):
  1290. linefmt(p, cpsStmts, "$1.status = __builtin_setjmp($1.context);$n", [safePoint])
  1291. elif isDefined(p.config, "nimRawSetjmp"):
  1292. if isDefined(p.config, "mswindows"):
  1293. if isDefined(p.config, "vcc") or isDefined(p.config, "clangcl"):
  1294. # For the vcc compiler, use `setjmp()` with one argument.
  1295. # See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setjmp?view=msvc-170
  1296. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1297. else:
  1298. # The Windows `_setjmp()` takes two arguments, with the second being an
  1299. # undocumented buffer used by the SEH mechanism for stack unwinding.
  1300. # Mingw-w64 has been trying to get it right for years, but it's still
  1301. # prone to stack corruption during unwinding, so we disable that by setting
  1302. # it to NULL.
  1303. # More details: https://github.com/status-im/nimbus-eth2/issues/3121
  1304. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context, 0);$n", [safePoint])
  1305. else:
  1306. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", [safePoint])
  1307. else:
  1308. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1309. lineCg(p, cpsStmts, "if ($1.status == 0) {$n", [safePoint])
  1310. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1311. p.nestedTryStmts.add((fin, quirkyExceptions, 0.Natural))
  1312. expr(p, t[0], d)
  1313. if not quirkyExceptions:
  1314. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  1315. lineCg(p, cpsStmts, "}$n", [])
  1316. startBlock(p, "else {$n")
  1317. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  1318. genRestoreFrameAfterException(p)
  1319. elif 1 < t.len and t[1].kind == nkExceptBranch:
  1320. startBlock(p, "if (#nimBorrowCurrentException()) {$n")
  1321. else:
  1322. startBlock(p)
  1323. p.nestedTryStmts[^1].inExcept = true
  1324. var i = 1
  1325. while (i < t.len) and (t[i].kind == nkExceptBranch):
  1326. # bug #4230: avoid false sharing between branches:
  1327. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1328. if t[i].len == 1:
  1329. # general except section:
  1330. if i > 1: lineF(p, cpsStmts, "else", [])
  1331. startBlock(p)
  1332. if not quirkyExceptions:
  1333. linefmt(p, cpsStmts, "$1.status = 0;$n", [safePoint])
  1334. expr(p, t[i][0], d)
  1335. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1336. endBlock(p)
  1337. else:
  1338. var orExpr = newRopeAppender()
  1339. for j in 0..<t[i].len - 1:
  1340. assert(t[i][j].kind == nkType)
  1341. if orExpr.len != 0: orExpr.add("||")
  1342. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1343. if optTinyRtti in p.config.globalOptions:
  1344. let checkFor = $getObjDepth(t[i][j].typ)
  1345. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)",
  1346. [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
  1347. else:
  1348. let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
  1349. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1350. if i > 1: line(p, cpsStmts, "else ")
  1351. startBlock(p, "if ($1) {$n", [orExpr])
  1352. if not quirkyExceptions:
  1353. linefmt(p, cpsStmts, "$1.status = 0;$n", [safePoint])
  1354. expr(p, t[i][^1], d)
  1355. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1356. endBlock(p)
  1357. inc(i)
  1358. discard pop(p.nestedTryStmts)
  1359. endBlock(p) # end of else block
  1360. if i < t.len and t[i].kind == nkFinally:
  1361. p.finallySafePoints.add(safePoint)
  1362. startBlock(p)
  1363. genStmts(p, t[i][0])
  1364. # pretend we handled the exception in a 'finally' so that we don't
  1365. # re-raise the unhandled one but instead keep the old one (it was
  1366. # not popped either):
  1367. if not quirkyExceptions and getCompilerProc(p.module.g.graph, "nimLeaveFinally") != nil:
  1368. linefmt(p, cpsStmts, "if ($1.status != 0) #nimLeaveFinally();$n", [safePoint])
  1369. endBlock(p)
  1370. discard pop(p.finallySafePoints)
  1371. if not quirkyExceptions:
  1372. linefmt(p, cpsStmts, "if ($1.status != 0) #reraiseException();$n", [safePoint])
  1373. proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false; result: var Rope) =
  1374. var res = ""
  1375. let offset =
  1376. if isAsmStmt: 1 # first son is pragmas
  1377. else: 0
  1378. for i in offset..<t.len:
  1379. let it = t[i]
  1380. case it.kind
  1381. of nkStrLit..nkTripleStrLit:
  1382. res.add(it.strVal)
  1383. of nkSym:
  1384. var sym = it.sym
  1385. if sym.kind in {skProc, skFunc, skIterator, skMethod}:
  1386. var a: TLoc = initLocExpr(p, it)
  1387. res.add($rdLoc(a))
  1388. elif sym.kind == skType:
  1389. res.add($getTypeDesc(p.module, sym.typ))
  1390. else:
  1391. discard getTypeDesc(p.module, skipTypes(sym.typ, abstractPtrs))
  1392. fillBackendName(p.module, sym)
  1393. res.add($sym.loc.r)
  1394. of nkTypeOfExpr:
  1395. res.add($getTypeDesc(p.module, it.typ))
  1396. else:
  1397. discard getTypeDesc(p.module, skipTypes(it.typ, abstractPtrs))
  1398. var a: TLoc = initLocExpr(p, it)
  1399. res.add($a.rdLoc)
  1400. if isAsmStmt and hasGnuAsm in CC[p.config.cCompiler].props:
  1401. for x in splitLines(res):
  1402. var j = 0
  1403. while j < x.len and x[j] in {' ', '\t'}: inc(j)
  1404. if j < x.len:
  1405. if x[j] in {'"', ':'}:
  1406. # don't modify the line if already in quotes or
  1407. # some clobber register list:
  1408. result.add(x); result.add("\L")
  1409. else:
  1410. # ignore empty lines
  1411. result.add("\"")
  1412. result.add(x.replace("\"", "\\\""))
  1413. result.add("\\n\"\n")
  1414. else:
  1415. res.add("\L")
  1416. result.add res.rope
  1417. proc genAsmStmt(p: BProc, t: PNode) =
  1418. assert(t.kind == nkAsmStmt)
  1419. genLineDir(p, t)
  1420. var s = newRopeAppender()
  1421. var asmSyntax = ""
  1422. if (let p = t[0]; p.kind == nkPragma):
  1423. for i in p:
  1424. if whichPragma(i) == wAsmSyntax:
  1425. asmSyntax = i[1].strVal
  1426. if asmSyntax != "" and
  1427. not (
  1428. asmSyntax == "gcc" and hasGnuAsm in CC[p.config.cCompiler].props or
  1429. asmSyntax == "vcc" and hasGnuAsm notin CC[p.config.cCompiler].props):
  1430. localError(
  1431. p.config, t.info,
  1432. "Your compiler does not support the specified inline assembler")
  1433. genAsmOrEmitStmt(p, t, isAsmStmt=true, s)
  1434. # see bug #2362, "top level asm statements" seem to be a mis-feature
  1435. # but even if we don't do this, the example in #2362 cannot possibly
  1436. # work:
  1437. if p.prc == nil:
  1438. # top level asm statement?
  1439. p.module.s[cfsProcHeaders].add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
  1440. else:
  1441. addIndent p, p.s(cpsStmts)
  1442. p.s(cpsStmts).add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
  1443. proc determineSection(n: PNode): TCFileSection =
  1444. result = cfsProcHeaders
  1445. if n.len >= 1 and n[0].kind in {nkStrLit..nkTripleStrLit}:
  1446. let sec = n[0].strVal
  1447. if sec.startsWith("/*TYPESECTION*/"): result = cfsForwardTypes # TODO WORKAROUND
  1448. elif sec.startsWith("/*VARSECTION*/"): result = cfsVars
  1449. elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders
  1450. proc genEmit(p: BProc, t: PNode) =
  1451. var s = newRopeAppender()
  1452. genAsmOrEmitStmt(p, t[1], false, s)
  1453. if p.prc == nil:
  1454. # top level emit pragma?
  1455. let section = determineSection(t[1])
  1456. genCLineDir(p.module.s[section], t.info, p.config)
  1457. p.module.s[section].add(s)
  1458. else:
  1459. genLineDir(p, t)
  1460. line(p, cpsStmts, s)
  1461. proc genPragma(p: BProc, n: PNode) =
  1462. for i in 0..<n.len:
  1463. let it = n[i]
  1464. case whichPragma(it)
  1465. of wEmit: genEmit(p, it)
  1466. of wPush:
  1467. processPushBackendOption(p.optionsStack, p.options, n, i+1)
  1468. of wPop:
  1469. processPopBackendOption(p.optionsStack, p.options)
  1470. else: discard
  1471. proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
  1472. field: PSym) =
  1473. var t = skipTypes(objtype, abstractVar)
  1474. assert t.kind == tyObject
  1475. discard genTypeInfoV1(p.module, t, a.lode.info)
  1476. if not containsOrIncl(p.module.declaredThings, field.id):
  1477. appcg(p.module, cfsVars, "extern $1",
  1478. [discriminatorTableDecl(p.module, t, field)])
  1479. var lit = newRopeAppender()
  1480. intLiteral(toInt64(lengthOrd(p.config, field.typ))+1, lit)
  1481. lineCg(p, cpsStmts,
  1482. "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n",
  1483. [rdLoc(a), rdLoc(tmp), discriminatorTableName(p.module, t, field),
  1484. lit])
  1485. if p.config.exc == excGoto:
  1486. raiseExit(p)
  1487. when false:
  1488. proc genCaseObjDiscMapping(p: BProc, e: PNode, t: PType, field: PSym; d: var TLoc) =
  1489. const ObjDiscMappingProcSlot = -5
  1490. var theProc: PSym = nil
  1491. for idx, p in items(t.methods):
  1492. if idx == ObjDiscMappingProcSlot:
  1493. theProc = p
  1494. break
  1495. if theProc == nil:
  1496. theProc = genCaseObjDiscMapping(t, field, e.info, p.module.g.graph, p.module.idgen)
  1497. t.methods.add((ObjDiscMappingProcSlot, theProc))
  1498. var call = newNodeIT(nkCall, e.info, getSysType(p.module.g.graph, e.info, tyUInt8))
  1499. call.add newSymNode(theProc)
  1500. call.add e
  1501. expr(p, call, d)
  1502. proc asgnFieldDiscriminant(p: BProc, e: PNode) =
  1503. var dotExpr = e[0]
  1504. if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr[0]
  1505. var a = initLocExpr(p, e[0])
  1506. var tmp: TLoc = getTemp(p, a.t)
  1507. expr(p, e[1], tmp)
  1508. if p.inUncheckedAssignSection == 0:
  1509. let field = dotExpr[1].sym
  1510. genDiscriminantCheck(p, a, tmp, dotExpr[0].typ, field)
  1511. message(p.config, e.info, warnCaseTransition)
  1512. genAssignment(p, a, tmp, {})
  1513. proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
  1514. if e[0].kind == nkSym and sfGoto in e[0].sym.flags:
  1515. genLineDir(p, e)
  1516. genGotoVar(p, e[1])
  1517. elif optFieldCheck in p.options and isDiscriminantField(e[0]):
  1518. genLineDir(p, e)
  1519. asgnFieldDiscriminant(p, e)
  1520. else:
  1521. let le = e[0]
  1522. let ri = e[1]
  1523. var a: TLoc = initLoc(locNone, le, OnUnknown)
  1524. discard getTypeDesc(p.module, le.typ.skipTypes(skipPtrs), dkVar)
  1525. a.flags.incl(lfEnforceDeref)
  1526. a.flags.incl(lfPrepareForMutation)
  1527. genLineDir(p, le) # it can be a nkBracketExpr, which may raise
  1528. expr(p, le, a)
  1529. a.flags.excl(lfPrepareForMutation)
  1530. if fastAsgn: incl(a.flags, lfNoDeepCopy)
  1531. assert(a.t != nil)
  1532. genLineDir(p, ri)
  1533. loadInto(p, le, ri, a)
  1534. proc genStmts(p: BProc, t: PNode) =
  1535. var a: TLoc = default(TLoc)
  1536. let isPush = p.config.hasHint(hintExtendedContext)
  1537. if isPush: pushInfoContext(p.config, t.info)
  1538. expr(p, t, a)
  1539. if isPush: popInfoContext(p.config)
  1540. internalAssert p.config, a.k in {locNone, locTemp, locLocalVar, locExpr}