ccgstmts.nim 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  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 registerGcRoot(p: BProc, v: PSym) =
  16. if p.config.selectedGC in {gcMarkAndSweep, gcDestructors, gcV2, gcRefc} and
  17. containsGarbageCollectedRef(v.loc.t):
  18. # we register a specialized marked proc here; this has the advantage
  19. # that it works out of the box for thread local storage then :-)
  20. let prc = genTraverseProcForGlobal(p.module, v, v.info)
  21. if sfThread in v.flags:
  22. appcg(p.module, p.module.initProc.procSec(cpsInit),
  23. "#nimRegisterThreadLocalMarker($1);$n", [prc])
  24. else:
  25. appcg(p.module, p.module.initProc.procSec(cpsInit),
  26. "#nimRegisterGlobalMarker($1);$n", [prc])
  27. proc isAssignedImmediately(conf: ConfigRef; n: PNode): bool {.inline.} =
  28. if n.kind == nkEmpty: return false
  29. if isInvalidReturnType(conf, n.typ):
  30. # var v = f()
  31. # is transformed into: var v; f(addr v)
  32. # where 'f' **does not** initialize the result!
  33. return false
  34. result = true
  35. proc inExceptBlockLen(p: BProc): int =
  36. for x in p.nestedTryStmts:
  37. if x.inExcept: result.inc
  38. proc genVarTuple(p: BProc, n: PNode) =
  39. var tup, field: TLoc
  40. if n.kind != nkVarTuple: internalError(p.config, n.info, "genVarTuple")
  41. var L = sonsLen(n)
  42. # if we have a something that's been captured, use the lowering instead:
  43. for i in countup(0, L-3):
  44. if n[i].kind != nkSym:
  45. genStmts(p, lowerTupleUnpacking(p.module.g.graph, n, p.prc))
  46. return
  47. genLineDir(p, n)
  48. initLocExpr(p, n.sons[L-1], tup)
  49. var t = tup.t.skipTypes(abstractInst)
  50. for i in countup(0, L-3):
  51. let vn = n.sons[i]
  52. let v = vn.sym
  53. if sfCompileTime in v.flags: continue
  54. if sfGlobal in v.flags:
  55. assignGlobalVar(p, vn)
  56. genObjectInit(p, cpsInit, v.typ, v.loc, true)
  57. registerGcRoot(p, v)
  58. else:
  59. assignLocalVar(p, vn)
  60. initLocalVar(p, v, immediateAsgn=isAssignedImmediately(p.config, n[L-1]))
  61. initLoc(field, locExpr, vn, tup.storage)
  62. if t.kind == tyTuple:
  63. field.r = "$1.Field$2" % [rdLoc(tup), rope(i)]
  64. else:
  65. if t.n.sons[i].kind != nkSym: internalError(p.config, n.info, "genVarTuple")
  66. field.r = "$1.$2" % [rdLoc(tup), mangleRecFieldName(p.module, t.n.sons[i].sym)]
  67. putLocIntoDest(p, v.loc, field)
  68. proc genDeref(p: BProc, e: PNode, d: var TLoc; enforceDeref=false)
  69. proc loadInto(p: BProc, le, ri: PNode, a: var TLoc) {.inline.} =
  70. if ri.kind in nkCallKinds and (ri.sons[0].kind != nkSym or
  71. ri.sons[0].sym.magic == mNone):
  72. genAsgnCall(p, le, ri, a)
  73. elif ri.kind in {nkDerefExpr, nkHiddenDeref}:
  74. # this is a hacky way to fix #1181 (tmissingderef)::
  75. #
  76. # var arr1 = cast[ptr array[4, int8]](addr foo)[]
  77. #
  78. # However, fixing this properly really requires modelling 'array' as
  79. # a 'struct' in C to preserve dereferencing semantics completely. Not
  80. # worth the effort until version 1.0 is out.
  81. genDeref(p, ri, a, enforceDeref=true)
  82. else:
  83. expr(p, ri, a)
  84. proc startBlock(p: BProc, start: FormatStr = "{$n",
  85. args: varargs[Rope]): int {.discardable.} =
  86. lineCg(p, cpsStmts, start, args)
  87. inc(p.labels)
  88. result = len(p.blocks)
  89. setLen(p.blocks, result + 1)
  90. p.blocks[result].id = p.labels
  91. p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16
  92. p.blocks[result].nestedExceptStmts = p.inExceptBlockLen.int16
  93. proc assignLabel(b: var TBlock): Rope {.inline.} =
  94. b.label = "LA" & b.id.rope
  95. result = b.label
  96. proc blockBody(b: var TBlock): Rope =
  97. result = b.sections[cpsLocals]
  98. if b.frameLen > 0:
  99. result.addf("FR_.len+=$1;$n", [b.frameLen.rope])
  100. result.add(b.sections[cpsInit])
  101. result.add(b.sections[cpsStmts])
  102. proc endBlock(p: BProc, blockEnd: Rope) =
  103. let topBlock = p.blocks.len-1
  104. # the block is merged into the parent block
  105. add(p.blocks[topBlock-1].sections[cpsStmts], p.blocks[topBlock].blockBody)
  106. setLen(p.blocks, topBlock)
  107. # this is done after the block is popped so $n is
  108. # properly indented when pretty printing is enabled
  109. line(p, cpsStmts, blockEnd)
  110. proc endBlock(p: BProc) =
  111. let topBlock = p.blocks.len - 1
  112. var blockEnd = if p.blocks[topBlock].label != nil:
  113. ropecg(p.module, "} $1: ;$n", p.blocks[topBlock].label)
  114. else:
  115. ~"}$n"
  116. let frameLen = p.blocks[topBlock].frameLen
  117. if frameLen > 0:
  118. blockEnd.addf("FR_.len-=$1;$n", [frameLen.rope])
  119. endBlock(p, blockEnd)
  120. proc genSimpleBlock(p: BProc, stmts: PNode) {.inline.} =
  121. startBlock(p)
  122. genStmts(p, stmts)
  123. endBlock(p)
  124. proc exprBlock(p: BProc, n: PNode, d: var TLoc) =
  125. startBlock(p)
  126. expr(p, n, d)
  127. endBlock(p)
  128. template preserveBreakIdx(body: untyped): untyped =
  129. var oldBreakIdx = p.breakIdx
  130. body
  131. p.breakIdx = oldBreakIdx
  132. proc genState(p: BProc, n: PNode) =
  133. internalAssert p.config, n.len == 1
  134. let n0 = n[0]
  135. if n0.kind == nkIntLit:
  136. let idx = n.sons[0].intVal
  137. linefmt(p, cpsStmts, "STATE$1: ;$n", idx.rope)
  138. elif n0.kind == nkStrLit:
  139. linefmt(p, cpsStmts, "$1: ;$n", n0.strVal.rope)
  140. proc blockLeaveActions(p: BProc, howManyTrys, howManyExcepts: int) =
  141. # Called by return and break stmts.
  142. # Deals with issues faced when jumping out of try/except/finally stmts,
  143. var stack = newSeq[tuple[n: PNode, inExcept: bool]](0)
  144. for i in countup(1, howManyTrys):
  145. let tryStmt = p.nestedTryStmts.pop
  146. if not p.module.compileToCpp or optNoCppExceptions in p.config.globalOptions:
  147. # Pop safe points generated by try
  148. if not tryStmt.inExcept:
  149. linefmt(p, cpsStmts, "#popSafePoint();$n")
  150. # Pop this try-stmt of the list of nested trys
  151. # so we don't infinite recurse on it in the next step.
  152. stack.add(tryStmt)
  153. # Find finally-stmt for this try-stmt
  154. # and generate a copy of its sons
  155. var finallyStmt = lastSon(tryStmt.n)
  156. if finallyStmt.kind == nkFinally:
  157. genStmts(p, finallyStmt.sons[0])
  158. # push old elements again:
  159. for i in countdown(howManyTrys-1, 0):
  160. p.nestedTryStmts.add(stack[i])
  161. if not p.module.compileToCpp or optNoCppExceptions in p.config.globalOptions:
  162. # Pop exceptions that was handled by the
  163. # except-blocks we are in
  164. for i in countdown(howManyExcepts-1, 0):
  165. linefmt(p, cpsStmts, "#popCurrentException();$n")
  166. proc genGotoState(p: BProc, n: PNode) =
  167. # we resist the temptation to translate it into duff's device as it later
  168. # will be translated into computed gotos anyway for GCC at least:
  169. # switch (x.state) {
  170. # case 0: goto STATE0;
  171. # ...
  172. var a: TLoc
  173. initLocExpr(p, n.sons[0], a)
  174. lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)])
  175. p.beforeRetNeeded = true
  176. lineF(p, cpsStmts, "case -1:$n", [])
  177. blockLeaveActions(p,
  178. howManyTrys = p.nestedTryStmts.len,
  179. howManyExcepts = p.inExceptBlockLen)
  180. lineF(p, cpsStmts, " goto BeforeRet_;$n", [])
  181. var statesCounter = lastOrd(p.config, n.sons[0].typ)
  182. if n.len >= 2 and n[1].kind == nkIntLit:
  183. statesCounter = n[1].intVal
  184. let prefix = if n.len == 3 and n[2].kind == nkStrLit: n[2].strVal.rope
  185. else: rope"STATE"
  186. for i in 0i64 .. statesCounter:
  187. lineF(p, cpsStmts, "case $2: goto $1$2;$n", [prefix, rope(i)])
  188. lineF(p, cpsStmts, "}$n", [])
  189. proc genBreakState(p: BProc, n: PNode, d: var TLoc) =
  190. var a: TLoc
  191. initLoc(d, locExpr, n, OnUnknown)
  192. if n.sons[0].kind == nkClosure:
  193. initLocExpr(p, n.sons[0].sons[1], a)
  194. d.r = "(((NI*) $1)[1] < 0)" % [rdLoc(a)]
  195. else:
  196. initLocExpr(p, n.sons[0], a)
  197. # the environment is guaranteed to contain the 'state' field at offset 1:
  198. d.r = "((((NI*) $1.ClE_0)[1]) < 0)" % [rdLoc(a)]
  199. proc genGotoVar(p: BProc; value: PNode) =
  200. if value.kind notin {nkCharLit..nkUInt64Lit}:
  201. localError(p.config, value.info, "'goto' target must be a literal value")
  202. else:
  203. lineF(p, cpsStmts, "goto NIMSTATE_$#;$n", [value.intVal.rope])
  204. proc genSingleVar(p: BProc, a: PNode) =
  205. let vn = a.sons[0]
  206. let v = vn.sym
  207. if sfCompileTime in v.flags: return
  208. if sfGoto in v.flags:
  209. # translate 'var state {.goto.} = X' into 'goto LX':
  210. genGotoVar(p, a.sons[2])
  211. return
  212. var targetProc = p
  213. if sfGlobal in v.flags:
  214. if v.flags * {sfImportc, sfExportc} == {sfImportc} and
  215. a.sons[2].kind == nkEmpty and
  216. v.loc.flags * {lfHeader, lfNoDecl} != {}:
  217. return
  218. if sfPure in v.flags:
  219. # v.owner.kind != skModule:
  220. targetProc = p.module.preInitProc
  221. assignGlobalVar(targetProc, vn)
  222. # XXX: be careful here.
  223. # Global variables should not be zeromem-ed within loops
  224. # (see bug #20).
  225. # That's why we are doing the construction inside the preInitProc.
  226. # genObjectInit relies on the C runtime's guarantees that
  227. # global variables will be initialized to zero.
  228. var loc = v.loc
  229. # When the native TLS is unavailable, a global thread-local variable needs
  230. # one more layer of indirection in order to access the TLS block.
  231. # Only do this for complex types that may need a call to `objectInit`
  232. if sfThread in v.flags and emulatedThreadVars(p.config) and
  233. isComplexValueType(v.typ):
  234. initLocExprSingleUse(p.module.preInitProc, vn, loc)
  235. genObjectInit(p.module.preInitProc, cpsInit, v.typ, loc, true)
  236. # Alternative construction using default constructor (which may zeromem):
  237. # if sfImportc notin v.flags: constructLoc(p.module.preInitProc, v.loc)
  238. if sfExportc in v.flags and p.module.g.generatedHeader != nil:
  239. genVarPrototype(p.module.g.generatedHeader, vn)
  240. registerGcRoot(p, v)
  241. else:
  242. let value = a.sons[2]
  243. let imm = isAssignedImmediately(p.config, value)
  244. if imm and p.module.compileToCpp and p.splitDecls == 0 and
  245. not containsHiddenPointer(v.typ):
  246. # C++ really doesn't like things like 'Foo f; f = x' as that invokes a
  247. # parameterless constructor followed by an assignment operator. So we
  248. # generate better code here: 'Foo f = x;'
  249. genLineDir(p, a)
  250. let decl = localVarDecl(p, vn)
  251. var tmp: TLoc
  252. if value.kind in nkCallKinds and value[0].kind == nkSym and
  253. sfConstructor in value[0].sym.flags:
  254. var params: Rope
  255. let typ = skipTypes(value.sons[0].typ, abstractInst)
  256. assert(typ.kind == tyProc)
  257. for i in 1..<value.len:
  258. if params != nil: params.add(~", ")
  259. assert(sonsLen(typ) == sonsLen(typ.n))
  260. add(params, genOtherArg(p, value, i, typ))
  261. if params == nil:
  262. lineF(p, cpsStmts, "$#;$n", [decl])
  263. else:
  264. lineF(p, cpsStmts, "$#($#);$n", [decl, params])
  265. else:
  266. initLocExprSingleUse(p, value, tmp)
  267. lineF(p, cpsStmts, "$# = $#;$n", [decl, tmp.rdLoc])
  268. return
  269. assignLocalVar(p, vn)
  270. initLocalVar(p, v, imm)
  271. if a.sons[2].kind != nkEmpty:
  272. genLineDir(targetProc, a)
  273. loadInto(targetProc, a.sons[0], a.sons[2], v.loc)
  274. proc genClosureVar(p: BProc, a: PNode) =
  275. var immediateAsgn = a.sons[2].kind != nkEmpty
  276. if immediateAsgn:
  277. var v: TLoc
  278. initLocExpr(p, a.sons[0], v)
  279. genLineDir(p, a)
  280. loadInto(p, a.sons[0], a.sons[2], v)
  281. proc genVarStmt(p: BProc, n: PNode) =
  282. for it in n.sons:
  283. if it.kind == nkCommentStmt: continue
  284. if it.kind == nkIdentDefs:
  285. # can be a lifted var nowadays ...
  286. if it.sons[0].kind == nkSym:
  287. genSingleVar(p, it)
  288. else:
  289. genClosureVar(p, it)
  290. else:
  291. genVarTuple(p, it)
  292. proc genIf(p: BProc, n: PNode, d: var TLoc) =
  293. #
  294. # { if (!expr1) goto L1;
  295. # thenPart }
  296. # goto LEnd
  297. # L1:
  298. # { if (!expr2) goto L2;
  299. # thenPart2 }
  300. # goto LEnd
  301. # L2:
  302. # { elsePart }
  303. # Lend:
  304. var
  305. a: TLoc
  306. lelse: TLabel
  307. if not isEmptyType(n.typ) and d.k == locNone:
  308. getTemp(p, n.typ, d)
  309. genLineDir(p, n)
  310. let lend = getLabel(p)
  311. for it in n.sons:
  312. # bug #4230: avoid false sharing between branches:
  313. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  314. if it.len == 2:
  315. startBlock(p)
  316. initLocExprSingleUse(p, it.sons[0], a)
  317. lelse = getLabel(p)
  318. inc(p.labels)
  319. lineF(p, cpsStmts, "if (!$1) goto $2;$n",
  320. [rdLoc(a), lelse])
  321. if p.module.compileToCpp:
  322. # avoid "jump to label crosses initialization" error:
  323. add(p.s(cpsStmts), "{")
  324. expr(p, it.sons[1], d)
  325. add(p.s(cpsStmts), "}")
  326. else:
  327. expr(p, it.sons[1], d)
  328. endBlock(p)
  329. if sonsLen(n) > 1:
  330. lineF(p, cpsStmts, "goto $1;$n", [lend])
  331. fixLabel(p, lelse)
  332. elif it.len == 1:
  333. startBlock(p)
  334. expr(p, it.sons[0], d)
  335. endBlock(p)
  336. else: internalError(p.config, n.info, "genIf()")
  337. if sonsLen(n) > 1: fixLabel(p, lend)
  338. proc genReturnStmt(p: BProc, t: PNode) =
  339. if nfPreventCg in t.flags: return
  340. p.beforeRetNeeded = true
  341. genLineDir(p, t)
  342. if (t.sons[0].kind != nkEmpty): genStmts(p, t.sons[0])
  343. blockLeaveActions(p,
  344. howManyTrys = p.nestedTryStmts.len,
  345. howManyExcepts = p.inExceptBlockLen)
  346. if (p.finallySafePoints.len > 0):
  347. # If we're in a finally block, and we came here by exception
  348. # consume it before we return.
  349. var safePoint = p.finallySafePoints[p.finallySafePoints.len-1]
  350. linefmt(p, cpsStmts, "if ($1.status != 0) #popCurrentException();$n", safePoint)
  351. lineF(p, cpsStmts, "goto BeforeRet_;$n", [])
  352. proc genGotoForCase(p: BProc; caseStmt: PNode) =
  353. for i in 1 ..< caseStmt.len:
  354. startBlock(p)
  355. let it = caseStmt.sons[i]
  356. for j in 0 .. it.len-2:
  357. if it.sons[j].kind == nkRange:
  358. localError(p.config, it.info, "range notation not available for computed goto")
  359. return
  360. let val = getOrdValue(it.sons[j])
  361. lineF(p, cpsStmts, "NIMSTATE_$#:$n", [val.rope])
  362. genStmts(p, it.lastSon)
  363. endBlock(p)
  364. iterator fieldValuePairs(n: PNode): tuple[memberSym, valueSym: PNode] =
  365. assert(n.kind in {nkLetSection, nkVarSection})
  366. for identDefs in n:
  367. if identDefs.kind == nkIdentDefs:
  368. let valueSym = identDefs[^1]
  369. for i in 0 ..< identDefs.len-2:
  370. let memberSym = identDefs[i]
  371. yield((memberSym: memberSym, valueSym: valueSym))
  372. proc genComputedGoto(p: BProc; n: PNode) =
  373. # first pass: Generate array of computed labels:
  374. var casePos = -1
  375. var arraySize: int
  376. for i in 0 ..< n.len:
  377. let it = n.sons[i]
  378. if it.kind == nkCaseStmt:
  379. if lastSon(it).kind != nkOfBranch:
  380. localError(p.config, it.info,
  381. "case statement must be exhaustive for computed goto"); return
  382. casePos = i
  383. if enumHasHoles(it.sons[0].typ):
  384. localError(p.config, it.info,
  385. "case statement cannot work on enums with holes for computed goto"); return
  386. let aSize = lengthOrd(p.config, it.sons[0].typ)
  387. if aSize > 10_000:
  388. localError(p.config, it.info,
  389. "case statement has too many cases for computed goto"); return
  390. arraySize = aSize.int
  391. if firstOrd(p.config, it.sons[0].typ) != 0:
  392. localError(p.config, it.info,
  393. "case statement has to start at 0 for computed goto"); return
  394. if casePos < 0:
  395. localError(p.config, n.info, "no case statement found for computed goto"); return
  396. var id = p.labels+1
  397. inc p.labels, arraySize+1
  398. let tmp = "TMP$1_" % [id.rope]
  399. var gotoArray = "static void* $#[$#] = {" % [tmp, arraySize.rope]
  400. for i in 1..arraySize-1:
  401. gotoArray.addf("&&TMP$#_, ", [rope(id+i)])
  402. gotoArray.addf("&&TMP$#_};$n", [rope(id+arraySize)])
  403. line(p, cpsLocals, gotoArray)
  404. for j in 0 ..< casePos:
  405. genStmts(p, n.sons[j])
  406. let caseStmt = n.sons[casePos]
  407. var a: TLoc
  408. initLocExpr(p, caseStmt.sons[0], a)
  409. # first goto:
  410. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  411. for i in 1 ..< caseStmt.len:
  412. startBlock(p)
  413. let it = caseStmt.sons[i]
  414. for j in 0 .. it.len-2:
  415. if it.sons[j].kind == nkRange:
  416. localError(p.config, it.info, "range notation not available for computed goto")
  417. return
  418. let val = getOrdValue(it.sons[j])
  419. lineF(p, cpsStmts, "TMP$#_:$n", [intLiteral(val+id+1)])
  420. genStmts(p, it.lastSon)
  421. for j in casePos+1 ..< n.sons.len:
  422. genStmts(p, n.sons[j])
  423. for j in 0 ..< casePos:
  424. # prevent new local declarations
  425. # compile declarations as assignments
  426. let it = n.sons[j]
  427. if it.kind in {nkLetSection, nkVarSection}:
  428. let asgn = copyNode(it)
  429. asgn.kind = nkAsgn
  430. asgn.sons.setLen 2
  431. for sym, value in it.fieldValuePairs:
  432. if value.kind != nkEmpty:
  433. asgn.sons[0] = sym
  434. asgn.sons[1] = value
  435. genStmts(p, asgn)
  436. else:
  437. genStmts(p, it)
  438. var a: TLoc
  439. initLocExpr(p, caseStmt.sons[0], a)
  440. lineF(p, cpsStmts, "goto *$#[$#];$n", [tmp, a.rdLoc])
  441. endBlock(p)
  442. for j in casePos+1 ..< n.sons.len:
  443. genStmts(p, n.sons[j])
  444. proc genWhileStmt(p: BProc, t: PNode) =
  445. # we don't generate labels here as for example GCC would produce
  446. # significantly worse code
  447. var
  448. a: TLoc
  449. assert(sonsLen(t) == 2)
  450. inc(p.withinLoop)
  451. genLineDir(p, t)
  452. preserveBreakIdx:
  453. var loopBody = t.sons[1]
  454. if loopBody.stmtsContainPragma(wComputedGoto) and
  455. hasComputedGoto in CC[p.config.cCompiler].props:
  456. # for closure support weird loop bodies are generated:
  457. if loopBody.len == 2 and loopBody.sons[0].kind == nkEmpty:
  458. loopBody = loopBody.sons[1]
  459. genComputedGoto(p, loopBody)
  460. else:
  461. p.breakIdx = startBlock(p, "while (1) {$n")
  462. p.blocks[p.breakIdx].isLoop = true
  463. initLocExpr(p, t.sons[0], a)
  464. if (t.sons[0].kind != nkIntLit) or (t.sons[0].intVal == 0):
  465. let label = assignLabel(p.blocks[p.breakIdx])
  466. lineF(p, cpsStmts, "if (!$1) goto $2;$n", [rdLoc(a), label])
  467. genStmts(p, loopBody)
  468. if optProfiler in p.options:
  469. # invoke at loop body exit:
  470. linefmt(p, cpsStmts, "#nimProfile();$n")
  471. endBlock(p)
  472. dec(p.withinLoop)
  473. proc genBlock(p: BProc, n: PNode, d: var TLoc) =
  474. # bug #4505: allocate the temp in the outer scope
  475. # so that it can escape the generated {}:
  476. if not isEmptyType(n.typ) and d.k == locNone:
  477. getTemp(p, n.typ, d)
  478. preserveBreakIdx:
  479. p.breakIdx = startBlock(p)
  480. if n.sons[0].kind != nkEmpty:
  481. # named block?
  482. assert(n.sons[0].kind == nkSym)
  483. var sym = n.sons[0].sym
  484. sym.loc.k = locOther
  485. sym.position = p.breakIdx+1
  486. expr(p, n.sons[1], d)
  487. endBlock(p)
  488. proc genParForStmt(p: BProc, t: PNode) =
  489. assert(sonsLen(t) == 3)
  490. inc(p.withinLoop)
  491. genLineDir(p, t)
  492. preserveBreakIdx:
  493. let forLoopVar = t.sons[0].sym
  494. var rangeA, rangeB: TLoc
  495. assignLocalVar(p, t.sons[0])
  496. #initLoc(forLoopVar.loc, locLocalVar, forLoopVar.typ, onStack)
  497. #discard mangleName(forLoopVar)
  498. let call = t.sons[1]
  499. initLocExpr(p, call.sons[1], rangeA)
  500. initLocExpr(p, call.sons[2], rangeB)
  501. lineF(p, cpsStmts, "#pragma omp $4$n" &
  502. "for ($1 = $2; $1 <= $3; ++$1)",
  503. [forLoopVar.loc.rdLoc,
  504. rangeA.rdLoc, rangeB.rdLoc,
  505. call.sons[3].getStr.rope])
  506. p.breakIdx = startBlock(p)
  507. p.blocks[p.breakIdx].isLoop = true
  508. genStmts(p, t.sons[2])
  509. endBlock(p)
  510. dec(p.withinLoop)
  511. proc genBreakStmt(p: BProc, t: PNode) =
  512. var idx = p.breakIdx
  513. if t.sons[0].kind != nkEmpty:
  514. # named break?
  515. assert(t.sons[0].kind == nkSym)
  516. var sym = t.sons[0].sym
  517. doAssert(sym.loc.k == locOther)
  518. idx = sym.position-1
  519. else:
  520. # an unnamed 'break' can only break a loop after 'transf' pass:
  521. while idx >= 0 and not p.blocks[idx].isLoop: dec idx
  522. if idx < 0 or not p.blocks[idx].isLoop:
  523. internalError(p.config, t.info, "no loop to break")
  524. let label = assignLabel(p.blocks[idx])
  525. blockLeaveActions(p,
  526. p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts,
  527. p.inExceptBlockLen - p.blocks[idx].nestedExceptStmts)
  528. genLineDir(p, t)
  529. lineF(p, cpsStmts, "goto $1;$n", [label])
  530. proc genRaiseStmt(p: BProc, t: PNode) =
  531. if p.module.compileToCpp:
  532. discard cgsym(p.module, "popCurrentExceptionEx")
  533. if p.nestedTryStmts.len > 0 and p.nestedTryStmts[^1].inExcept:
  534. # if the current try stmt have a finally block,
  535. # we must execute it before reraising
  536. var finallyBlock = p.nestedTryStmts[^1].n[^1]
  537. if finallyBlock.kind == nkFinally:
  538. genSimpleBlock(p, finallyBlock[0])
  539. if t[0].kind != nkEmpty:
  540. var a: TLoc
  541. initLocExprSingleUse(p, t[0], a)
  542. var e = rdLoc(a)
  543. var typ = skipTypes(t[0].typ, abstractPtrs)
  544. genLineDir(p, t)
  545. if isImportedException(typ, p.config):
  546. lineF(p, cpsStmts, "throw $1;$n", [e])
  547. else:
  548. lineCg(p, cpsStmts, "#raiseExceptionEx((#Exception*)$1, $2, $3, $4, $5);$n",
  549. [e, makeCString(typ.sym.name.s),
  550. makeCString(if p.prc != nil: p.prc.name.s else: p.module.module.name.s),
  551. makeCString(toFileName(p.config, t.info)), rope(toLinenumber(t.info))])
  552. else:
  553. genLineDir(p, t)
  554. # reraise the last exception:
  555. if p.module.compileToCpp and optNoCppExceptions notin p.config.globalOptions:
  556. line(p, cpsStmts, ~"throw;$n")
  557. else:
  558. linefmt(p, cpsStmts, "#reraiseException();$n")
  559. proc genCaseGenericBranch(p: BProc, b: PNode, e: TLoc,
  560. rangeFormat, eqFormat: FormatStr, labl: TLabel) =
  561. var
  562. x, y: TLoc
  563. var length = sonsLen(b)
  564. for i in countup(0, length - 2):
  565. if b.sons[i].kind == nkRange:
  566. initLocExpr(p, b.sons[i].sons[0], x)
  567. initLocExpr(p, b.sons[i].sons[1], y)
  568. lineCg(p, cpsStmts, rangeFormat,
  569. [rdCharLoc(e), rdCharLoc(x), rdCharLoc(y), labl])
  570. else:
  571. initLocExpr(p, b.sons[i], x)
  572. lineCg(p, cpsStmts, eqFormat, [rdCharLoc(e), rdCharLoc(x), labl])
  573. proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc,
  574. labId, until: int): TLabel =
  575. var lend = getLabel(p)
  576. for i in 1..until:
  577. # bug #4230: avoid false sharing between branches:
  578. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  579. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(labId + i)])
  580. if t.sons[i].kind == nkOfBranch:
  581. var length = sonsLen(t.sons[i])
  582. exprBlock(p, t.sons[i].sons[length - 1], d)
  583. lineF(p, cpsStmts, "goto $1;$n", [lend])
  584. else:
  585. exprBlock(p, t.sons[i].sons[0], d)
  586. result = lend
  587. proc genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc,
  588. rangeFormat, eqFormat: FormatStr,
  589. until: int, a: TLoc): TLabel =
  590. # generate a C-if statement for a Nim case statement
  591. var labId = p.labels
  592. for i in 1..until:
  593. inc(p.labels)
  594. if t.sons[i].kind == nkOfBranch: # else statement
  595. genCaseGenericBranch(p, t.sons[i], a, rangeFormat, eqFormat,
  596. "LA" & rope(p.labels) & "_")
  597. else:
  598. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  599. if until < t.len-1:
  600. inc(p.labels)
  601. var gotoTarget = p.labels
  602. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(gotoTarget)])
  603. result = genCaseSecondPass(p, t, d, labId, until)
  604. lineF(p, cpsStmts, "LA$1_: ;$n", [rope(gotoTarget)])
  605. else:
  606. result = genCaseSecondPass(p, t, d, labId, until)
  607. proc genCaseGeneric(p: BProc, t: PNode, d: var TLoc,
  608. rangeFormat, eqFormat: FormatStr) =
  609. var a: TLoc
  610. initLocExpr(p, t.sons[0], a)
  611. var lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, sonsLen(t)-1, a)
  612. fixLabel(p, lend)
  613. proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel,
  614. branches: var openArray[Rope]) =
  615. var x: TLoc
  616. var length = sonsLen(b)
  617. for i in countup(0, length - 2):
  618. assert(b.sons[i].kind != nkRange)
  619. initLocExpr(p, b.sons[i], x)
  620. assert(b.sons[i].kind in {nkStrLit..nkTripleStrLit})
  621. var j = int(hashString(p.config, b.sons[i].strVal) and high(branches))
  622. appcg(p.module, branches[j], "if (#eqStrings($1, $2)) goto $3;$n",
  623. [rdLoc(e), rdLoc(x), labl])
  624. proc genStringCase(p: BProc, t: PNode, d: var TLoc) =
  625. # count how many constant strings there are in the case:
  626. var strings = 0
  627. for i in countup(1, sonsLen(t) - 1):
  628. if t.sons[i].kind == nkOfBranch: inc(strings, sonsLen(t.sons[i]) - 1)
  629. if strings > stringCaseThreshold:
  630. var bitMask = math.nextPowerOfTwo(strings) - 1
  631. var branches: seq[Rope]
  632. newSeq(branches, bitMask + 1)
  633. var a: TLoc
  634. initLocExpr(p, t.sons[0], a) # fist pass: gnerate ifs+goto:
  635. var labId = p.labels
  636. for i in countup(1, sonsLen(t) - 1):
  637. inc(p.labels)
  638. if t.sons[i].kind == nkOfBranch:
  639. genCaseStringBranch(p, t.sons[i], a, "LA" & rope(p.labels) & "_",
  640. branches)
  641. else:
  642. # else statement: nothing to do yet
  643. # but we reserved a label, which we use later
  644. discard
  645. linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n",
  646. rdLoc(a), rope(bitMask))
  647. for j in countup(0, high(branches)):
  648. if branches[j] != nil:
  649. lineF(p, cpsStmts, "case $1: $n$2break;$n",
  650. [intLiteral(j), branches[j]])
  651. lineF(p, cpsStmts, "}$n", []) # else statement:
  652. if t.sons[sonsLen(t)-1].kind != nkOfBranch:
  653. lineF(p, cpsStmts, "goto LA$1_;$n", [rope(p.labels)])
  654. # third pass: generate statements
  655. var lend = genCaseSecondPass(p, t, d, labId, sonsLen(t)-1)
  656. fixLabel(p, lend)
  657. else:
  658. genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n")
  659. proc branchHasTooBigRange(b: PNode): bool =
  660. for i in countup(0, sonsLen(b)-2):
  661. # last son is block
  662. if (b.sons[i].kind == nkRange) and
  663. b.sons[i].sons[1].intVal - b.sons[i].sons[0].intVal > RangeExpandLimit:
  664. return true
  665. proc ifSwitchSplitPoint(p: BProc, n: PNode): int =
  666. for i in 1..n.len-1:
  667. var branch = n[i]
  668. var stmtBlock = lastSon(branch)
  669. if stmtBlock.stmtsContainPragma(wLinearScanEnd):
  670. result = i
  671. elif hasSwitchRange notin CC[p.config.cCompiler].props:
  672. if branch.kind == nkOfBranch and branchHasTooBigRange(branch):
  673. result = i
  674. proc genCaseRange(p: BProc, branch: PNode) =
  675. var length = branch.len
  676. for j in 0 .. length-2:
  677. if branch[j].kind == nkRange:
  678. if hasSwitchRange in CC[p.config.cCompiler].props:
  679. lineF(p, cpsStmts, "case $1 ... $2:$n", [
  680. genLiteral(p, branch[j][0]),
  681. genLiteral(p, branch[j][1])])
  682. else:
  683. var v = copyNode(branch[j][0])
  684. while v.intVal <= branch[j][1].intVal:
  685. lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, v)])
  686. inc(v.intVal)
  687. else:
  688. lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, branch[j])])
  689. proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) =
  690. # analyse 'case' statement:
  691. var splitPoint = ifSwitchSplitPoint(p, n)
  692. # generate if part (might be empty):
  693. var a: TLoc
  694. initLocExpr(p, n.sons[0], a)
  695. var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d,
  696. rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  697. eqFormat = "if ($1 == $2) goto $3;$n",
  698. splitPoint, a) else: nil
  699. # generate switch part (might be empty):
  700. if splitPoint+1 < n.len:
  701. lineF(p, cpsStmts, "switch ($1) {$n", [rdCharLoc(a)])
  702. var hasDefault = false
  703. for i in splitPoint+1 ..< n.len:
  704. # bug #4230: avoid false sharing between branches:
  705. if d.k == locTemp and isEmptyType(n.typ): d.k = locNone
  706. var branch = n[i]
  707. if branch.kind == nkOfBranch:
  708. genCaseRange(p, branch)
  709. else:
  710. # else part of case statement:
  711. lineF(p, cpsStmts, "default:$n", [])
  712. hasDefault = true
  713. exprBlock(p, branch.lastSon, d)
  714. lineF(p, cpsStmts, "break;$n", [])
  715. if (hasAssume in CC[p.config.cCompiler].props) and not hasDefault:
  716. lineF(p, cpsStmts, "default: __assume(0);$n", [])
  717. lineF(p, cpsStmts, "}$n", [])
  718. if lend != nil: fixLabel(p, lend)
  719. proc genCase(p: BProc, t: PNode, d: var TLoc) =
  720. genLineDir(p, t)
  721. if not isEmptyType(t.typ) and d.k == locNone:
  722. getTemp(p, t.typ, d)
  723. case skipTypes(t.sons[0].typ, abstractVarRange).kind
  724. of tyString:
  725. genStringCase(p, t, d)
  726. of tyFloat..tyFloat128:
  727. genCaseGeneric(p, t, d, "if ($1 >= $2 && $1 <= $3) goto $4;$n",
  728. "if ($1 == $2) goto $3;$n")
  729. else:
  730. if t.sons[0].kind == nkSym and sfGoto in t.sons[0].sym.flags:
  731. genGotoForCase(p, t)
  732. else:
  733. genOrdinalCase(p, t, d)
  734. proc genRestoreFrameAfterException(p: BProc) =
  735. if optStackTrace in p.module.config.options:
  736. if not p.hasCurFramePointer:
  737. p.hasCurFramePointer = true
  738. p.procSec(cpsLocals).add(ropecg(p.module, "\tTFrame* _nimCurFrame;$n", []))
  739. p.procSec(cpsInit).add(ropecg(p.module, "\t_nimCurFrame = #getFrame();$n", []))
  740. linefmt(p, cpsStmts, "#setFrame(_nimCurFrame);$n")
  741. proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
  742. # code to generate:
  743. #
  744. # try
  745. # {
  746. # myDiv(4, 9);
  747. # } catch (NimExceptionType1&) {
  748. # body
  749. # } catch (NimExceptionType2&) {
  750. # finallyPart()
  751. # raise;
  752. # }
  753. # catch(...) {
  754. # general_handler_body
  755. # }
  756. # finallyPart();
  757. template genExceptBranchBody(body: PNode) {.dirty.} =
  758. genRestoreFrameAfterException(p)
  759. expr(p, body, d)
  760. if not isEmptyType(t.typ) and d.k == locNone:
  761. getTemp(p, t.typ, d)
  762. genLineDir(p, t)
  763. discard cgsym(p.module, "popCurrentExceptionEx")
  764. add(p.nestedTryStmts, (t, false))
  765. startBlock(p, "try {$n")
  766. expr(p, t[0], d)
  767. endBlock(p)
  768. var catchAllPresent = false
  769. p.nestedTryStmts[^1].inExcept = true
  770. for i in 1..<t.len:
  771. if t[i].kind != nkExceptBranch: break
  772. # bug #4230: avoid false sharing between branches:
  773. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  774. if t[i].len == 1:
  775. # general except section:
  776. catchAllPresent = true
  777. startBlock(p, "catch (...) {$n")
  778. genExceptBranchBody(t[i][0])
  779. endBlock(p)
  780. else:
  781. for j in 0..t[i].len-2:
  782. if t[i][j].isInfixAs():
  783. let exvar = t[i][j][2] # ex1 in `except ExceptType as ex1:`
  784. fillLoc(exvar.sym.loc, locTemp, exvar, mangleLocalName(p, exvar.sym), OnUnknown)
  785. startBlock(p, "catch ($1& $2) {$n", getTypeDesc(p.module, t[i][j][1].typ), rdLoc(exvar.sym.loc))
  786. else:
  787. startBlock(p, "catch ($1&) {$n", getTypeDesc(p.module, t[i][j].typ))
  788. genExceptBranchBody(t[i][^1]) # exception handler body will duplicated for every type
  789. endBlock(p)
  790. discard pop(p.nestedTryStmts)
  791. if t[^1].kind == nkFinally:
  792. # c++ does not have finally, therefore code needs to be generated twice
  793. if not catchAllPresent:
  794. # finally requires catch all presence
  795. startBlock(p, "catch (...) {$n")
  796. genStmts(p, t[^1][0])
  797. line(p, cpsStmts, ~"throw;$n")
  798. endBlock(p)
  799. genSimpleBlock(p, t[^1][0])
  800. proc genTry(p: BProc, t: PNode, d: var TLoc) =
  801. # code to generate:
  802. #
  803. # XXX: There should be a standard dispatch algorithm
  804. # that's used both here and with multi-methods
  805. #
  806. # TSafePoint sp;
  807. # pushSafePoint(&sp);
  808. # sp.status = setjmp(sp.context);
  809. # if (sp.status == 0) {
  810. # myDiv(4, 9);
  811. # popSafePoint();
  812. # } else {
  813. # popSafePoint();
  814. # /* except DivisionByZero: */
  815. # if (sp.status == DivisionByZero) {
  816. # printf('Division by Zero\n');
  817. # clearException();
  818. # } else {
  819. # clearException();
  820. # }
  821. # }
  822. # {
  823. # /* finally: */
  824. # printf('fin!\n');
  825. # }
  826. # if (exception not cleared)
  827. # propagateCurrentException();
  828. #
  829. if not isEmptyType(t.typ) and d.k == locNone:
  830. getTemp(p, t.typ, d)
  831. p.module.includeHeader("<setjmp.h>")
  832. genLineDir(p, t)
  833. var safePoint = getTempName(p.module)
  834. discard cgsym(p.module, "Exception")
  835. linefmt(p, cpsLocals, "#TSafePoint $1;$n", safePoint)
  836. linefmt(p, cpsStmts, "#pushSafePoint(&$1);$n", safePoint)
  837. if isDefined(p.config, "nimStdSetjmp"):
  838. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", safePoint)
  839. elif isDefined(p.config, "nimSigSetjmp"):
  840. linefmt(p, cpsStmts, "$1.status = sigsetjmp($1.context, 0);$n", safePoint)
  841. elif isDefined(p.config, "nimRawSetjmp"):
  842. linefmt(p, cpsStmts, "$1.status = _setjmp($1.context);$n", safePoint)
  843. else:
  844. linefmt(p, cpsStmts, "$1.status = setjmp($1.context);$n", safePoint)
  845. startBlock(p, "if ($1.status == 0) {$n", [safePoint])
  846. var length = sonsLen(t)
  847. add(p.nestedTryStmts, (t, false))
  848. expr(p, t.sons[0], d)
  849. linefmt(p, cpsStmts, "#popSafePoint();$n")
  850. endBlock(p)
  851. startBlock(p, "else {$n")
  852. linefmt(p, cpsStmts, "#popSafePoint();$n")
  853. genRestoreFrameAfterException(p)
  854. p.nestedTryStmts[^1].inExcept = true
  855. var i = 1
  856. while (i < length) and (t.sons[i].kind == nkExceptBranch):
  857. # bug #4230: avoid false sharing between branches:
  858. if d.k == locTemp and isEmptyType(t.typ): d.k = locNone
  859. var blen = sonsLen(t.sons[i])
  860. if blen == 1:
  861. # general except section:
  862. if i > 1: lineF(p, cpsStmts, "else", [])
  863. startBlock(p)
  864. linefmt(p, cpsStmts, "$1.status = 0;$n", safePoint)
  865. expr(p, t.sons[i].sons[0], d)
  866. linefmt(p, cpsStmts, "#popCurrentException();$n")
  867. endBlock(p)
  868. else:
  869. var orExpr: Rope = nil
  870. for j in countup(0, blen - 2):
  871. assert(t.sons[i].sons[j].kind == nkType)
  872. if orExpr != nil: add(orExpr, "||")
  873. let isObjFormat = if not p.module.compileToCpp:
  874. "#isObj(#getCurrentException()->Sup.m_type, $1)"
  875. else: "#isObj(#getCurrentException()->m_type, $1)"
  876. appcg(p.module, orExpr, isObjFormat,
  877. [genTypeInfo(p.module, t[i][j].typ, t[i][j].info)])
  878. if i > 1: line(p, cpsStmts, "else ")
  879. startBlock(p, "if ($1) {$n", [orExpr])
  880. linefmt(p, cpsStmts, "$1.status = 0;$n", safePoint)
  881. expr(p, t.sons[i].sons[blen-1], d)
  882. linefmt(p, cpsStmts, "#popCurrentException();$n")
  883. endBlock(p)
  884. inc(i)
  885. discard pop(p.nestedTryStmts)
  886. endBlock(p) # end of else block
  887. if i < length and t.sons[i].kind == nkFinally:
  888. p.finallySafePoints.add(safePoint)
  889. genSimpleBlock(p, t.sons[i].sons[0])
  890. discard pop(p.finallySafePoints)
  891. linefmt(p, cpsStmts, "if ($1.status != 0) #reraiseException();$n", safePoint)
  892. proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): Rope =
  893. var res = ""
  894. for it in t.sons:
  895. case it.kind
  896. of nkStrLit..nkTripleStrLit:
  897. res.add(it.strVal)
  898. of nkSym:
  899. var sym = it.sym
  900. if sym.kind in {skProc, skFunc, skIterator, skMethod}:
  901. var a: TLoc
  902. initLocExpr(p, it, a)
  903. res.add($rdLoc(a))
  904. elif sym.kind == skType:
  905. res.add($getTypeDesc(p.module, sym.typ))
  906. else:
  907. discard getTypeDesc(p.module, skipTypes(sym.typ, abstractPtrs))
  908. var r = sym.loc.r
  909. if r == nil:
  910. # if no name has already been given,
  911. # it doesn't matter much:
  912. r = mangleName(p.module, sym)
  913. sym.loc.r = r # but be consequent!
  914. res.add($r)
  915. of nkTypeOfExpr:
  916. res.add($getTypeDesc(p.module, it.typ))
  917. else:
  918. discard getTypeDesc(p.module, skipTypes(it.typ, abstractPtrs))
  919. var a: TLoc
  920. initLocExpr(p, it, a)
  921. res.add($a.rdLoc)
  922. if isAsmStmt and hasGnuAsm in CC[p.config.cCompiler].props:
  923. for x in splitLines(res):
  924. var j = 0
  925. while j < x.len and x[j] in {' ', '\t'}: inc(j)
  926. if j < x.len:
  927. if x[j] in {'"', ':'}:
  928. # don't modify the line if already in quotes or
  929. # some clobber register list:
  930. add(result, x); add(result, "\L")
  931. else:
  932. # ignore empty lines
  933. add(result, "\"")
  934. add(result, x)
  935. add(result, "\\n\"\n")
  936. else:
  937. res.add("\L")
  938. result = res.rope
  939. proc genAsmStmt(p: BProc, t: PNode) =
  940. assert(t.kind == nkAsmStmt)
  941. genLineDir(p, t)
  942. var s = genAsmOrEmitStmt(p, t, isAsmStmt=true)
  943. # see bug #2362, "top level asm statements" seem to be a mis-feature
  944. # but even if we don't do this, the example in #2362 cannot possibly
  945. # work:
  946. if p.prc == nil:
  947. # top level asm statement?
  948. addf(p.module.s[cfsProcHeaders], CC[p.config.cCompiler].asmStmtFrmt, [s])
  949. else:
  950. lineF(p, cpsStmts, CC[p.config.cCompiler].asmStmtFrmt, [s])
  951. proc determineSection(n: PNode): TCFileSection =
  952. result = cfsProcHeaders
  953. if n.len >= 1 and n.sons[0].kind in {nkStrLit..nkTripleStrLit}:
  954. let sec = n.sons[0].strVal
  955. if sec.startsWith("/*TYPESECTION*/"): result = cfsTypes
  956. elif sec.startsWith("/*VARSECTION*/"): result = cfsVars
  957. elif sec.startsWith("/*INCLUDESECTION*/"): result = cfsHeaders
  958. proc genEmit(p: BProc, t: PNode) =
  959. var s = genAsmOrEmitStmt(p, t.sons[1])
  960. if p.prc == nil:
  961. # top level emit pragma?
  962. let section = determineSection(t[1])
  963. genCLineDir(p.module.s[section], t.info, p.config)
  964. add(p.module.s[section], s)
  965. else:
  966. genLineDir(p, t)
  967. line(p, cpsStmts, s)
  968. proc genBreakPoint(p: BProc, t: PNode) =
  969. var name: string
  970. if optEndb in p.options:
  971. if t.kind == nkExprColonExpr:
  972. assert(t.sons[1].kind in {nkStrLit..nkTripleStrLit})
  973. name = normalize(t.sons[1].strVal)
  974. else:
  975. inc(p.module.g.breakPointId)
  976. name = "bp" & $p.module.g.breakPointId
  977. genLineDir(p, t) # BUGFIX
  978. appcg(p.module, p.module.g.breakpoints,
  979. "#dbgRegisterBreakpoint($1, (NCSTRING)$2, (NCSTRING)$3);$n", [
  980. rope(toLinenumber(t.info)), makeCString(toFilename(p.config, t.info)),
  981. makeCString(name)])
  982. proc genWatchpoint(p: BProc, n: PNode) =
  983. if optEndb notin p.options: return
  984. var a: TLoc
  985. initLocExpr(p, n.sons[1], a)
  986. let typ = skipTypes(n.sons[1].typ, abstractVarRange)
  987. lineCg(p, cpsStmts, "#dbgRegisterWatchpoint($1, (NCSTRING)$2, $3);$n",
  988. [addrLoc(p.config, a), makeCString(renderTree(n.sons[1])),
  989. genTypeInfo(p.module, typ, n.info)])
  990. proc genPragma(p: BProc, n: PNode) =
  991. for it in n.sons:
  992. case whichPragma(it)
  993. of wEmit: genEmit(p, it)
  994. of wBreakpoint: genBreakPoint(p, it)
  995. of wWatchPoint: genWatchpoint(p, it)
  996. of wInjectStmt:
  997. var p = newProc(nil, p.module)
  998. p.options = p.options - {optLineTrace, optStackTrace}
  999. genStmts(p, it.sons[1])
  1000. p.module.injectStmt = p.s(cpsStmts)
  1001. else: discard
  1002. proc fieldDiscriminantCheckNeeded(p: BProc, asgn: PNode): bool =
  1003. if optFieldCheck in p.options:
  1004. var le = asgn.sons[0]
  1005. if le.kind == nkCheckedFieldExpr:
  1006. var field = le.sons[0].sons[1].sym
  1007. result = sfDiscriminant in field.flags
  1008. elif le.kind == nkDotExpr:
  1009. var field = le.sons[1].sym
  1010. result = sfDiscriminant in field.flags
  1011. proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType,
  1012. field: PSym) =
  1013. var t = skipTypes(objtype, abstractVar)
  1014. assert t.kind == tyObject
  1015. discard genTypeInfo(p.module, t, a.lode.info)
  1016. var L = lengthOrd(p.config, field.typ)
  1017. if not containsOrIncl(p.module.declaredThings, field.id):
  1018. appcg(p.module, cfsVars, "extern $1",
  1019. discriminatorTableDecl(p.module, t, field))
  1020. lineCg(p, cpsStmts,
  1021. "#FieldDiscriminantCheck((NI)(NU)($1), (NI)(NU)($2), $3, $4);$n",
  1022. [rdLoc(a), rdLoc(tmp), discriminatorTableName(p.module, t, field),
  1023. intLiteral(L+1)])
  1024. proc asgnFieldDiscriminant(p: BProc, e: PNode) =
  1025. var a, tmp: TLoc
  1026. var dotExpr = e.sons[0]
  1027. if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr.sons[0]
  1028. initLocExpr(p, e.sons[0], a)
  1029. getTemp(p, a.t, tmp)
  1030. expr(p, e.sons[1], tmp)
  1031. genDiscriminantCheck(p, a, tmp, dotExpr.sons[0].typ, dotExpr.sons[1].sym)
  1032. genAssignment(p, a, tmp, {})
  1033. proc patchAsgnStmtListExpr(father, orig, n: PNode) =
  1034. case n.kind
  1035. of nkDerefExpr, nkHiddenDeref:
  1036. let asgn = copyNode(orig)
  1037. asgn.add orig[0]
  1038. asgn.add n
  1039. father.add asgn
  1040. of nkStmtList, nkStmtListExpr:
  1041. for x in n:
  1042. patchAsgnStmtListExpr(father, orig, x)
  1043. else:
  1044. father.add n
  1045. proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
  1046. if e.sons[0].kind == nkSym and sfGoto in e.sons[0].sym.flags:
  1047. genLineDir(p, e)
  1048. genGotoVar(p, e.sons[1])
  1049. elif not fieldDiscriminantCheckNeeded(p, e):
  1050. # this fixes bug #6422 but we really need to change the representation of
  1051. # arrays in the backend...
  1052. let le = e[0]
  1053. let ri = e[1]
  1054. var needsRepair = false
  1055. var it = ri
  1056. while it.kind in {nkStmtList, nkStmtListExpr}:
  1057. it = it.lastSon
  1058. needsRepair = true
  1059. if it.kind in {nkDerefExpr, nkHiddenDeref} and needsRepair:
  1060. var patchedTree = newNodeI(nkStmtList, e.info)
  1061. patchAsgnStmtListExpr(patchedTree, e, ri)
  1062. genStmts(p, patchedTree)
  1063. return
  1064. var a: TLoc
  1065. discard getTypeDesc(p.module, le.typ.skipTypes(skipPtrs))
  1066. if le.kind in {nkDerefExpr, nkHiddenDeref}:
  1067. genDeref(p, le, a, enforceDeref=true)
  1068. else:
  1069. initLocExpr(p, le, a)
  1070. if fastAsgn: incl(a.flags, lfNoDeepCopy)
  1071. assert(a.t != nil)
  1072. genLineDir(p, ri)
  1073. loadInto(p, e.sons[0], ri, a)
  1074. else:
  1075. genLineDir(p, e)
  1076. asgnFieldDiscriminant(p, e)
  1077. proc genStmts(p: BProc, t: PNode) =
  1078. var a: TLoc
  1079. let isPush = hintExtendedContext in p.config.notes
  1080. if isPush: pushInfoContext(p.config, t.info)
  1081. expr(p, t, a)
  1082. if isPush: popInfoContext(p.config)
  1083. internalAssert p.config, a.k in {locNone, locTemp, locLocalVar, locExpr}