ccgutils.nim 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  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, astalgo, ropes, hashes, strutils, types, msgs, wordrecg,
  12. platform, trees, options
  13. proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode =
  14. case n.kind
  15. of nkStmtList:
  16. for i in 0 .. < n.len:
  17. result = getPragmaStmt(n[i], w)
  18. if result != nil: break
  19. of nkPragma:
  20. for i in 0 .. < n.len:
  21. if whichPragma(n[i]) == w: return n[i]
  22. else: discard
  23. proc stmtsContainPragma*(n: PNode, w: TSpecialWord): bool =
  24. result = getPragmaStmt(n, w) != nil
  25. proc hashString*(s: string): BiggestInt =
  26. # has to be the same algorithm as system.hashString!
  27. if CPU[targetCPU].bit == 64:
  28. # we have to use the same bitwidth
  29. # as the target CPU
  30. var b = 0'i64
  31. for i in countup(0, len(s) - 1):
  32. b = b +% ord(s[i])
  33. b = b +% `shl`(b, 10)
  34. b = b xor `shr`(b, 6)
  35. b = b +% `shl`(b, 3)
  36. b = b xor `shr`(b, 11)
  37. b = b +% `shl`(b, 15)
  38. result = b
  39. else:
  40. var a = 0'i32
  41. for i in countup(0, len(s) - 1):
  42. a = a +% ord(s[i]).int32
  43. a = a +% `shl`(a, 10'i32)
  44. a = a xor `shr`(a, 6'i32)
  45. a = a +% `shl`(a, 3'i32)
  46. a = a xor `shr`(a, 11'i32)
  47. a = a +% `shl`(a, 15'i32)
  48. result = a
  49. var
  50. gTypeTable: array[TTypeKind, TIdTable]
  51. gCanonicalTypes: array[TTypeKind, PType]
  52. proc initTypeTables() =
  53. for i in countup(low(TTypeKind), high(TTypeKind)): initIdTable(gTypeTable[i])
  54. proc resetCaches* =
  55. ## XXX: fix that more properly
  56. initTypeTables()
  57. for i in low(gCanonicalTypes)..high(gCanonicalTypes):
  58. gCanonicalTypes[i] = nil
  59. when false:
  60. proc echoStats*() =
  61. for i in countup(low(TTypeKind), high(TTypeKind)):
  62. echo i, " ", gTypeTable[i].counter
  63. proc slowSearch(key: PType; k: TTypeKind): PType =
  64. # tuples are quite horrible as C does not support them directly and
  65. # tuple[string, string] is a (strange) subtype of
  66. # tuple[nameA, nameB: string]. This bites us here, so we
  67. # use 'sameBackendType' instead of 'sameType'.
  68. if idTableHasObjectAsKey(gTypeTable[k], key): return key
  69. for h in countup(0, high(gTypeTable[k].data)):
  70. var t = PType(gTypeTable[k].data[h].key)
  71. if t != nil and sameBackendType(t, key):
  72. return t
  73. idTablePut(gTypeTable[k], key, key)
  74. result = key
  75. proc getUniqueType*(key: PType): PType =
  76. # this is a hotspot in the compiler!
  77. result = key
  78. when false:
  79. if key == nil: return
  80. var k = key.kind
  81. case k
  82. of tyBool, tyChar, tyInt..tyUInt64:
  83. # no canonicalization for integral types, so that e.g. ``pid_t`` is
  84. # produced instead of ``NI``.
  85. result = key
  86. of tyEmpty, tyNil, tyExpr, tyStmt, tyPointer, tyString,
  87. tyCString, tyNone, tyVoid:
  88. result = gCanonicalTypes[k]
  89. if result == nil:
  90. gCanonicalTypes[k] = key
  91. result = key
  92. of tyTypeDesc, tyTypeClasses, tyGenericParam, tyFromExpr:
  93. if key.isResolvedUserTypeClass:
  94. return getUniqueType(lastSon(key))
  95. if key.sym != nil:
  96. internalError(key.sym.info, "metatype not eliminated")
  97. else:
  98. internalError("metatype not eliminated")
  99. of tyDistinct:
  100. if key.deepCopy != nil: result = key
  101. else: result = getUniqueType(lastSon(key))
  102. of tyGenericInst, tyOrdinal, tyStatic, tyAlias, tyInferred:
  103. result = getUniqueType(lastSon(key))
  104. #let obj = lastSon(key)
  105. #if obj.sym != nil and obj.sym.name.s == "TOption":
  106. # echo "for ", typeToString(key), " I returned "
  107. # debug result
  108. of tyPtr, tyRef, tyVar:
  109. let elemType = lastSon(key)
  110. if elemType.kind in {tyBool, tyChar, tyInt..tyUInt64}:
  111. # no canonicalization for integral types, so that e.g. ``ptr pid_t`` is
  112. # produced instead of ``ptr NI``.
  113. result = key
  114. else:
  115. result = slowSearch(key, k)
  116. of tyGenericInvocation, tyGenericBody,
  117. tyOpenArray, tyArray, tySet, tyRange, tyTuple,
  118. tySequence, tyForward, tyVarargs, tyProxy, tyOpt:
  119. # we have to do a slow linear search because types may need
  120. # to be compared by their structure:
  121. result = slowSearch(key, k)
  122. of tyObject:
  123. if tfFromGeneric notin key.flags:
  124. # fast case; lookup per id suffices:
  125. result = PType(idTableGet(gTypeTable[k], key))
  126. if result == nil:
  127. idTablePut(gTypeTable[k], key, key)
  128. result = key
  129. else:
  130. # ugly slow case: need to compare by structure
  131. if idTableHasObjectAsKey(gTypeTable[k], key): return key
  132. for h in countup(0, high(gTypeTable[k].data)):
  133. var t = PType(gTypeTable[k].data[h].key)
  134. if t != nil and sameBackendType(t, key):
  135. return t
  136. idTablePut(gTypeTable[k], key, key)
  137. result = key
  138. of tyEnum:
  139. result = PType(idTableGet(gTypeTable[k], key))
  140. if result == nil:
  141. idTablePut(gTypeTable[k], key, key)
  142. result = key
  143. of tyProc:
  144. if key.callConv != ccClosure:
  145. result = key
  146. else:
  147. # ugh, we need the canon here:
  148. result = slowSearch(key, k)
  149. of tyUnused, tyOptAsRef, tyUnused1, tyUnused2: internalError("getUniqueType")
  150. proc makeSingleLineCString*(s: string): string =
  151. result = "\""
  152. for c in items(s):
  153. result.add(c.toCChar)
  154. result.add('\"')
  155. proc mangle*(name: string): string =
  156. result = newStringOfCap(name.len)
  157. var start = 0
  158. if name[0] in Digits:
  159. result.add("X" & name[0])
  160. start = 1
  161. var requiresUnderscore = false
  162. template special(x) =
  163. result.add x
  164. requiresUnderscore = true
  165. for i in start..(name.len-1):
  166. let c = name[i]
  167. case c
  168. of 'a'..'z', '0'..'9', 'A'..'Z':
  169. add(result, c)
  170. of '_':
  171. # we generate names like 'foo_9' for scope disambiguations and so
  172. # disallow this here:
  173. if i > 0 and i < name.len-1 and name[i+1] in Digits:
  174. discard
  175. else:
  176. add(result, c)
  177. of '$': special "dollar"
  178. of '%': special "percent"
  179. of '&': special "amp"
  180. of '^': special "roof"
  181. of '!': special "emark"
  182. of '?': special "qmark"
  183. of '*': special "star"
  184. of '+': special "plus"
  185. of '-': special "minus"
  186. of '/': special "slash"
  187. of '=': special "eq"
  188. of '<': special "lt"
  189. of '>': special "gt"
  190. of '~': special "tilde"
  191. of ':': special "colon"
  192. of '.': special "dot"
  193. of '@': special "at"
  194. of '|': special "bar"
  195. else:
  196. add(result, "X" & toHex(ord(c), 2))
  197. requiresUnderscore = true
  198. if requiresUnderscore:
  199. result.add "_"
  200. proc emitLazily*(s: PSym): bool {.inline.} =
  201. result = optDeadCodeElim in gGlobalOptions or
  202. sfDeadCodeElim in getModule(s).flags
  203. initTypeTables()