ccgutils.nim 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. #
  2. #
  3. # The Nim Compiler
  4. # (c) Copyright 2012 Andreas Rumpf
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. # This module declares some helpers for the C code generator.
  10. import
  11. ast, types, hashes, strutils, msgs, wordrecg,
  12. platform, trees, options, cgendata
  13. import std/[hashes, strutils, formatfloat]
  14. when defined(nimPreviewSlimSystem):
  15. import std/assertions
  16. proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode =
  17. case n.kind
  18. of nkStmtList:
  19. for i in 0..<n.len:
  20. result = getPragmaStmt(n[i], w)
  21. if result != nil: break
  22. of nkPragma:
  23. for i in 0..<n.len:
  24. if whichPragma(n[i]) == w: return n[i]
  25. else: discard
  26. proc stmtsContainPragma*(n: PNode, w: TSpecialWord): bool =
  27. result = getPragmaStmt(n, w) != nil
  28. proc hashString*(conf: ConfigRef; s: string): BiggestInt =
  29. # has to be the same algorithm as strmantle.hashString!
  30. if CPU[conf.target.targetCPU].bit == 64:
  31. # we have to use the same bitwidth
  32. # as the target CPU
  33. var b = 0'u64
  34. for i in 0..<s.len:
  35. b = b + uint(s[i])
  36. b = b + (b shl 10)
  37. b = b xor (b shr 6)
  38. b = b + (b shl 3)
  39. b = b xor (b shr 11)
  40. b = b + (b shl 15)
  41. result = cast[Hash](b)
  42. else:
  43. var a = 0'u32
  44. for i in 0..<s.len:
  45. a = a + uint32(s[i])
  46. a = a + (a shl 10)
  47. a = a xor (a shr 6)
  48. a = a + (a shl 3)
  49. a = a xor (a shr 11)
  50. a = a + (a shl 15)
  51. result = cast[Hash](uint(a))
  52. template getUniqueType*(key: PType): PType = key
  53. proc makeSingleLineCString*(s: string): string =
  54. result = "\""
  55. for c in items(s):
  56. c.toCChar(result)
  57. result.add('\"')
  58. proc mangle*(name: string): string =
  59. result = newStringOfCap(name.len)
  60. var start = 0
  61. if name[0] in Digits:
  62. result.add("X" & name[0])
  63. start = 1
  64. var requiresUnderscore = false
  65. template special(x) =
  66. result.add x
  67. requiresUnderscore = true
  68. for i in start..<name.len:
  69. let c = name[i]
  70. case c
  71. of 'a'..'z', '0'..'9', 'A'..'Z':
  72. result.add(c)
  73. of '_':
  74. # we generate names like 'foo_9' for scope disambiguations and so
  75. # disallow this here:
  76. if i > 0 and i < name.len-1 and name[i+1] in Digits:
  77. discard
  78. else:
  79. result.add(c)
  80. of '$': special "dollar"
  81. of '%': special "percent"
  82. of '&': special "amp"
  83. of '^': special "roof"
  84. of '!': special "emark"
  85. of '?': special "qmark"
  86. of '*': special "star"
  87. of '+': special "plus"
  88. of '-': special "minus"
  89. of '/': special "slash"
  90. of '\\': special "backslash"
  91. of '=': special "eq"
  92. of '<': special "lt"
  93. of '>': special "gt"
  94. of '~': special "tilde"
  95. of ':': special "colon"
  96. of '.': special "dot"
  97. of '@': special "at"
  98. of '|': special "bar"
  99. else:
  100. result.add("X" & toHex(ord(c), 2))
  101. requiresUnderscore = true
  102. if requiresUnderscore:
  103. result.add "_"
  104. proc mapSetType(conf: ConfigRef; typ: PType): TCTypeKind =
  105. case int(getSize(conf, typ))
  106. of 1: result = ctInt8
  107. of 2: result = ctInt16
  108. of 4: result = ctInt32
  109. of 8: result = ctInt64
  110. else: result = ctArray
  111. proc ccgIntroducedPtr*(conf: ConfigRef; s: PSym, retType: PType): bool =
  112. var pt = skipTypes(s.typ, typedescInst)
  113. assert skResult != s.kind
  114. #note precedence: params override types
  115. if optByRef in s.options: return true
  116. elif sfByCopy in s.flags: return false
  117. elif tfByRef in pt.flags: return true
  118. elif tfByCopy in pt.flags: return false
  119. case pt.kind
  120. of tyObject:
  121. if s.typ.sym != nil and sfForward in s.typ.sym.flags:
  122. # forwarded objects are *always* passed by pointers for consistency!
  123. result = true
  124. elif s.typ.kind == tySink and conf.selectedGC notin {gcArc, gcAtomicArc, gcOrc, gcHooks}:
  125. # bug #23354:
  126. result = false
  127. elif (optByRef in s.options) or (getSize(conf, pt) > conf.target.floatSize * 3):
  128. result = true # requested anyway
  129. elif (tfFinal in pt.flags) and (pt[0] == nil):
  130. result = false # no need, because no subtyping possible
  131. else:
  132. result = true # ordinary objects are always passed by reference,
  133. # otherwise casting doesn't work
  134. of tyTuple:
  135. result = (getSize(conf, pt) > conf.target.floatSize*3) or (optByRef in s.options)
  136. else:
  137. result = false
  138. # first parameter and return type is 'lent T'? --> use pass by pointer
  139. if s.position == 0 and retType != nil and retType.kind == tyLent:
  140. result = not (pt.kind in {tyVar, tyArray, tyOpenArray, tyVarargs, tyRef, tyPtr, tyPointer} or
  141. pt.kind == tySet and mapSetType(conf, pt) == ctArray)
  142. proc encodeName*(name: string): string =
  143. result = mangle(name)
  144. result = $result.len & result
  145. proc makeUnique(m: BModule; s: PSym, name: string = ""): string =
  146. result = if name == "": s.name.s else: name
  147. result.add "__"
  148. result.add m.g.graph.ifaces[s.itemId.module].uniqueName
  149. result.add "_u"
  150. result.add $s.itemId.item
  151. proc encodeSym*(m: BModule; s: PSym; makeUnique: bool = false): string =
  152. #Module::Type
  153. var name = s.name.s
  154. if makeUnique:
  155. name = makeUnique(m, s, name)
  156. "N" & encodeName(s.skipGenericOwner.name.s) & encodeName(name) & "E"
  157. proc elementType*(n: PType): PType {.inline.} = n.sons[^1]
  158. proc encodeType*(m: BModule; t: PType): string =
  159. result = ""
  160. var kindName = ($t.kind)[2..^1]
  161. kindName[0] = toLower($kindName[0])[0]
  162. case t.kind
  163. of tyObject, tyEnum, tyDistinct, tyUserTypeClass, tyGenericParam:
  164. result = encodeSym(m, t.sym)
  165. of tyGenericInst, tyUserTypeClassInst, tyGenericBody:
  166. result = encodeName(t[0].sym.name.s)
  167. result.add "I"
  168. for i in 1..<t.len - 1:
  169. result.add encodeType(m, t[i])
  170. result.add "E"
  171. of tySequence, tyOpenArray, tyArray, tyVarargs, tyTuple, tyProc, tySet, tyTypeDesc,
  172. tyPtr, tyRef, tyVar, tyLent, tySink, tyStatic, tyUncheckedArray, tyOr, tyAnd, tyBuiltInTypeClass:
  173. result =
  174. case t.kind:
  175. of tySequence: encodeName("seq")
  176. else: encodeName(kindName)
  177. result.add "I"
  178. for i in 0..<t.len:
  179. let s = t[i]
  180. if s.isNil: continue
  181. result.add encodeType(m, s)
  182. result.add "E"
  183. of tyRange:
  184. var val = "range_"
  185. if t.n[0].typ.kind in {tyFloat..tyFloat128}:
  186. val.addFloat t.n[0].floatVal
  187. val.add "_"
  188. val.addFloat t.n[1].floatVal
  189. else:
  190. val.add $t.n[0].intVal & "_" & $t.n[1].intVal
  191. result = encodeName(val)
  192. of tyString..tyUInt64, tyPointer, tyBool, tyChar, tyVoid, tyAnything, tyNil, tyEmpty:
  193. result = encodeName(kindName)
  194. of tyAlias, tyInferred, tyOwned:
  195. result = encodeType(m, t.elementType)
  196. else:
  197. assert false, "encodeType " & $t.kind