shuffle_fuzz.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. #!/usr/bin/env python
  2. """A shuffle vector fuzz tester.
  3. This is a python program to fuzz test the LLVM shufflevector instruction. It
  4. generates a function with a random sequnece of shufflevectors, maintaining the
  5. element mapping accumulated across the function. It then generates a main
  6. function which calls it with a different value in each element and checks that
  7. the result matches the expected mapping.
  8. Take the output IR printed to stdout, compile it to an executable using whatever
  9. set of transforms you want to test, and run the program. If it crashes, it found
  10. a bug.
  11. """
  12. import argparse
  13. import itertools
  14. import random
  15. import sys
  16. import uuid
  17. def main():
  18. element_types=['i8', 'i16', 'i32', 'i64', 'f32', 'f64']
  19. parser = argparse.ArgumentParser(description=__doc__)
  20. parser.add_argument('-v', '--verbose', action='store_true',
  21. help='Show verbose output')
  22. parser.add_argument('--seed', default=str(uuid.uuid4()),
  23. help='A string used to seed the RNG')
  24. parser.add_argument('--max-shuffle-height', type=int, default=16,
  25. help='Specify a fixed height of shuffle tree to test')
  26. parser.add_argument('--no-blends', dest='blends', action='store_false',
  27. help='Include blends of two input vectors')
  28. parser.add_argument('--fixed-bit-width', type=int, choices=[128, 256],
  29. help='Specify a fixed bit width of vector to test')
  30. parser.add_argument('--fixed-element-type', choices=element_types,
  31. help='Specify a fixed element type to test')
  32. parser.add_argument('--triple',
  33. help='Specify a triple string to include in the IR')
  34. args = parser.parse_args()
  35. random.seed(args.seed)
  36. if args.fixed_element_type is not None:
  37. element_types=[args.fixed_element_type]
  38. if args.fixed_bit_width is not None:
  39. if args.fixed_bit_width == 128:
  40. width_map={'i64': 2, 'i32': 4, 'i16': 8, 'i8': 16, 'f64': 2, 'f32': 4}
  41. (width, element_type) = random.choice(
  42. [(width_map[t], t) for t in element_types])
  43. elif args.fixed_bit_width == 256:
  44. width_map={'i64': 4, 'i32': 8, 'i16': 16, 'i8': 32, 'f64': 4, 'f32': 8}
  45. (width, element_type) = random.choice(
  46. [(width_map[t], t) for t in element_types])
  47. else:
  48. sys.exit(1) # Checked above by argument parsing.
  49. else:
  50. width = random.choice([2, 4, 8, 16, 32, 64])
  51. element_type = random.choice(element_types)
  52. element_modulus = {
  53. 'i8': 1 << 8, 'i16': 1 << 16, 'i32': 1 << 32, 'i64': 1 << 64,
  54. 'f32': 1 << 32, 'f64': 1 << 64}[element_type]
  55. shuffle_range = (2 * width) if args.blends else width
  56. # Because undef (-1) saturates and is indistinguishable when testing the
  57. # correctness of a shuffle, we want to bias our fuzz toward having a decent
  58. # mixture of non-undef lanes in the end. With a deep shuffle tree, the
  59. # probabilies aren't good so we need to bias things. The math here is that if
  60. # we uniformly select between -1 and the other inputs, each element of the
  61. # result will have the following probability of being undef:
  62. #
  63. # 1 - (shuffle_range/(shuffle_range+1))^max_shuffle_height
  64. #
  65. # More generally, for any probability P of selecting a defined element in
  66. # a single shuffle, the end result is:
  67. #
  68. # 1 - P^max_shuffle_height
  69. #
  70. # The power of the shuffle height is the real problem, as we want:
  71. #
  72. # 1 - shuffle_range/(shuffle_range+1)
  73. #
  74. # So we bias the selection of undef at any given node based on the tree
  75. # height. Below, let 'A' be 'len(shuffle_range)', 'C' be 'max_shuffle_height',
  76. # and 'B' be the bias we use to compensate for
  77. # C '((A+1)*A^(1/C))/(A*(A+1)^(1/C))':
  78. #
  79. # 1 - (B * A)/(A + 1)^C = 1 - A/(A + 1)
  80. #
  81. # So at each node we use:
  82. #
  83. # 1 - (B * A)/(A + 1)
  84. # = 1 - ((A + 1) * A * A^(1/C))/(A * (A + 1) * (A + 1)^(1/C))
  85. # = 1 - ((A + 1) * A^((C + 1)/C))/(A * (A + 1)^((C + 1)/C))
  86. #
  87. # This is the formula we use to select undef lanes in the shuffle.
  88. A = float(shuffle_range)
  89. C = float(args.max_shuffle_height)
  90. undef_prob = 1.0 - (((A + 1.0) * pow(A, (C + 1.0)/C)) /
  91. (A * pow(A + 1.0, (C + 1.0)/C)))
  92. shuffle_tree = [[[-1 if random.random() <= undef_prob
  93. else random.choice(range(shuffle_range))
  94. for _ in itertools.repeat(None, width)]
  95. for _ in itertools.repeat(None, args.max_shuffle_height - i)]
  96. for i in xrange(args.max_shuffle_height)]
  97. if args.verbose:
  98. # Print out the shuffle sequence in a compact form.
  99. print >>sys.stderr, ('Testing shuffle sequence "%s" (v%d%s):' %
  100. (args.seed, width, element_type))
  101. for i, shuffles in enumerate(shuffle_tree):
  102. print >>sys.stderr, ' tree level %d:' % (i,)
  103. for j, s in enumerate(shuffles):
  104. print >>sys.stderr, ' shuffle %d: %s' % (j, s)
  105. print >>sys.stderr, ''
  106. # Symbolically evaluate the shuffle tree.
  107. inputs = [[int(j % element_modulus)
  108. for j in xrange(i * width + 1, (i + 1) * width + 1)]
  109. for i in xrange(args.max_shuffle_height + 1)]
  110. results = inputs
  111. for shuffles in shuffle_tree:
  112. results = [[((results[i] if j < width else results[i + 1])[j % width]
  113. if j != -1 else -1)
  114. for j in s]
  115. for i, s in enumerate(shuffles)]
  116. if len(results) != 1:
  117. print >>sys.stderr, 'ERROR: Bad results: %s' % (results,)
  118. sys.exit(1)
  119. result = results[0]
  120. if args.verbose:
  121. print >>sys.stderr, 'Which transforms:'
  122. print >>sys.stderr, ' from: %s' % (inputs,)
  123. print >>sys.stderr, ' into: %s' % (result,)
  124. print >>sys.stderr, ''
  125. # The IR uses silly names for floating point types. We also need a same-size
  126. # integer type.
  127. integral_element_type = element_type
  128. if element_type == 'f32':
  129. integral_element_type = 'i32'
  130. element_type = 'float'
  131. elif element_type == 'f64':
  132. integral_element_type = 'i64'
  133. element_type = 'double'
  134. # Now we need to generate IR for the shuffle function.
  135. subst = {'N': width, 'T': element_type, 'IT': integral_element_type}
  136. print """
  137. define internal fastcc <%(N)d x %(T)s> @test(%(arguments)s) noinline nounwind {
  138. entry:""" % dict(subst,
  139. arguments=', '.join(
  140. ['<%(N)d x %(T)s> %%s.0.%(i)d' % dict(subst, i=i)
  141. for i in xrange(args.max_shuffle_height + 1)]))
  142. for i, shuffles in enumerate(shuffle_tree):
  143. for j, s in enumerate(shuffles):
  144. print """
  145. %%s.%(next_i)d.%(j)d = shufflevector <%(N)d x %(T)s> %%s.%(i)d.%(j)d, <%(N)d x %(T)s> %%s.%(i)d.%(next_j)d, <%(N)d x i32> <%(S)s>
  146. """.strip('\n') % dict(subst, i=i, next_i=i + 1, j=j, next_j=j + 1,
  147. S=', '.join(['i32 ' + (str(si) if si != -1 else 'undef')
  148. for si in s]))
  149. print """
  150. ret <%(N)d x %(T)s> %%s.%(i)d.0
  151. }
  152. """ % dict(subst, i=len(shuffle_tree))
  153. # Generate some string constants that we can use to report errors.
  154. for i, r in enumerate(result):
  155. if r != -1:
  156. s = ('FAIL(%(seed)s): lane %(lane)d, expected %(result)d, found %%d\n\\0A' %
  157. {'seed': args.seed, 'lane': i, 'result': r})
  158. s += ''.join(['\\00' for _ in itertools.repeat(None, 128 - len(s) + 2)])
  159. print """
  160. @error.%(i)d = private unnamed_addr global [128 x i8] c"%(s)s"
  161. """.strip() % {'i': i, 's': s}
  162. # Define a wrapper function which is marked 'optnone' to prevent
  163. # interprocedural optimizations from deleting the test.
  164. print """
  165. define internal fastcc <%(N)d x %(T)s> @test_wrapper(%(arguments)s) optnone noinline {
  166. %%result = call fastcc <%(N)d x %(T)s> @test(%(arguments)s)
  167. ret <%(N)d x %(T)s> %%result
  168. }
  169. """ % dict(subst,
  170. arguments=', '.join(['<%(N)d x %(T)s> %%s.%(i)d' % dict(subst, i=i)
  171. for i in xrange(args.max_shuffle_height + 1)]))
  172. # Finally, generate a main function which will trap if any lanes are mapped
  173. # incorrectly (in an observable way).
  174. print """
  175. define i32 @main() {
  176. entry:
  177. ; Create a scratch space to print error messages.
  178. %%str = alloca [128 x i8]
  179. %%str.ptr = getelementptr inbounds [128 x i8]* %%str, i32 0, i32 0
  180. ; Build the input vector and call the test function.
  181. %%v = call fastcc <%(N)d x %(T)s> @test_wrapper(%(inputs)s)
  182. ; We need to cast this back to an integer type vector to easily check the
  183. ; result.
  184. %%v.cast = bitcast <%(N)d x %(T)s> %%v to <%(N)d x %(IT)s>
  185. br label %%test.0
  186. """ % dict(subst,
  187. inputs=', '.join(
  188. [('<%(N)d x %(T)s> bitcast '
  189. '(<%(N)d x %(IT)s> <%(input)s> to <%(N)d x %(T)s>)' %
  190. dict(subst, input=', '.join(['%(IT)s %(i)d' % dict(subst, i=i)
  191. for i in input])))
  192. for input in inputs]))
  193. # Test that each non-undef result lane contains the expected value.
  194. for i, r in enumerate(result):
  195. if r == -1:
  196. print """
  197. test.%(i)d:
  198. ; Skip this lane, its value is undef.
  199. br label %%test.%(next_i)d
  200. """ % dict(subst, i=i, next_i=i + 1)
  201. else:
  202. print """
  203. test.%(i)d:
  204. %%v.%(i)d = extractelement <%(N)d x %(IT)s> %%v.cast, i32 %(i)d
  205. %%cmp.%(i)d = icmp ne %(IT)s %%v.%(i)d, %(r)d
  206. br i1 %%cmp.%(i)d, label %%die.%(i)d, label %%test.%(next_i)d
  207. die.%(i)d:
  208. ; Capture the actual value and print an error message.
  209. %%tmp.%(i)d = zext %(IT)s %%v.%(i)d to i2048
  210. %%bad.%(i)d = trunc i2048 %%tmp.%(i)d to i32
  211. call i32 (i8*, i8*, ...)* @sprintf(i8* %%str.ptr, i8* getelementptr inbounds ([128 x i8]* @error.%(i)d, i32 0, i32 0), i32 %%bad.%(i)d)
  212. %%length.%(i)d = call i32 @strlen(i8* %%str.ptr)
  213. call i32 @write(i32 2, i8* %%str.ptr, i32 %%length.%(i)d)
  214. call void @llvm.trap()
  215. unreachable
  216. """ % dict(subst, i=i, next_i=i + 1, r=r)
  217. print """
  218. test.%d:
  219. ret i32 0
  220. }
  221. declare i32 @strlen(i8*)
  222. declare i32 @write(i32, i8*, i32)
  223. declare i32 @sprintf(i8*, i8*, ...)
  224. declare void @llvm.trap() noreturn nounwind
  225. """ % (len(result),)
  226. if __name__ == '__main__':
  227. main()