ccgstmts.nim 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707
  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 raiseExitCleanup(p: BProc, destroy: string) =
  680. assert p.config.exc == excGoto
  681. if nimErrorFlagDisabled notin p.flags:
  682. p.flags.incl nimErrorFlagAccessed
  683. if p.nestedTryStmts.len == 0:
  684. p.flags.incl beforeRetNeeded
  685. # easy case, simply goto 'ret':
  686. lineCg(p, cpsStmts, "if (NIM_UNLIKELY(*nimErr_)) {$1; goto BeforeRet_;}$n", [destroy])
  687. else:
  688. lineCg(p, cpsStmts, "if (NIM_UNLIKELY(*nimErr_)) {$2; goto LA$1_;}$n",
  689. [p.nestedTryStmts[^1].label, destroy])
  690. proc finallyActions(p: BProc) =
  691. if p.config.exc != excGoto and p.nestedTryStmts.len > 0 and p.nestedTryStmts[^1].inExcept:
  692. # if the current try stmt have a finally block,
  693. # we must execute it before reraising
  694. let finallyBlock = p.nestedTryStmts[^1].fin
  695. if finallyBlock != nil:
  696. genSimpleBlock(p, finallyBlock[0])
  697. proc raiseInstr(p: BProc; result: var Rope) =
  698. if p.config.exc == excGoto:
  699. let L = p.nestedTryStmts.len
  700. if L == 0:
  701. p.flags.incl beforeRetNeeded
  702. # easy case, simply goto 'ret':
  703. result.add ropecg(p.module, "goto BeforeRet_;$n", [])
  704. else:
  705. # raise inside an 'except' must go to the finally block,
  706. # raise outside an 'except' block must go to the 'except' list.
  707. result.add ropecg(p.module, "goto LA$1_;$n",
  708. [p.nestedTryStmts[L-1].label])
  709. # + ord(p.nestedTryStmts[L-1].inExcept)])
  710. proc genRaiseStmt(p: BProc, t: PNode) =
  711. if t[0].kind != nkEmpty:
  712. var a: TLoc = initLocExprSingleUse(p, t[0])
  713. finallyActions(p)
  714. var e = rdLoc(a)
  715. discard getTypeDesc(p.module, t[0].typ)
  716. var typ = skipTypes(t[0].typ, abstractPtrs)
  717. # XXX For reasons that currently escape me, this is only required by the new
  718. # C++ based exception handling:
  719. if p.config.exc == excCpp:
  720. blockLeaveActions(p, howManyTrys = 0, howManyExcepts = p.inExceptBlockLen)
  721. genLineDir(p, t)
  722. if isImportedException(typ, p.config):
  723. lineF(p, cpsStmts, "throw $1;$n", [e])
  724. else:
  725. lineCg(p, cpsStmts, "#raiseExceptionEx((#Exception*)$1, $2, $3, $4, $5);$n",
  726. [e, makeCString(typ.sym.name.s),
  727. makeCString(if p.prc != nil: p.prc.name.s else: p.module.module.name.s),
  728. quotedFilename(p.config, t.info), toLinenumber(t.info)])
  729. if optOwnedRefs in p.config.globalOptions:
  730. lineCg(p, cpsStmts, "$1 = NIM_NIL;$n", [e])
  731. else:
  732. finallyActions(p)
  733. genLineDir(p, t)
  734. linefmt(p, cpsStmts, "#reraiseException();$n", [])
  735. raiseInstr(p, p.s(cpsStmts))
  736. template genCaseGenericBranch(p: BProc, b: PNode, e: TLoc,
  737. rangeFormat, eqFormat: FormatStr, labl: TLabel) =
  738. var x, y: TLoc
  739. for i in 0..<b.len - 1:
  740. if b[i].kind == nkRange:
  741. x = initLocExpr(p, b[i][0])
  742. y = initLocExpr(p, b[i][1])
  743. lineCg(p, cpsStmts, rangeFormat,
  744. [rdCharLoc(e), rdCharLoc(x), rdCharLoc(y), labl])
  745. else:
  746. x = initLocExpr(p, b[i])
  747. lineCg(p, cpsStmts, eqFormat, [rdCharLoc(e), rdCharLoc(x), labl])
  748. proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc,
  749. labId, until: int): TLabel =
  750. var lend = getLabel(p)
  751. for i in 1..until:
  752. # bug #4230: avoid false sharing between branches:
  753. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  754. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(labId + i)])
  755. if t[i].kind == nkOfBranch:
  756. exprBlock(p, t[i][^1], d)
  757. lineF(p, cpsStmts, "goto $1;$n", [lend])
  758. else:
  759. exprBlock(p, t[i][0], d)
  760. result = lend
  761. template genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc,
  762. rangeFormat, eqFormat: FormatStr,
  763. until: int, a: TLoc): TLabel =
  764. # generate a C-if statement for a Nim case statement
  765. var res: TLabel
  766. var labId = p.labels
  767. for i in 1..until:
  768. inc(p.labels)
  769. if t[i].kind == nkOfBranch: # else statement
  770. genCaseGenericBranch(p, t[i], a, rangeFormat, eqFormat,
  771. "LA" & rope(p.labels) & "_")
  772. else:
  773. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  774. if until < t.len-1:
  775. inc(p.labels)
  776. var gotoTarget = p.labels
  777. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(gotoTarget)])
  778. res = genCaseSecondPass(p, t, d, labId, until)
  779. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(gotoTarget)])
  780. else:
  781. res = genCaseSecondPass(p, t, d, labId, until)
  782. res
  783. template genCaseGeneric(p: BProc, t: PNode, d: var TLoc,
  784. rangeFormat, eqFormat: FormatStr) =
  785. var a: TLoc = initLocExpr(p, t[0])
  786. var lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, t.len-1, a)
  787. fixLabel(p, lend)
  788. proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel,
  789. stringKind: TTypeKind,
  790. branches: var openArray[Rope]) =
  791. var x: TLoc
  792. for i in 0..<b.len - 1:
  793. assert(b[i].kind != nkRange)
  794. x = initLocExpr(p, b[i])
  795. var j: int = 0
  796. case b[i].kind
  797. of nkStrLit..nkTripleStrLit:
  798. j = int(hashString(p.config, b[i].strVal) and high(branches))
  799. of nkNilLit: j = 0
  800. else:
  801. assert false, "invalid string case branch node kind"
  802. if stringKind == tyCstring:
  803. appcg(p.module, branches[j], "if (#eqCstrings($1, $2)) goto $3;$n",
  804. [rdLoc(e), rdLoc(x), labl])
  805. else:
  806. appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
  807. [rdLoc(e), rdLoc(x), labl])
  808. proc genStringCase(p: BProc, t: PNode, stringKind: TTypeKind, d: var TLoc) =
  809. # count how many constant strings there are in the case:
  810. var strings = 0
  811. for i in 1..<t.len:
  812. if t[i].kind == nkOfBranch: inc(strings, t[i].len - 1)
  813. if strings > stringCaseThreshold:
  814. var bitMask = math.nextPowerOfTwo(strings) - 1
  815. var branches: seq[Rope]
  816. newSeq(branches, bitMask + 1)
  817. var a: TLoc = initLocExpr(p, t[0]) # first pass: generate ifs+goto:
  818. var labId = p.labels
  819. for i in 1..<t.len:
  820. inc(p.labels)
  821. if t[i].kind == nkOfBranch:
  822. genCaseStringBranch(p, t[i], a, "LA" & rope(p.labels) & "_",
  823. stringKind, branches)
  824. else:
  825. # else statement: nothing to do yet
  826. # but we reserved a label, which we use later
  827. discard
  828. if stringKind == tyCstring:
  829. linefmt(p, cpsStmts, "switch (#hashCstring($1) & $2) {$n",
  830. [rdLoc(a), bitMask])
  831. else:
  832. linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
  833. [rdLoc(a), bitMask])
  834. for j in 0..high(branches):
  835. if branches[j] != "":
  836. var lit = newRopeAppender()
  837. intLiteral(j, lit)
  838. lineF(p, cpsStmts, "case $1: $n$2break;$n",
  839. [lit, branches[j]])
  840. lineF(p, cpsStmts, "}$n", []) # else statement:
  841. if t[^1].kind != nkOfBranch:
  842. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  843. # third pass: generate statements
  844. var lend = genCaseSecondPass(p, t, d, labId, t.len-1)
  845. fixLabel(p, lend)
  846. else:
  847. if stringKind == tyCstring:
  848. genCaseGeneric(p, t, d, "", "if (#eqCstrings($1, $2)) goto $3;$n")
  849. else:
  850. genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
  851. proc branchHasTooBigRange(b: PNode): bool =
  852. result = false
  853. for it in b:
  854. # last son is block
  855. if (it.kind == nkRange) and
  856. it[1].intVal - it[0].intVal > RangeExpandLimit:
  857. return true
  858. proc ifSwitchSplitPoint(p: BProc, n: PNode): int =
  859. result = 0
  860. for i in 1..<n.len:
  861. var branch = n[i]
  862. var stmtBlock = lastSon(branch)
  863. if stmtBlock.stmtsContainPragma(wLinearScanEnd):
  864. result = i
  865. elif hasSwitchRange notin CC[p.config.cCompiler].props:
  866. if branch.kind == nkOfBranch and branchHasTooBigRange(branch):
  867. result = i
  868. proc genCaseRange(p: BProc, branch: PNode) =
  869. for j in 0..<branch.len-1:
  870. if branch[j].kind == nkRange:
  871. if hasSwitchRange in CC[p.config.cCompiler].props:
  872. var litA = newRopeAppender()
  873. var litB = newRopeAppender()
  874. genLiteral(p, branch[j][0], litA)
  875. genLiteral(p, branch[j][1], litB)
  876. lineF(p, cpsStmts, "case $1 ... $2:$n", [litA, litB])
  877. else:
  878. var v = copyNode(branch[j][0])
  879. while v.intVal <= branch[j][1].intVal:
  880. var litA = newRopeAppender()
  881. genLiteral(p, v, litA)
  882. lineF(p, cpsStmts, "case $1:$n", [litA])
  883. inc(v.intVal)
  884. else:
  885. var litA = newRopeAppender()
  886. genLiteral(p, branch[j], litA)
  887. lineF(p, cpsStmts, "case $1:$n", [litA])
  888. proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
  889. # analyse 'case' statement:
  890. var splitPoint = ifSwitchSplitPoint(p, n)
  891. # generate if part (might be empty):
  892. var a: TLoc = initLocExpr(p, n[0])
  893. var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d,
  894. rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  895. eqFormat = "if ($1 == $2) goto $3;$n",
  896. splitPoint, a) else: ""
  897. # generate switch part (might be empty):
  898. if splitPoint+1 < n.len:
  899. lineF(p, cpsStmts, "switch ($1) {$n", [rdCharLoc(a)])
  900. var hasDefault = false
  901. for i in splitPoint+1..<n.len:
  902. # bug #4230: avoid false sharing between branches:
  903. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  904. var branch = n[i]
  905. if branch.kind == nkOfBranch:
  906. genCaseRange(p, branch)
  907. else:
  908. # else part of case statement:
  909. lineF(p, cpsStmts, "default:$n", [])
  910. hasDefault = true
  911. exprBlock(p, branch.lastSon, d)
  912. lineF(p, cpsStmts, "break;$n", [])
  913. if not hasDefault:
  914. if hasBuiltinUnreachable in CC[p.config.cCompiler].props:
  915. lineF(p, cpsStmts, "default: __builtin_unreachable();$n", [])
  916. elif hasAssume in CC[p.config.cCompiler].props:
  917. lineF(p, cpsStmts, "default: __assume(0);$n", [])
  918. lineF(p, cpsStmts, "}$n", [])
  919. if lend != "": fixLabel(p, lend)
  920. proc genCase(p: BProc, t: PNode, d: var TLoc) =
  921. genLineDir(p, t)
  922. if not isEmptyType(t.typ) and d.k == locNone:
  923. d = getTemp(p, t.typ)
  924. case skipTypes(t[0].typ, abstractVarRange).kind
  925. of tyString:
  926. genStringCase(p, t, tyString, d)
  927. of tyCstring:
  928. genStringCase(p, t, tyCstring, d)
  929. of tyFloat..tyFloat128:
  930. genCaseGeneric(p, t, d, "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  931. "if ($1 == $2) goto $3;$n")
  932. else:
  933. if t[0].kind == nkSym and sfGoto in t[0].sym.flags:
  934. genGotoForCase(p, t)
  935. else:
  936. genOrdinalCase(p, t, d)
  937. proc genRestoreFrameAfterException(p: BProc) =
  938. if optStackTrace in p.module.config.options:
  939. if hasCurFramePointer notin p.flags:
  940. p.flags.incl hasCurFramePointer
  941. p.procSec(cpsLocals).add(ropecg(p.module, "\tTFrame* _nimCurFrame;$n", []))
  942. p.procSec(cpsInit).add(ropecg(p.module, "\t_nimCurFrame = #getFrame();$n", []))
  943. linefmt(p, cpsStmts, "#setFrame(_nimCurFrame);$n", [])
  944. proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
  945. #[ code to generate:
  946. std::exception_ptr error;
  947. try {
  948. body;
  949. } catch (Exception e) {
  950. error = std::current_exception();
  951. if (ofExpr(e, TypeHere)) {
  952. error = nullptr; // handled
  953. } else if (...) {
  954. } else {
  955. throw;
  956. }
  957. } catch(...) {
  958. // C++ exception occured, not under Nim's control.
  959. }
  960. {
  961. /* finally: */
  962. printf('fin!\n');
  963. if (error) std::rethrow_exception(error); // re-raise the exception
  964. }
  965. ]#
  966. p.module.includeHeader("<exception>")
  967. if not isEmptyType(t.typ) and d.k == locNone:
  968. d = getTemp(p, t.typ)
  969. genLineDir(p, t)
  970. inc(p.labels, 2)
  971. let etmp = p.labels
  972. #init on locals, fixes #23306
  973. lineCg(p, cpsLocals, "std::exception_ptr T$1_;$n", [etmp])
  974. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  975. p.nestedTryStmts.add((fin, false, 0.Natural))
  976. if t.kind == nkHiddenTryStmt:
  977. lineCg(p, cpsStmts, "try {$n", [])
  978. expr(p, t[0], d)
  979. lineCg(p, cpsStmts, "}$n", [])
  980. else:
  981. startBlock(p, "try {$n")
  982. expr(p, t[0], d)
  983. endBlock(p)
  984. # First pass: handle Nim based exceptions:
  985. lineCg(p, cpsStmts, "catch (#Exception* T$1_) {$n", [etmp+1])
  986. genRestoreFrameAfterException(p)
  987. # an unhandled exception happened!
  988. lineCg(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  989. p.nestedTryStmts[^1].inExcept = true
  990. var hasImportedCppExceptions = false
  991. var i = 1
  992. var hasIf = false
  993. var hasElse = false
  994. while (i < t.len) and (t[i].kind == nkExceptBranch):
  995. # bug #4230: avoid false sharing between branches:
  996. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  997. if t[i].len == 1:
  998. hasImportedCppExceptions = true
  999. # general except section:
  1000. hasElse = true
  1001. if hasIf: lineF(p, cpsStmts, "else ", [])
  1002. startBlock(p)
  1003. # we handled the error:
  1004. expr(p, t[i][0], d)
  1005. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1006. endBlock(p)
  1007. else:
  1008. var orExpr = newRopeAppender()
  1009. var exvar = PNode(nil)
  1010. for j in 0..<t[i].len - 1:
  1011. var typeNode = t[i][j]
  1012. if t[i][j].isInfixAs():
  1013. typeNode = t[i][j][1]
  1014. exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1015. assert(typeNode.kind == nkType)
  1016. if isImportedException(typeNode.typ, p.config):
  1017. hasImportedCppExceptions = true
  1018. else:
  1019. if orExpr.len != 0: orExpr.add("||")
  1020. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1021. if optTinyRtti in p.config.globalOptions:
  1022. let checkFor = $getObjDepth(typeNode.typ)
  1023. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)", [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(typeNode.typ, p.config)))])
  1024. else:
  1025. let checkFor = genTypeInfoV1(p.module, typeNode.typ, typeNode.info)
  1026. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1027. if orExpr.len != 0:
  1028. if hasIf:
  1029. startBlock(p, "else if ($1) {$n", [orExpr])
  1030. else:
  1031. startBlock(p, "if ($1) {$n", [orExpr])
  1032. hasIf = true
  1033. if exvar != nil:
  1034. fillLocalName(p, exvar.sym)
  1035. fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
  1036. linefmt(p, cpsStmts, "$1 $2 = T$3_;$n", [getTypeDesc(p.module, exvar.sym.typ),
  1037. rdLoc(exvar.sym.loc), rope(etmp+1)])
  1038. # we handled the error:
  1039. linefmt(p, cpsStmts, "T$1_ = nullptr;$n", [etmp])
  1040. expr(p, t[i][^1], d)
  1041. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1042. endBlock(p)
  1043. inc(i)
  1044. if hasIf and not hasElse:
  1045. linefmt(p, cpsStmts, "else throw;$n", [etmp])
  1046. linefmt(p, cpsStmts, "}$n", [])
  1047. # Second pass: handle C++ based exceptions:
  1048. template genExceptBranchBody(body: PNode) {.dirty.} =
  1049. genRestoreFrameAfterException(p)
  1050. #linefmt(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  1051. expr(p, body, d)
  1052. var catchAllPresent = false
  1053. incl p.flags, noSafePoints # mark as not needing 'popCurrentException'
  1054. if hasImportedCppExceptions:
  1055. for i in 1..<t.len:
  1056. if t[i].kind != nkExceptBranch: break
  1057. # bug #4230: avoid false sharing between branches:
  1058. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1059. if t[i].len == 1:
  1060. # general except section:
  1061. startBlock(p, "catch (...) {$n", [])
  1062. genExceptBranchBody(t[i][0])
  1063. endBlock(p)
  1064. catchAllPresent = true
  1065. else:
  1066. for j in 0..<t[i].len-1:
  1067. var typeNode = t[i][j]
  1068. if t[i][j].isInfixAs():
  1069. typeNode = t[i][j][1]
  1070. if isImportedException(typeNode.typ, p.config):
  1071. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1072. fillLocalName(p, exvar.sym)
  1073. fillLoc(exvar.sym.loc, locTemp, exvar, OnStack)
  1074. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, typeNode.typ), rdLoc(exvar.sym.loc))
  1075. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1076. endBlock(p)
  1077. elif isImportedException(typeNode.typ, p.config):
  1078. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  1079. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1080. endBlock(p)
  1081. excl p.flags, noSafePoints
  1082. discard pop(p.nestedTryStmts)
  1083. # general finally block:
  1084. if t.len > 0 and t[^1].kind == nkFinally:
  1085. if not catchAllPresent:
  1086. startBlock(p, "catch (...) {$n", [])
  1087. genRestoreFrameAfterException(p)
  1088. linefmt(p, cpsStmts, "T$1_ = std::current_exception();$n", [etmp])
  1089. endBlock(p)
  1090. startBlock(p)
  1091. genStmts(p, t[^1][0])
  1092. linefmt(p, cpsStmts, "if (T$1_) std::rethrow_exception(T$1_);$n", [etmp])
  1093. endBlock(p)
  1094. proc genTryCppOld(p: BProc, t: PNode, d: var TLoc) =
  1095. # There are two versions we generate, depending on whether we
  1096. # catch C++ exceptions, imported via .importcpp or not. The
  1097. # code can be easier if there are no imported C++ exceptions
  1098. # to deal with.
  1099. # code to generate:
  1100. #
  1101. # try
  1102. # {
  1103. # myDiv(4, 9);
  1104. # } catch (NimExceptionType1&) {
  1105. # body
  1106. # } catch (NimExceptionType2&) {
  1107. # finallyPart()
  1108. # raise;
  1109. # }
  1110. # catch(...) {
  1111. # general_handler_body
  1112. # }
  1113. # finallyPart();
  1114. template genExceptBranchBody(body: PNode) {.dirty.} =
  1115. genRestoreFrameAfterException(p)
  1116. expr(p, body, d)
  1117. if not isEmptyType(t.typ) and d.k == locNone:
  1118. d = getTemp(p, t.typ)
  1119. genLineDir(p, t)
  1120. cgsym(p.module, "popCurrentExceptionEx")
  1121. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1122. p.nestedTryStmts.add((fin, false, 0.Natural))
  1123. startBlock(p, "try {$n")
  1124. expr(p, t[0], d)
  1125. endBlock(p)
  1126. var catchAllPresent = false
  1127. p.nestedTryStmts[^1].inExcept = true
  1128. for i in 1..<t.len:
  1129. if t[i].kind != nkExceptBranch: break
  1130. # bug #4230: avoid false sharing between branches:
  1131. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1132. if t[i].len == 1:
  1133. # general except section:
  1134. catchAllPresent = true
  1135. startBlock(p, "catch (...) {$n")
  1136. genExceptBranchBody(t[i][0])
  1137. endBlock(p)
  1138. else:
  1139. for j in 0..<t[i].len-1:
  1140. if t[i][j].isInfixAs():
  1141. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  1142. fillLocalName(p, exvar.sym)
  1143. fillLoc(exvar.sym.loc, locTemp, exvar, OnUnknown)
  1144. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, t[i][j][1].typ), rdLoc(exvar.sym.loc))
  1145. else:
  1146. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  1147. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  1148. endBlock(p)
  1149. discard pop(p.nestedTryStmts)
  1150. if t[^1].kind == nkFinally:
  1151. # c++ does not have finally, therefore code needs to be generated twice
  1152. if not catchAllPresent:
  1153. # finally requires catch all presence
  1154. startBlock(p, "catch (...) {$n")
  1155. genStmts(p, t[^1][0])
  1156. line(p, cpsStmts, "throw;\n")
  1157. endBlock(p)
  1158. genSimpleBlock(p, t[^1][0])
  1159. proc bodyCanRaise(p: BProc; n: PNode): bool =
  1160. case n.kind
  1161. of nkCallKinds:
  1162. result = canRaiseDisp(p, n[0])
  1163. if not result:
  1164. # also check the arguments:
  1165. for i in 1 ..< n.len:
  1166. if bodyCanRaise(p, n[i]): return true
  1167. of nkRaiseStmt:
  1168. result = true
  1169. of nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef,
  1170. nkMacroDef, nkTemplateDef, nkLambda, nkDo, nkFuncDef:
  1171. result = false
  1172. else:
  1173. for i in 0 ..< safeLen(n):
  1174. if bodyCanRaise(p, n[i]): return true
  1175. result = false
  1176. proc genTryGoto(p: BProc; t: PNode; d: var TLoc) =
  1177. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1178. inc p.labels
  1179. let lab = p.labels
  1180. let hasExcept = t[1].kind == nkExceptBranch
  1181. if hasExcept: inc p.withinTryWithExcept
  1182. p.nestedTryStmts.add((fin, false, Natural lab))
  1183. p.flags.incl nimErrorFlagAccessed
  1184. if not isEmptyType(t.typ) and d.k == locNone:
  1185. d = getTemp(p, t.typ)
  1186. expr(p, t[0], d)
  1187. if 1 < t.len and t[1].kind == nkExceptBranch:
  1188. startBlock(p, "if (NIM_UNLIKELY(*nimErr_)) {$n")
  1189. else:
  1190. startBlock(p)
  1191. linefmt(p, cpsStmts, "LA$1_:;$n", [lab])
  1192. p.nestedTryStmts[^1].inExcept = true
  1193. var i = 1
  1194. while (i < t.len) and (t[i].kind == nkExceptBranch):
  1195. inc p.labels
  1196. let nextExcept = p.labels
  1197. p.nestedTryStmts[^1].label = nextExcept
  1198. # bug #4230: avoid false sharing between branches:
  1199. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1200. if t[i].len == 1:
  1201. # general except section:
  1202. if i > 1: lineF(p, cpsStmts, "else", [])
  1203. startBlock(p)
  1204. # we handled the exception, remember this:
  1205. linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
  1206. expr(p, t[i][0], d)
  1207. else:
  1208. var orExpr = newRopeAppender()
  1209. for j in 0..<t[i].len - 1:
  1210. assert(t[i][j].kind == nkType)
  1211. if orExpr.len != 0: orExpr.add("||")
  1212. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1213. if optTinyRtti in p.config.globalOptions:
  1214. let checkFor = $getObjDepth(t[i][j].typ)
  1215. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)",
  1216. [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
  1217. else:
  1218. let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
  1219. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1220. if i > 1: line(p, cpsStmts, "else ")
  1221. startBlock(p, "if ($1) {$n", [orExpr])
  1222. # we handled the exception, remember this:
  1223. linefmt(p, cpsStmts, "*nimErr_ = NIM_FALSE;$n", [])
  1224. expr(p, t[i][^1], d)
  1225. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1226. linefmt(p, cpsStmts, "LA$1_:;$n", [nextExcept])
  1227. endBlock(p)
  1228. inc(i)
  1229. discard pop(p.nestedTryStmts)
  1230. endBlock(p)
  1231. if i < t.len and t[i].kind == nkFinally:
  1232. startBlock(p)
  1233. if not bodyCanRaise(p, t[i][0]):
  1234. # this is an important optimization; most destroy blocks are detected not to raise an
  1235. # exception and so we help the C optimizer by not mutating nimErr_ pointlessly:
  1236. genStmts(p, t[i][0])
  1237. else:
  1238. # pretend we did handle the error for the safe execution of the 'finally' section:
  1239. p.procSec(cpsLocals).add(ropecg(p.module, "NIM_BOOL oldNimErrFin$1_;$n", [lab]))
  1240. linefmt(p, cpsStmts, "oldNimErrFin$1_ = *nimErr_; *nimErr_ = NIM_FALSE;$n", [lab])
  1241. genStmts(p, t[i][0])
  1242. # this is correct for all these cases:
  1243. # 1. finally is run during ordinary control flow
  1244. # 2. finally is run after 'except' block handling: these however set the
  1245. # error back to nil.
  1246. # 3. finally is run for exception handling code without any 'except'
  1247. # handler present or only handlers that did not match.
  1248. linefmt(p, cpsStmts, "*nimErr_ = oldNimErrFin$1_;$n", [lab])
  1249. endBlock(p)
  1250. raiseExit(p)
  1251. if hasExcept: inc p.withinTryWithExcept
  1252. proc genTrySetjmp(p: BProc, t: PNode, d: var TLoc) =
  1253. # code to generate:
  1254. #
  1255. # XXX: There should be a standard dispatch algorithm
  1256. # that's used both here and with multi-methods
  1257. #
  1258. # TSafePoint sp;
  1259. # pushSafePoint(&sp);
  1260. # sp.status = setjmp(sp.context);
  1261. # if (sp.status == 0) {
  1262. # myDiv(4, 9);
  1263. # popSafePoint();
  1264. # } else {
  1265. # popSafePoint();
  1266. # /* except DivisionByZero: */
  1267. # if (sp.status == DivisionByZero) {
  1268. # printf('Division by Zero\n');
  1269. # clearException();
  1270. # } else {
  1271. # clearException();
  1272. # }
  1273. # }
  1274. # {
  1275. # /* finally: */
  1276. # printf('fin!\n');
  1277. # }
  1278. # if (exception not cleared)
  1279. # propagateCurrentException();
  1280. #
  1281. if not isEmptyType(t.typ) and d.k == locNone:
  1282. d = getTemp(p, t.typ)
  1283. let quirkyExceptions = p.config.exc == excQuirky or
  1284. (t.kind == nkHiddenTryStmt and sfSystemModule in p.module.module.flags)
  1285. if not quirkyExceptions:
  1286. p.module.includeHeader("<setjmp.h>")
  1287. else:
  1288. p.flags.incl noSafePoints
  1289. genLineDir(p, t)
  1290. cgsym(p.module, "Exception")
  1291. var safePoint: Rope = ""
  1292. if not quirkyExceptions:
  1293. safePoint = getTempName(p.module)
  1294. linefmt(p, cpsLocals, "#TSafePoint $1;$n", [safePoint])
  1295. linefmt(p, cpsStmts, "#pushSafePoint(&$1);$n", [safePoint])
  1296. if isDefined(p.config, "nimStdSetjmp"):
  1297. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1298. elif isDefined(p.config, "nimSigSetjmp"):
  1299. linefmt(p, cpsStmts, "$1.status = sigsetjmp($1.context, 0);$n", [safePoint])
  1300. elif isDefined(p.config, "nimBuiltinSetjmp"):
  1301. linefmt(p, cpsStmts, "$1.status = __builtin_setjmp($1.context);$n", [safePoint])
  1302. elif isDefined(p.config, "nimRawSetjmp"):
  1303. if isDefined(p.config, "mswindows"):
  1304. if isDefined(p.config, "vcc") or isDefined(p.config, "clangcl"):
  1305. # For the vcc compiler, use `setjmp()` with one argument.
  1306. # See https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/setjmp?view=msvc-170
  1307. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1308. else:
  1309. # The Windows `_setjmp()` takes two arguments, with the second being an
  1310. # undocumented buffer used by the SEH mechanism for stack unwinding.
  1311. # Mingw-w64 has been trying to get it right for years, but it's still
  1312. # prone to stack corruption during unwinding, so we disable that by setting
  1313. # it to NULL.
  1314. # More details: https://github.com/status-im/nimbus-eth2/issues/3121
  1315. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context, 0);$n", [safePoint])
  1316. else:
  1317. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", [safePoint])
  1318. else:
  1319. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", [safePoint])
  1320. lineCg(p, cpsStmts, "if ($1.status == 0) {$n", [safePoint])
  1321. let fin = if t[^1].kind == nkFinally: t[^1] else: nil
  1322. p.nestedTryStmts.add((fin, quirkyExceptions, 0.Natural))
  1323. expr(p, t[0], d)
  1324. if not quirkyExceptions:
  1325. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  1326. lineCg(p, cpsStmts, "}$n", [])
  1327. startBlock(p, "else {$n")
  1328. linefmt(p, cpsStmts, "#popSafePoint();$n", [])
  1329. genRestoreFrameAfterException(p)
  1330. elif 1 < t.len and t[1].kind == nkExceptBranch:
  1331. startBlock(p, "if (#nimBorrowCurrentException()) {$n")
  1332. else:
  1333. startBlock(p)
  1334. p.nestedTryStmts[^1].inExcept = true
  1335. var i = 1
  1336. while (i < t.len) and (t[i].kind == nkExceptBranch):
  1337. # bug #4230: avoid false sharing between branches:
  1338. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  1339. if t[i].len == 1:
  1340. # general except section:
  1341. if i > 1: lineF(p, cpsStmts, "else", [])
  1342. startBlock(p)
  1343. if not quirkyExceptions:
  1344. linefmt(p, cpsStmts, "$1.status = 0;$n", [safePoint])
  1345. expr(p, t[i][0], d)
  1346. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1347. endBlock(p)
  1348. else:
  1349. var orExpr = newRopeAppender()
  1350. for j in 0..<t[i].len - 1:
  1351. assert(t[i][j].kind == nkType)
  1352. if orExpr.len != 0: orExpr.add("||")
  1353. let memberName = if p.module.compileToCpp: "m_type" else: "Sup.m_type"
  1354. if optTinyRtti in p.config.globalOptions:
  1355. let checkFor = $getObjDepth(t[i][j].typ)
  1356. appcg(p.module, orExpr, "#isObjDisplayCheck(#nimBorrowCurrentException()->$1, $2, $3)",
  1357. [memberName, checkFor, $genDisplayElem(MD5Digest(hashType(t[i][j].typ, p.config)))])
  1358. else:
  1359. let checkFor = genTypeInfoV1(p.module, t[i][j].typ, t[i][j].info)
  1360. appcg(p.module, orExpr, "#isObj(#nimBorrowCurrentException()->$1, $2)", [memberName, checkFor])
  1361. if i > 1: line(p, cpsStmts, "else ")
  1362. startBlock(p, "if ($1) {$n", [orExpr])
  1363. if not quirkyExceptions:
  1364. linefmt(p, cpsStmts, "$1.status = 0;$n", [safePoint])
  1365. expr(p, t[i][^1], d)
  1366. linefmt(p, cpsStmts, "#popCurrentException();$n", [])
  1367. endBlock(p)
  1368. inc(i)
  1369. discard pop(p.nestedTryStmts)
  1370. endBlock(p) # end of else block
  1371. if i < t.len and t[i].kind == nkFinally:
  1372. p.finallySafePoints.add(safePoint)
  1373. startBlock(p)
  1374. genStmts(p, t[i][0])
  1375. # pretend we handled the exception in a 'finally' so that we don't
  1376. # re-raise the unhandled one but instead keep the old one (it was
  1377. # not popped either):
  1378. if not quirkyExceptions and getCompilerProc(p.module.g.graph, "nimLeaveFinally") != nil:
  1379. linefmt(p, cpsStmts, "if ($1.status != 0) #nimLeaveFinally();$n", [safePoint])
  1380. endBlock(p)
  1381. discard pop(p.finallySafePoints)
  1382. if not quirkyExceptions:
  1383. linefmt(p, cpsStmts, "if ($1.status != 0) #reraiseException();$n", [safePoint])
  1384. proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false; result: var Rope) =
  1385. var res = ""
  1386. let offset =
  1387. if isAsmStmt: 1 # first son is pragmas
  1388. else: 0
  1389. for i in offset..<t.len:
  1390. let it = t[i]
  1391. case it.kind
  1392. of nkStrLit..nkTripleStrLit:
  1393. res.add(it.strVal)
  1394. of nkSym:
  1395. var sym = it.sym
  1396. if sym.kind in {skProc, skFunc, skIterator, skMethod}:
  1397. var a: TLoc = initLocExpr(p, it)
  1398. res.add($rdLoc(a))
  1399. elif sym.kind == skType:
  1400. res.add($getTypeDesc(p.module, sym.typ))
  1401. else:
  1402. discard getTypeDesc(p.module, skipTypes(sym.typ, abstractPtrs))
  1403. fillBackendName(p.module, sym)
  1404. res.add($sym.loc.r)
  1405. of nkTypeOfExpr:
  1406. res.add($getTypeDesc(p.module, it.typ))
  1407. else:
  1408. discard getTypeDesc(p.module, skipTypes(it.typ, abstractPtrs))
  1409. var a: TLoc = initLocExpr(p, it)
  1410. res.add($a.rdLoc)
  1411. if isAsmStmt and hasGnuAsm in CC[p.config.cCompiler].props:
  1412. for x in splitLines(res):
  1413. var j = 0
  1414. while j < x.len and x[j] in {' ', '\t'}: inc(j)
  1415. if j < x.len:
  1416. if x[j] in {'"', ':'}:
  1417. # don't modify the line if already in quotes or
  1418. # some clobber register list:
  1419. result.add(x); result.add("\L")
  1420. else:
  1421. # ignore empty lines
  1422. result.add("\"")
  1423. result.add(x.replace("\"", "\\\""))
  1424. result.add("\\n\"\n")
  1425. else:
  1426. res.add("\L")
  1427. result.add res.rope
  1428. proc genAsmStmt(p: BProc, t: PNode) =
  1429. assert(t.kind == nkAsmStmt)
  1430. genLineDir(p, t)
  1431. var s = newRopeAppender()
  1432. var asmSyntax = ""
  1433. if (let p = t[0]; p.kind == nkPragma):
  1434. for i in p:
  1435. if whichPragma(i) == wAsmSyntax:
  1436. asmSyntax = i[1].strVal
  1437. if asmSyntax != "" and
  1438. not (
  1439. asmSyntax == "gcc" and hasGnuAsm in CC[p.config.cCompiler].props or
  1440. asmSyntax == "vcc" and hasGnuAsm notin CC[p.config.cCompiler].props):
  1441. localError(
  1442. p.config, t.info,
  1443. "Your compiler does not support the specified inline assembler")
  1444. genAsmOrEmitStmt(p, t, isAsmStmt=true, s)
  1445. # see bug #2362, "top level asm statements" seem to be a mis-feature
  1446. # but even if we don't do this, the example in #2362 cannot possibly
  1447. # work:
  1448. if p.prc == nil:
  1449. # top level asm statement?
  1450. p.module.s[cfsProcHeaders].add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
  1451. else:
  1452. addIndent p, p.s(cpsStmts)
  1453. p.s(cpsStmts).add runtimeFormat(CC[p.config.cCompiler].asmStmtFrmt, [s])
  1454. proc determineSection(n: PNode): TCFileSection =
  1455. result = cfsProcHeaders
  1456. if n.len >= 1 and n[0].kind in {nkStrLit..nkTripleStrLit}:
  1457. let sec = n[0].strVal
  1458. if sec.startsWith("/*TYPESECTION*/"): result = cfsForwardTypes # TODO WORKAROUND
  1459. elif sec.startsWith("/*VARSECTION*/"): result = cfsVars
  1460. elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders
  1461. proc genEmit(p: BProc, t: PNode) =
  1462. var s = newRopeAppender()
  1463. genAsmOrEmitStmt(p, t[1], false, s)
  1464. if p.prc == nil:
  1465. # top level emit pragma?
  1466. let section = determineSection(t[1])
  1467. genCLineDir(p.module.s[section], t.info, p.config)
  1468. p.module.s[section].add(s)
  1469. else:
  1470. genLineDir(p, t)
  1471. line(p, cpsStmts, s)
  1472. proc genPragma(p: BProc, n: PNode) =
  1473. for i in 0..<n.len:
  1474. let it = n[i]
  1475. case whichPragma(it)
  1476. of wEmit: genEmit(p, it)
  1477. of wPush:
  1478. processPushBackendOption(p.optionsStack, p.options, n, i+1)
  1479. of wPop:
  1480. processPopBackendOption(p.optionsStack, p.options)
  1481. else: discard
  1482. proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
  1483. field: PSym) =
  1484. var t = skipTypes(objtype, abstractVar)
  1485. assert t.kind == tyObject
  1486. discard genTypeInfoV1(p.module, t, a.lode.info)
  1487. if not containsOrIncl(p.module.declaredThings, field.id):
  1488. appcg(p.module, cfsVars, "extern $1",
  1489. [discriminatorTableDecl(p.module, t, field)])
  1490. var lit = newRopeAppender()
  1491. intLiteral(toInt64(lengthOrd(p.config, field.typ))+1, lit)
  1492. lineCg(p, cpsStmts,
  1493. "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n",
  1494. [rdLoc(a), rdLoc(tmp), discriminatorTableName(p.module, t, field),
  1495. lit])
  1496. if p.config.exc == excGoto:
  1497. raiseExit(p)
  1498. when false:
  1499. proc genCaseObjDiscMapping(p: BProc, e: PNode, t: PType, field: PSym; d: var TLoc) =
  1500. const ObjDiscMappingProcSlot = -5
  1501. var theProc: PSym = nil
  1502. for idx, p in items(t.methods):
  1503. if idx == ObjDiscMappingProcSlot:
  1504. theProc = p
  1505. break
  1506. if theProc == nil:
  1507. theProc = genCaseObjDiscMapping(t, field, e.info, p.module.g.graph, p.module.idgen)
  1508. t.methods.add((ObjDiscMappingProcSlot, theProc))
  1509. var call = newNodeIT(nkCall, e.info, getSysType(p.module.g.graph, e.info, tyUInt8))
  1510. call.add newSymNode(theProc)
  1511. call.add e
  1512. expr(p, call, d)
  1513. proc asgnFieldDiscriminant(p: BProc, e: PNode) =
  1514. var dotExpr = e[0]
  1515. if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr[0]
  1516. var a = initLocExpr(p, e[0])
  1517. var tmp: TLoc = getTemp(p, a.t)
  1518. expr(p, e[1], tmp)
  1519. if p.inUncheckedAssignSection == 0:
  1520. let field = dotExpr[1].sym
  1521. genDiscriminantCheck(p, a, tmp, dotExpr[0].typ, field)
  1522. message(p.config, e.info, warnCaseTransition)
  1523. genAssignment(p, a, tmp, {})
  1524. proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
  1525. if e[0].kind == nkSym and sfGoto in e[0].sym.flags:
  1526. genLineDir(p, e)
  1527. genGotoVar(p, e[1])
  1528. elif optFieldCheck in p.options and isDiscriminantField(e[0]):
  1529. genLineDir(p, e)
  1530. asgnFieldDiscriminant(p, e)
  1531. else:
  1532. let le = e[0]
  1533. let ri = e[1]
  1534. var a: TLoc = initLoc(locNone, le, OnUnknown)
  1535. discard getTypeDesc(p.module, le.typ.skipTypes(skipPtrs), dkVar)
  1536. a.flags.incl(lfEnforceDeref)
  1537. a.flags.incl(lfPrepareForMutation)
  1538. genLineDir(p, le) # it can be a nkBracketExpr, which may raise
  1539. expr(p, le, a)
  1540. a.flags.excl(lfPrepareForMutation)
  1541. if fastAsgn: incl(a.flags, lfNoDeepCopy)
  1542. assert(a.t != nil)
  1543. genLineDir(p, ri)
  1544. loadInto(p, le, ri, a)
  1545. proc genStmts(p: BProc, t: PNode) =
  1546. var a: TLoc = default(TLoc)
  1547. let isPush = p.config.hasHint(hintExtendedContext)
  1548. if isPush: pushInfoContext(p.config, t.info)
  1549. expr(p, t, a)
  1550. if isPush: popInfoContext(p.config)
  1551. internalAssert p.config, a.k in {locNone, locTemp, locLocalVar, locExpr}