llvmlite 0.44.0rc1__cp312-cp312-manylinux_2_27_aarch64.manylinux_2_28_aarch64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of llvmlite might be problematic. Click here for more details.

Files changed (46) hide show
  1. llvmlite/__init__.py +10 -0
  2. llvmlite/_version.py +11 -0
  3. llvmlite/binding/__init__.py +19 -0
  4. llvmlite/binding/analysis.py +69 -0
  5. llvmlite/binding/common.py +34 -0
  6. llvmlite/binding/context.py +39 -0
  7. llvmlite/binding/dylib.py +45 -0
  8. llvmlite/binding/executionengine.py +330 -0
  9. llvmlite/binding/ffi.py +395 -0
  10. llvmlite/binding/initfini.py +73 -0
  11. llvmlite/binding/libllvmlite.so +0 -0
  12. llvmlite/binding/linker.py +20 -0
  13. llvmlite/binding/module.py +349 -0
  14. llvmlite/binding/newpassmanagers.py +357 -0
  15. llvmlite/binding/object_file.py +82 -0
  16. llvmlite/binding/options.py +17 -0
  17. llvmlite/binding/orcjit.py +342 -0
  18. llvmlite/binding/passmanagers.py +946 -0
  19. llvmlite/binding/targets.py +520 -0
  20. llvmlite/binding/transforms.py +151 -0
  21. llvmlite/binding/typeref.py +285 -0
  22. llvmlite/binding/value.py +632 -0
  23. llvmlite/ir/__init__.py +11 -0
  24. llvmlite/ir/_utils.py +80 -0
  25. llvmlite/ir/builder.py +1120 -0
  26. llvmlite/ir/context.py +20 -0
  27. llvmlite/ir/instructions.py +920 -0
  28. llvmlite/ir/module.py +246 -0
  29. llvmlite/ir/transforms.py +64 -0
  30. llvmlite/ir/types.py +734 -0
  31. llvmlite/ir/values.py +1217 -0
  32. llvmlite/tests/__init__.py +57 -0
  33. llvmlite/tests/__main__.py +3 -0
  34. llvmlite/tests/customize.py +407 -0
  35. llvmlite/tests/refprune_proto.py +329 -0
  36. llvmlite/tests/test_binding.py +3208 -0
  37. llvmlite/tests/test_ir.py +2986 -0
  38. llvmlite/tests/test_refprune.py +730 -0
  39. llvmlite/tests/test_valuerepr.py +60 -0
  40. llvmlite/utils.py +29 -0
  41. llvmlite-0.44.0rc1.dist-info/LICENSE +24 -0
  42. llvmlite-0.44.0rc1.dist-info/LICENSE.thirdparty +225 -0
  43. llvmlite-0.44.0rc1.dist-info/METADATA +138 -0
  44. llvmlite-0.44.0rc1.dist-info/RECORD +46 -0
  45. llvmlite-0.44.0rc1.dist-info/WHEEL +6 -0
  46. llvmlite-0.44.0rc1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,2986 @@
1
+ """
2
+ IR Construction Tests
3
+ """
4
+
5
+ import copy
6
+ import itertools
7
+ import pickle
8
+ import re
9
+ import textwrap
10
+ import unittest
11
+
12
+ from . import TestCase
13
+ from llvmlite import ir
14
+ from llvmlite import binding as llvm
15
+
16
+ # FIXME: Remove me once typed pointers are no longer supported.
17
+ from llvmlite import opaque_pointers_enabled
18
+
19
+
20
+ int1 = ir.IntType(1)
21
+ int8 = ir.IntType(8)
22
+ int16 = ir.IntType(16)
23
+ int32 = ir.IntType(32)
24
+ int64 = ir.IntType(64)
25
+ hlf = ir.HalfType()
26
+ flt = ir.FloatType()
27
+ dbl = ir.DoubleType()
28
+
29
+
30
+ class TestBase(TestCase):
31
+ """
32
+ Utilities for IR tests.
33
+ """
34
+
35
+ def assertInText(self, pattern, text):
36
+ """
37
+ Assert *pattern* is in *text*, ignoring any whitespace differences
38
+ (including newlines).
39
+ """
40
+
41
+ def escape(c):
42
+ if not c.isalnum() and not c.isspace():
43
+ return '\\' + c
44
+ return c
45
+
46
+ pattern = ''.join(map(escape, pattern))
47
+ regex = re.sub(r'\s+', r'\\s*', pattern)
48
+ self.assertRegex(text, regex)
49
+
50
+ def assert_ir_line(self, line, mod):
51
+ lines = [line.strip() for line in str(mod).splitlines()]
52
+ self.assertIn(line, lines)
53
+
54
+ def assert_valid_ir(self, mod):
55
+ llvm.parse_assembly(str(mod))
56
+
57
+ def assert_pickle_correctly(self, irobject):
58
+ """Assert that the IR object pickles and unpickles correctly.
59
+ The IR string is equal and that their type is equal
60
+ """
61
+ newobject = pickle.loads(pickle.dumps(irobject, protocol=-1))
62
+ self.assertIs(irobject.__class__, newobject.__class__)
63
+ self.assertEqual(str(irobject), str(newobject))
64
+ return newobject
65
+
66
+ def module(self):
67
+ return ir.Module()
68
+
69
+ def function(self, module=None, name='my_func'):
70
+ module = module or self.module()
71
+ fnty = ir.FunctionType(int32, (int32, int32, dbl,
72
+ ir.PointerType(int32)))
73
+ return ir.Function(module, fnty, name)
74
+
75
+ def block(self, func=None, name=''):
76
+ func = func or self.function()
77
+ return func.append_basic_block(name)
78
+
79
+ def descr(self, thing):
80
+ buf = []
81
+ thing.descr(buf)
82
+ return "".join(buf)
83
+
84
+ def _normalize_asm(self, asm):
85
+ asm = textwrap.dedent(asm)
86
+ # Normalize indent
87
+ asm = asm.replace("\n ", "\n ")
88
+ return asm
89
+
90
+ def check_descr_regex(self, descr, asm):
91
+ expected = self._normalize_asm(asm)
92
+ self.assertRegex(descr, expected)
93
+
94
+ def check_descr(self, descr, asm):
95
+ expected = self._normalize_asm(asm)
96
+ self.assertEqual(descr, expected)
97
+
98
+ def check_block(self, block, asm):
99
+ self.check_descr(self.descr(block), asm)
100
+
101
+ def check_block_regex(self, block, asm):
102
+ self.check_descr_regex(self.descr(block), asm)
103
+
104
+ def check_module_body(self, module, asm):
105
+ expected = self._normalize_asm(asm)
106
+ actual = module._stringify_body()
107
+ self.assertEqual(actual.strip(), expected.strip())
108
+
109
+ def check_metadata(self, module, asm):
110
+ """
111
+ Check module metadata against *asm*.
112
+ """
113
+ expected = self._normalize_asm(asm)
114
+ actual = module._stringify_metadata()
115
+ self.assertEqual(actual.strip(), expected.strip())
116
+
117
+ def check_func_body(self, func, asm):
118
+ expected = self._normalize_asm(asm)
119
+ actual = self.descr(func)
120
+ actual = actual.partition('{')[2].rpartition('}')[0]
121
+ self.assertEqual(actual.strip(), expected.strip())
122
+
123
+
124
+ class TestFunction(TestBase):
125
+
126
+ # FIXME: Remove `else' once TP are no longer supported.
127
+ proto = \
128
+ """i32 @"my_func"(i32 %".1", i32 %".2", double %".3", ptr %".4")""" \
129
+ if opaque_pointers_enabled else \
130
+ """i32 @"my_func"(i32 %".1", i32 %".2", double %".3", i32* %".4")"""
131
+
132
+ def test_declare(self):
133
+ # A simple declaration
134
+ func = self.function()
135
+ asm = self.descr(func).strip()
136
+ self.assertEqual(asm.strip(), "declare %s" % self.proto)
137
+
138
+ def test_declare_attributes(self):
139
+ # Now with function attributes
140
+ func = self.function()
141
+ func.attributes.add("optsize")
142
+ func.attributes.add("alwaysinline")
143
+ func.attributes.add("convergent")
144
+ func.attributes.alignstack = 16
145
+ tp_pers = ir.FunctionType(int8, (), var_arg=True)
146
+ pers = ir.Function(self.module(), tp_pers, '__gxx_personality_v0')
147
+ func.attributes.personality = pers
148
+ asm = self.descr(func).strip()
149
+ # FIXME: Remove `else' once TP are no longer supported.
150
+ if opaque_pointers_enabled:
151
+ self.assertEqual(asm,
152
+ ("declare %s alwaysinline convergent optsize "
153
+ "alignstack(16) "
154
+ "personality ptr @\"__gxx_personality_v0\"") %
155
+ self.proto)
156
+ else:
157
+ self.assertEqual(asm,
158
+ ("declare %s alwaysinline convergent optsize "
159
+ "alignstack(16) personality "
160
+ "i8 (...)* @\"__gxx_personality_v0\"") %
161
+ self.proto)
162
+ # Check pickling
163
+ self.assert_pickle_correctly(func)
164
+
165
+ def test_function_attributes(self):
166
+ # Now with parameter attributes
167
+ func = self.function()
168
+ func.args[0].add_attribute("zeroext")
169
+ func.args[1].attributes.dereferenceable = 5
170
+ func.args[1].attributes.dereferenceable_or_null = 10
171
+ func.args[3].attributes.align = 4
172
+ func.args[3].add_attribute("nonnull")
173
+ func.return_value.add_attribute("noalias")
174
+ asm = self.descr(func).strip()
175
+ # FIXME: Remove `else' once TP are no longer supported.
176
+ if opaque_pointers_enabled:
177
+ self.assertEqual(asm,
178
+ """declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", ptr nonnull align 4 %".4")""" # noqa E501
179
+ )
180
+ else:
181
+ self.assertEqual(asm,
182
+ """declare noalias i32 @"my_func"(i32 zeroext %".1", i32 dereferenceable(5) dereferenceable_or_null(10) %".2", double %".3", i32* nonnull align 4 %".4")""" # noqa E501
183
+ )
184
+ # Check pickling
185
+ self.assert_pickle_correctly(func)
186
+
187
+ def test_function_metadata(self):
188
+ # Now with function metadata
189
+ module = self.module()
190
+ func = self.function(module)
191
+ func.set_metadata('dbg', module.add_metadata([]))
192
+ asm = self.descr(func).strip()
193
+ self.assertEqual(asm,
194
+ f'declare {self.proto} !dbg !0'
195
+ )
196
+ # Check pickling
197
+ self.assert_pickle_correctly(func)
198
+
199
+ def test_function_section(self):
200
+ # Test function with section
201
+ func = self.function()
202
+ func.section = "a_section"
203
+ asm = self.descr(func).strip()
204
+ self.assertEqual(asm,
205
+ f'declare {self.proto} section "a_section"'
206
+ )
207
+ # Check pickling
208
+ self.assert_pickle_correctly(func)
209
+
210
+ def test_function_section_meta(self):
211
+ # Test function with section and metadata
212
+ module = self.module()
213
+ func = self.function(module)
214
+ func.section = "a_section"
215
+ func.set_metadata('dbg', module.add_metadata([]))
216
+ asm = self.descr(func).strip()
217
+ self.assertEqual(asm,
218
+ f'declare {self.proto} section "a_section" !dbg !0'
219
+ )
220
+ # Check pickling
221
+ self.assert_pickle_correctly(func)
222
+
223
+ def test_function_attr_meta(self):
224
+ # Test function with attributes and metadata
225
+ module = self.module()
226
+ func = self.function(module)
227
+ func.attributes.add("alwaysinline")
228
+ func.set_metadata('dbg', module.add_metadata([]))
229
+ asm = self.descr(func).strip()
230
+ self.assertEqual(asm,
231
+ f'declare {self.proto} alwaysinline !dbg !0'
232
+ )
233
+ # Check pickling
234
+ self.assert_pickle_correctly(func)
235
+
236
+ def test_function_attr_section(self):
237
+ # Test function with attributes and section
238
+ func = self.function()
239
+ func.attributes.add("optsize")
240
+ func.section = "a_section"
241
+ asm = self.descr(func).strip()
242
+ self.assertEqual(asm,
243
+ f'declare {self.proto} optsize section "a_section"')
244
+ # Check pickling
245
+ self.assert_pickle_correctly(func)
246
+
247
+ def test_function_attr_section_meta(self):
248
+ # Test function with attributes, section and metadata
249
+ module = self.module()
250
+ func = self.function(module)
251
+ func.attributes.add("alwaysinline")
252
+ func.section = "a_section"
253
+ func.set_metadata('dbg', module.add_metadata([]))
254
+ asm = self.descr(func).strip()
255
+ self.assertEqual(asm,
256
+ f'declare {self.proto} alwaysinline section "a_section" !dbg !0' # noqa E501
257
+ )
258
+ # Check pickling
259
+ self.assert_pickle_correctly(func)
260
+
261
+ def test_define(self):
262
+ # A simple definition
263
+ func = self.function()
264
+ func.attributes.add("alwaysinline")
265
+ block = func.append_basic_block('my_block')
266
+ builder = ir.IRBuilder(block)
267
+ builder.ret_void()
268
+ asm = self.descr(func)
269
+ self.check_descr(asm, """\
270
+ define {proto} alwaysinline
271
+ {{
272
+ my_block:
273
+ ret void
274
+ }}
275
+ """.format(proto=self.proto))
276
+
277
+ def test_declare_intrinsics(self):
278
+ module = self.module()
279
+ pint8 = int8.as_pointer()
280
+
281
+ powi = module.declare_intrinsic('llvm.powi', [dbl])
282
+ memset = module.declare_intrinsic('llvm.memset', [pint8, int32])
283
+ memcpy = module.declare_intrinsic('llvm.memcpy', [pint8, pint8, int32])
284
+ assume = module.declare_intrinsic('llvm.assume')
285
+ self.check_descr(self.descr(powi).strip(), """\
286
+ declare double @"llvm.powi.f64"(double %".1", i32 %".2")""")
287
+ # FIXME: Remove `else' once TP are no longer supported.
288
+ if opaque_pointers_enabled:
289
+ self.check_descr(self.descr(memset).strip(), """\
290
+ declare void @"llvm.memset.p0i8.i32"(ptr %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501
291
+ self.check_descr(self.descr(memcpy).strip(), """\
292
+ declare void @"llvm.memcpy.p0i8.p0i8.i32"(ptr %".1", ptr %".2", i32 %".3", i1 %".4")""") # noqa E501
293
+ else:
294
+ self.check_descr(self.descr(memset).strip(), """\
295
+ declare void @"llvm.memset.p0i8.i32"(i8* %".1", i8 %".2", i32 %".3", i1 %".4")""") # noqa E501
296
+ self.check_descr(self.descr(memcpy).strip(), """\
297
+ declare void @"llvm.memcpy.p0i8.p0i8.i32"(i8* %".1", i8* %".2", i32 %".3", i1 %".4")""") # noqa E501
298
+ self.check_descr(self.descr(assume).strip(), """\
299
+ declare void @"llvm.assume"(i1 %".1")""")
300
+
301
+ def test_redeclare_intrinsic(self):
302
+ module = self.module()
303
+ powi = module.declare_intrinsic('llvm.powi', [dbl])
304
+ powi2 = module.declare_intrinsic('llvm.powi', [dbl])
305
+ self.assertIs(powi, powi2)
306
+
307
+ def test_pickling(self):
308
+ fn = self.function()
309
+ self.assert_pickle_correctly(fn)
310
+
311
+ def test_alwaysinline_noinline_disallowed(self):
312
+ module = self.module()
313
+ func = self.function(module)
314
+ func.attributes.add('alwaysinline')
315
+
316
+ msg = "Can't have alwaysinline and noinline"
317
+ with self.assertRaisesRegex(ValueError, msg):
318
+ func.attributes.add('noinline')
319
+
320
+ def test_noinline_alwaysinline_disallowed(self):
321
+ module = self.module()
322
+ func = self.function(module)
323
+ func.attributes.add('noinline')
324
+
325
+ msg = "Can't have alwaysinline and noinline"
326
+ with self.assertRaisesRegex(ValueError, msg):
327
+ func.attributes.add('alwaysinline')
328
+
329
+
330
+ class TestIR(TestBase):
331
+
332
+ def test_unnamed_metadata(self):
333
+ # An unnamed metadata node
334
+ mod = self.module()
335
+ mod.add_metadata([int32(123), int8(42)])
336
+ self.assert_ir_line("!0 = !{ i32 123, i8 42 }", mod)
337
+ self.assert_valid_ir(mod)
338
+
339
+ def test_unnamed_metadata_2(self):
340
+ # Several unnamed metadata nodes
341
+ mod = self.module()
342
+ # First node has a literal metadata string
343
+ m0 = mod.add_metadata([int32(123), "kernel"])
344
+ # Second node refers to the first one
345
+ m1 = mod.add_metadata([int64(456), m0])
346
+ # Third node is the same as the second one
347
+ m2 = mod.add_metadata([int64(456), m0])
348
+ self.assertIs(m2, m1)
349
+ # Fourth node refers to the first three
350
+ mod.add_metadata([m0, m1, m2])
351
+ self.assert_ir_line('!0 = !{ i32 123, !"kernel" }', mod)
352
+ self.assert_ir_line('!1 = !{ i64 456, !0 }', mod)
353
+ self.assert_ir_line('!2 = !{ !0, !1, !1 }', mod)
354
+
355
+ def test_unnamed_metadata_3(self):
356
+ # Passing nested metadata as a sequence
357
+ mod = self.module()
358
+ mod.add_metadata([int32(123), [int32(456)], [int32(789)], [int32(456)]])
359
+ self.assert_ir_line('!0 = !{ i32 456 }', mod)
360
+ self.assert_ir_line('!1 = !{ i32 789 }', mod)
361
+ self.assert_ir_line('!2 = !{ i32 123, !0, !1, !0 }', mod)
362
+
363
+ def test_metadata_string(self):
364
+ # Escaping contents of a metadata string
365
+ mod = self.module()
366
+ mod.add_metadata(["\"\\$"])
367
+ self.assert_ir_line('!0 = !{ !"\\22\\5c$" }', mod)
368
+
369
+ def test_named_metadata(self):
370
+ # Add a named metadata node and add metadata values to it
371
+ mod = self.module()
372
+ m0 = mod.add_metadata([int32(123)])
373
+ m1 = mod.add_metadata([int64(456)])
374
+ nmd = mod.add_named_metadata("foo")
375
+ nmd.add(m0)
376
+ nmd.add(m1)
377
+ nmd.add(m0)
378
+ self.assert_ir_line("!foo = !{ !0, !1, !0 }", mod)
379
+ self.assert_valid_ir(mod)
380
+ # Check get_named_metadata()
381
+ self.assertIs(nmd, mod.get_named_metadata("foo"))
382
+ with self.assertRaises(KeyError):
383
+ mod.get_named_metadata("bar")
384
+
385
+ def test_named_metadata_2(self):
386
+ # Add and set named metadata through a single add_named_metadata() call
387
+ mod = self.module()
388
+ m0 = mod.add_metadata([int32(123)])
389
+ mod.add_named_metadata("foo", m0)
390
+ mod.add_named_metadata("foo", [int64(456)])
391
+ mod.add_named_metadata("foo", ["kernel"])
392
+ mod.add_named_metadata("bar", [])
393
+ self.assert_ir_line("!foo = !{ !0, !1, !2 }", mod)
394
+ self.assert_ir_line("!0 = !{ i32 123 }", mod)
395
+ self.assert_ir_line("!1 = !{ i64 456 }", mod)
396
+ self.assert_ir_line('!2 = !{ !"kernel" }', mod)
397
+ self.assert_ir_line("!bar = !{ !3 }", mod)
398
+ self.assert_ir_line('!3 = !{ }', mod)
399
+ self.assert_valid_ir(mod)
400
+
401
+ def test_metadata_null(self):
402
+ # A null metadata (typed) value
403
+ mod = self.module()
404
+ mod.add_metadata([int32.as_pointer()(None)])
405
+ # FIXME: Remove `else' once TP are no longer supported.
406
+ if opaque_pointers_enabled:
407
+ self.assert_ir_line("!0 = !{ ptr null }", mod)
408
+ else:
409
+ self.assert_ir_line("!0 = !{ i32* null }", mod)
410
+ self.assert_valid_ir(mod)
411
+ # A null metadata (untyped) value
412
+ mod = self.module()
413
+ mod.add_metadata([None, int32(123)])
414
+ self.assert_ir_line("!0 = !{ null, i32 123 }", mod)
415
+ self.assert_valid_ir(mod)
416
+
417
+ def test_debug_info(self):
418
+ # Add real world-looking debug information to a module
419
+ # (with various value types)
420
+ mod = self.module()
421
+ di_file = mod.add_debug_info("DIFile", {
422
+ "filename": "foo",
423
+ "directory": "bar",
424
+ })
425
+ di_func_type = mod.add_debug_info("DISubroutineType", {
426
+ # None as `null`
427
+ "types": mod.add_metadata([None]),
428
+ })
429
+ di_compileunit = mod.add_debug_info("DICompileUnit", {
430
+ "language": ir.DIToken("DW_LANG_Python"),
431
+ "file": di_file,
432
+ "producer": "ARTIQ",
433
+ "runtimeVersion": 0,
434
+ "isOptimized": True,
435
+ }, is_distinct=True)
436
+ mod.add_debug_info("DISubprogram", {
437
+ "name": "my_func",
438
+ "file": di_file,
439
+ "line": 11,
440
+ "type": di_func_type,
441
+ "isLocal": False,
442
+ "unit": di_compileunit,
443
+ }, is_distinct=True)
444
+
445
+ # Check output
446
+ strmod = str(mod)
447
+ self.assert_ir_line('!0 = !DIFile(directory: "bar", filename: "foo")',
448
+ strmod)
449
+ self.assert_ir_line('!1 = !{ null }', strmod)
450
+ self.assert_ir_line('!2 = !DISubroutineType(types: !1)', strmod)
451
+ # self.assert_ir_line('!4 = !{ !3 }', strmod)
452
+ self.assert_ir_line('!3 = distinct !DICompileUnit(file: !0, '
453
+ 'isOptimized: true, language: DW_LANG_Python, '
454
+ 'producer: "ARTIQ", runtimeVersion: 0)',
455
+ strmod)
456
+ self.assert_ir_line('!4 = distinct !DISubprogram(file: !0, isLocal: '
457
+ 'false, line: 11, name: "my_func", type: !2, unit: '
458
+ '!3)',
459
+ strmod)
460
+ self.assert_valid_ir(mod)
461
+
462
+ def test_debug_info_2(self):
463
+ # Identical debug info nodes should be merged
464
+ mod = self.module()
465
+ di1 = mod.add_debug_info("DIFile",
466
+ {"filename": "foo",
467
+ "directory": "bar",
468
+ })
469
+ di2 = mod.add_debug_info("DIFile",
470
+ {"filename": "foo",
471
+ "directory": "bar",
472
+ })
473
+ di3 = mod.add_debug_info("DIFile",
474
+ {"filename": "bar",
475
+ "directory": "foo",
476
+ })
477
+ di4 = mod.add_debug_info("DIFile",
478
+ {"filename": "foo",
479
+ "directory": "bar",
480
+ }, is_distinct=True)
481
+ self.assertIs(di1, di2)
482
+ self.assertEqual(len({di1, di2, di3, di4}), 3)
483
+ # Check output
484
+ strmod = str(mod)
485
+ self.assert_ir_line('!0 = !DIFile(directory: "bar", filename: "foo")',
486
+ strmod)
487
+ self.assert_ir_line('!1 = !DIFile(directory: "foo", filename: "bar")',
488
+ strmod)
489
+ self.assert_ir_line('!2 = distinct !DIFile(directory: "bar", filename: '
490
+ '"foo")', strmod)
491
+ self.assert_valid_ir(mod)
492
+
493
+ def test_debug_info_gvar(self):
494
+ # This test defines a module with a global variable named 'gvar'.
495
+ # When the module is compiled and linked with a main function, gdb can
496
+ # be used to interpret and print the the value of 'gvar'.
497
+ mod = self.module()
498
+
499
+ gvar = ir.GlobalVariable(mod, ir.FloatType(), 'gvar')
500
+ gvar.initializer = ir.Constant(ir.FloatType(), 42)
501
+
502
+ di_float = mod.add_debug_info("DIBasicType", {
503
+ "name": "float",
504
+ "size": 32,
505
+ "encoding": ir.DIToken("DW_ATE_float")
506
+ })
507
+ di_gvar = mod.add_debug_info("DIGlobalVariableExpression", {
508
+ "expr": mod.add_debug_info("DIExpression", {}),
509
+ "var": mod.add_debug_info("DIGlobalVariable", {
510
+ "name": gvar.name,
511
+ "type": di_float,
512
+ "isDefinition": True
513
+ }, is_distinct=True)
514
+ })
515
+ gvar.set_metadata('dbg', di_gvar)
516
+
517
+ # Check output
518
+ strmod = str(mod)
519
+ self.assert_ir_line('!0 = !DIBasicType(encoding: DW_ATE_float, '
520
+ 'name: "float", size: 32)', strmod)
521
+ self.assert_ir_line('!1 = !DIExpression()', strmod)
522
+ self.assert_ir_line('!2 = distinct !DIGlobalVariable(isDefinition: '
523
+ 'true, name: "gvar", type: !0)', strmod)
524
+ self.assert_ir_line('!3 = !DIGlobalVariableExpression(expr: !1, '
525
+ 'var: !2)', strmod)
526
+ self.assert_ir_line('@"gvar" = global float 0x4045000000000000, '
527
+ '!dbg !3', strmod)
528
+
529
+ # The remaining debug info is not part of the automated test, but
530
+ # can be used to produce an object file that can be loaded into a
531
+ # debugger to print the value of gvar. This can be done by printing the
532
+ # module then compiling it with clang and inspecting with gdb:
533
+ #
534
+ # clang test_debug_info_gvar.ll -c
535
+ # printf "file test_debug_info_gvar.o \n p gvar" | gdb
536
+ #
537
+ # Which should result in the output:
538
+ #
539
+ # (gdb) $1 = 42
540
+
541
+ dver = [ir.IntType(32)(2), 'Dwarf Version', ir.IntType(32)(4)]
542
+ diver = [ir.IntType(32)(2), 'Debug Info Version', ir.IntType(32)(3)]
543
+ dver = mod.add_metadata(dver)
544
+ diver = mod.add_metadata(diver)
545
+ flags = mod.add_named_metadata('llvm.module.flags')
546
+ flags.add(dver)
547
+ flags.add(diver)
548
+
549
+ di_file = mod.add_debug_info("DIFile", {
550
+ "filename": "foo",
551
+ "directory": "bar",
552
+ })
553
+ di_cu = mod.add_debug_info("DICompileUnit", {
554
+ "language": ir.DIToken("DW_LANG_Python"),
555
+ "file": di_file,
556
+ 'emissionKind': ir.DIToken('FullDebug'),
557
+ "globals": mod.add_metadata([di_gvar])
558
+ }, is_distinct=True)
559
+ mod.add_named_metadata('llvm.dbg.cu', di_cu)
560
+
561
+ def test_debug_info_unicode_string(self):
562
+ mod = self.module()
563
+ mod.add_debug_info("DILocalVariable", {"name": "a∆"})
564
+ # Check output
565
+ strmod = str(mod)
566
+ # The unicode character is utf8 encoded with \XX format, where XX is hex
567
+ name = ''.join(map(lambda x: f"\\{x:02x}", "∆".encode()))
568
+ self.assert_ir_line(f'!0 = !DILocalVariable(name: "a{name}")', strmod)
569
+
570
+ def test_inline_assembly(self):
571
+ mod = self.module()
572
+ foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo')
573
+ builder = ir.IRBuilder(foo.append_basic_block(''))
574
+ asmty = ir.FunctionType(int32, [int32])
575
+ asm = ir.InlineAsm(asmty, "mov $1, $2", "=r,r", side_effect=True)
576
+ builder.call(asm, [int32(123)])
577
+ builder.ret_void()
578
+ pat = 'call i32 asm sideeffect "mov $1, $2", "=r,r" ( i32 123 )'
579
+ self.assertInText(pat, str(mod))
580
+ self.assert_valid_ir(mod)
581
+
582
+ def test_builder_asm(self):
583
+ mod = self.module()
584
+ foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo')
585
+ builder = ir.IRBuilder(foo.append_basic_block(''))
586
+ asmty = ir.FunctionType(int32, [int32])
587
+ builder.asm(asmty, "mov $1, $2", "=r,r", [int32(123)], side_effect=True)
588
+ builder.ret_void()
589
+ pat = 'call i32 asm sideeffect "mov $1, $2", "=r,r" ( i32 123 )'
590
+ self.assertInText(pat, str(mod))
591
+ self.assert_valid_ir(mod)
592
+
593
+ def test_builder_load_reg(self):
594
+ mod = self.module()
595
+ foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo')
596
+ builder = ir.IRBuilder(foo.append_basic_block(''))
597
+ builder.load_reg(ir.IntType(64), "rax")
598
+ builder.ret_void()
599
+ pat = 'call i64 asm "", "={rax}"'
600
+ self.assertInText(pat, str(mod))
601
+ self.assert_valid_ir(mod)
602
+
603
+ def test_builder_store_reg(self):
604
+ mod = self.module()
605
+ foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo')
606
+ builder = ir.IRBuilder(foo.append_basic_block(''))
607
+ builder.store_reg(int64(123), ir.IntType(64), "rax")
608
+ builder.ret_void()
609
+ pat = 'call void asm sideeffect "", "{rax}" ( i64 123 )'
610
+ self.assertInText(pat, str(mod))
611
+ self.assert_valid_ir(mod)
612
+
613
+
614
+ class TestGlobalValues(TestBase):
615
+
616
+ def test_globals_access(self):
617
+ mod = self.module()
618
+ foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'foo')
619
+ ir.Function(mod, ir.FunctionType(ir.VoidType(), []), 'bar')
620
+ globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble')
621
+ self.assertEqual(mod.get_global('foo'), foo)
622
+ self.assertEqual(mod.get_global('globdouble'), globdouble)
623
+ with self.assertRaises(KeyError):
624
+ mod.get_global('kkk')
625
+ # Globals should have a useful repr()
626
+ # FIXME: Remove `else' once TP are no longer supported.
627
+ if opaque_pointers_enabled:
628
+ self.assertEqual(repr(globdouble),
629
+ "<ir.GlobalVariable 'globdouble' of type 'ptr'>")
630
+ else:
631
+ self.assertEqual(
632
+ repr(globdouble),
633
+ "<ir.GlobalVariable 'globdouble' of type 'double*'>")
634
+
635
+ def test_functions_global_values_access(self):
636
+ """
637
+ Accessing functions and global values through Module.functions
638
+ and Module.global_values.
639
+ """
640
+ mod = self.module()
641
+ fty = ir.FunctionType(ir.VoidType(), [])
642
+ foo = ir.Function(mod, fty, 'foo')
643
+ bar = ir.Function(mod, fty, 'bar')
644
+ globdouble = ir.GlobalVariable(mod, ir.DoubleType(), 'globdouble')
645
+ self.assertEqual(set(mod.functions), set((foo, bar)))
646
+ self.assertEqual(set(mod.global_values), set((foo, bar, globdouble)))
647
+
648
+ def test_global_variables_ir(self):
649
+ """
650
+ IR serialization of global variables.
651
+ """
652
+ mod = self.module()
653
+ # the following have side effects and write to self.module()
654
+ a = ir.GlobalVariable(mod, int8, 'a') # noqa F841
655
+ b = ir.GlobalVariable(mod, int8, 'b', addrspace=42) # noqa F841
656
+ # Initialized global variable doesn't default to "external"
657
+ c = ir.GlobalVariable(mod, int32, 'c')
658
+ c.initializer = int32(123)
659
+ d = ir.GlobalVariable(mod, int32, 'd')
660
+ d.global_constant = True
661
+ # Non-external linkage implies default "undef" initializer
662
+ e = ir.GlobalVariable(mod, int32, 'e')
663
+ e.linkage = "internal"
664
+ f = ir.GlobalVariable(mod, int32, 'f', addrspace=456)
665
+ f.unnamed_addr = True
666
+ g = ir.GlobalVariable(mod, int32, 'g')
667
+ g.linkage = "internal"
668
+ g.initializer = int32(123)
669
+ g.align = 16
670
+ h = ir.GlobalVariable(mod, int32, 'h')
671
+ h.linkage = "internal"
672
+ h.initializer = int32(123)
673
+ h.section = "h_section"
674
+ i = ir.GlobalVariable(mod, int32, 'i')
675
+ i.linkage = "internal"
676
+ i.initializer = int32(456)
677
+ i.align = 8
678
+ i.section = "i_section"
679
+ self.check_module_body(mod, """\
680
+ @"a" = external global i8
681
+ @"b" = external addrspace(42) global i8
682
+ @"c" = global i32 123
683
+ @"d" = external constant i32
684
+ @"e" = internal global i32 undef
685
+ @"f" = external unnamed_addr addrspace(456) global i32
686
+ @"g" = internal global i32 123, align 16
687
+ @"h" = internal global i32 123, section "h_section"
688
+ @"i" = internal global i32 456, section "i_section", align 8
689
+ """)
690
+
691
+ def test_pickle(self):
692
+ mod = self.module()
693
+ self.assert_pickle_correctly(mod)
694
+
695
+
696
+ class TestBlock(TestBase):
697
+
698
+ def test_attributes(self):
699
+ func = self.function()
700
+ block = ir.Block(parent=func, name='start')
701
+ self.assertIs(block.parent, func)
702
+ self.assertFalse(block.is_terminated)
703
+
704
+ def test_descr(self):
705
+ block = self.block(name='my_block')
706
+ self.assertEqual(self.descr(block), "my_block:\n")
707
+ block.instructions.extend(['a', 'b'])
708
+ self.assertEqual(self.descr(block), "my_block:\n a\n b\n")
709
+
710
+ def test_replace(self):
711
+ block = self.block(name='my_block')
712
+ builder = ir.IRBuilder(block)
713
+ a, b = builder.function.args[:2]
714
+ c = builder.add(a, b, 'c')
715
+ d = builder.sub(a, b, 'd')
716
+ builder.mul(d, b, 'e')
717
+ f = ir.Instruction(block, a.type, 'sdiv', (c, b), 'f')
718
+ self.check_block(block, """\
719
+ my_block:
720
+ %"c" = add i32 %".1", %".2"
721
+ %"d" = sub i32 %".1", %".2"
722
+ %"e" = mul i32 %"d", %".2"
723
+ """)
724
+ block.replace(d, f)
725
+ self.check_block(block, """\
726
+ my_block:
727
+ %"c" = add i32 %".1", %".2"
728
+ %"f" = sdiv i32 %"c", %".2"
729
+ %"e" = mul i32 %"f", %".2"
730
+ """)
731
+
732
+ def test_repr(self):
733
+ """
734
+ Blocks should have a useful repr()
735
+ """
736
+ func = self.function()
737
+ block = ir.Block(parent=func, name='start')
738
+ self.assertEqual(repr(block), "<ir.Block 'start' of type 'label'>")
739
+
740
+
741
+ class TestBuildInstructions(TestBase):
742
+ """
743
+ Test IR generation of LLVM instructions through the IRBuilder class.
744
+ """
745
+
746
+ maxDiff = 4000
747
+
748
+ def test_simple(self):
749
+ block = self.block(name='my_block')
750
+ builder = ir.IRBuilder(block)
751
+ a, b = builder.function.args[:2]
752
+ inst = builder.add(a, b, 'res')
753
+ self.check_block(block, """\
754
+ my_block:
755
+ %"res" = add i32 %".1", %".2"
756
+ """)
757
+ # Instructions should have a useful repr()
758
+ self.assertEqual(repr(inst),
759
+ "<ir.Instruction 'res' of type 'i32', opname 'add', "
760
+ "operands (<ir.Argument '.1' of type i32>, "
761
+ "<ir.Argument '.2' of type i32>)>")
762
+
763
+ def test_binops(self):
764
+ block = self.block(name='my_block')
765
+ builder = ir.IRBuilder(block)
766
+ a, b, ff = builder.function.args[:3]
767
+ builder.add(a, b, 'c')
768
+ builder.fadd(a, b, 'd')
769
+ builder.sub(a, b, 'e')
770
+ builder.fsub(a, b, 'f')
771
+ builder.mul(a, b, 'g')
772
+ builder.fmul(a, b, 'h')
773
+ builder.udiv(a, b, 'i')
774
+ builder.sdiv(a, b, 'j')
775
+ builder.fdiv(a, b, 'k')
776
+ builder.urem(a, b, 'l')
777
+ builder.srem(a, b, 'm')
778
+ builder.frem(a, b, 'n')
779
+ builder.or_(a, b, 'o')
780
+ builder.and_(a, b, 'p')
781
+ builder.xor(a, b, 'q')
782
+ builder.shl(a, b, 'r')
783
+ builder.ashr(a, b, 's')
784
+ builder.lshr(a, b, 't')
785
+ with self.assertRaises(ValueError) as cm:
786
+ builder.add(a, ff)
787
+ self.assertEqual(str(cm.exception),
788
+ "Operands must be the same type, got (i32, double)")
789
+ self.assertFalse(block.is_terminated)
790
+ self.check_block(block, """\
791
+ my_block:
792
+ %"c" = add i32 %".1", %".2"
793
+ %"d" = fadd i32 %".1", %".2"
794
+ %"e" = sub i32 %".1", %".2"
795
+ %"f" = fsub i32 %".1", %".2"
796
+ %"g" = mul i32 %".1", %".2"
797
+ %"h" = fmul i32 %".1", %".2"
798
+ %"i" = udiv i32 %".1", %".2"
799
+ %"j" = sdiv i32 %".1", %".2"
800
+ %"k" = fdiv i32 %".1", %".2"
801
+ %"l" = urem i32 %".1", %".2"
802
+ %"m" = srem i32 %".1", %".2"
803
+ %"n" = frem i32 %".1", %".2"
804
+ %"o" = or i32 %".1", %".2"
805
+ %"p" = and i32 %".1", %".2"
806
+ %"q" = xor i32 %".1", %".2"
807
+ %"r" = shl i32 %".1", %".2"
808
+ %"s" = ashr i32 %".1", %".2"
809
+ %"t" = lshr i32 %".1", %".2"
810
+ """)
811
+
812
+ def test_binop_flags(self):
813
+ block = self.block(name='my_block')
814
+ builder = ir.IRBuilder(block)
815
+ a, b = builder.function.args[:2]
816
+ # As tuple
817
+ builder.add(a, b, 'c', flags=('nuw',))
818
+ # and as list
819
+ builder.sub(a, b, 'd', flags=['nuw', 'nsw'])
820
+ self.check_block(block, """\
821
+ my_block:
822
+ %"c" = add nuw i32 %".1", %".2"
823
+ %"d" = sub nuw nsw i32 %".1", %".2"
824
+ """)
825
+
826
+ def test_binop_fastmath_flags(self):
827
+ block = self.block(name='my_block')
828
+ builder = ir.IRBuilder(block)
829
+ a, b = builder.function.args[:2]
830
+ # As tuple
831
+ builder.fadd(a, b, 'c', flags=('fast',))
832
+ # and as list
833
+ builder.fsub(a, b, 'd', flags=['ninf', 'nsz'])
834
+ self.check_block(block, """\
835
+ my_block:
836
+ %"c" = fadd fast i32 %".1", %".2"
837
+ %"d" = fsub ninf nsz i32 %".1", %".2"
838
+ """)
839
+
840
+ def test_binops_with_overflow(self):
841
+ block = self.block(name='my_block')
842
+ builder = ir.IRBuilder(block)
843
+ a, b = builder.function.args[:2]
844
+ builder.sadd_with_overflow(a, b, 'c')
845
+ builder.smul_with_overflow(a, b, 'd')
846
+ builder.ssub_with_overflow(a, b, 'e')
847
+ builder.uadd_with_overflow(a, b, 'f')
848
+ builder.umul_with_overflow(a, b, 'g')
849
+ builder.usub_with_overflow(a, b, 'h')
850
+ self.check_block(block, """\
851
+ my_block:
852
+ %"c" = call {i32, i1} @"llvm.sadd.with.overflow.i32"(i32 %".1", i32 %".2")
853
+ %"d" = call {i32, i1} @"llvm.smul.with.overflow.i32"(i32 %".1", i32 %".2")
854
+ %"e" = call {i32, i1} @"llvm.ssub.with.overflow.i32"(i32 %".1", i32 %".2")
855
+ %"f" = call {i32, i1} @"llvm.uadd.with.overflow.i32"(i32 %".1", i32 %".2")
856
+ %"g" = call {i32, i1} @"llvm.umul.with.overflow.i32"(i32 %".1", i32 %".2")
857
+ %"h" = call {i32, i1} @"llvm.usub.with.overflow.i32"(i32 %".1", i32 %".2")
858
+ """)
859
+
860
+ def test_unary_ops(self):
861
+ block = self.block(name='my_block')
862
+ builder = ir.IRBuilder(block)
863
+ a, b, c = builder.function.args[:3]
864
+ builder.neg(a, 'd')
865
+ builder.not_(b, 'e')
866
+ builder.fneg(c, 'f')
867
+ self.assertFalse(block.is_terminated)
868
+ self.check_block(block, """\
869
+ my_block:
870
+ %"d" = sub i32 0, %".1"
871
+ %"e" = xor i32 %".2", -1
872
+ %"f" = fneg double %".3"
873
+ """)
874
+
875
+ def test_replace_operand(self):
876
+ block = self.block(name='my_block')
877
+ builder = ir.IRBuilder(block)
878
+ a, b = builder.function.args[:2]
879
+ undef1 = ir.Constant(ir.IntType(32), ir.Undefined)
880
+ undef2 = ir.Constant(ir.IntType(32), ir.Undefined)
881
+ c = builder.add(undef1, undef2, 'c')
882
+ self.check_block(block, """\
883
+ my_block:
884
+ %"c" = add i32 undef, undef
885
+ """)
886
+ c.replace_usage(undef1, a)
887
+ c.replace_usage(undef2, b)
888
+ self.check_block(block, """\
889
+ my_block:
890
+ %"c" = add i32 %".1", %".2"
891
+ """)
892
+
893
+ def test_integer_comparisons(self):
894
+ block = self.block(name='my_block')
895
+ builder = ir.IRBuilder(block)
896
+ a, b = builder.function.args[:2]
897
+ builder.icmp_unsigned('==', a, b, 'c')
898
+ builder.icmp_unsigned('!=', a, b, 'd')
899
+ builder.icmp_unsigned('<', a, b, 'e')
900
+ builder.icmp_unsigned('<=', a, b, 'f')
901
+ builder.icmp_unsigned('>', a, b, 'g')
902
+ builder.icmp_unsigned('>=', a, b, 'h')
903
+ builder.icmp_signed('==', a, b, 'i')
904
+ builder.icmp_signed('!=', a, b, 'j')
905
+ builder.icmp_signed('<', a, b, 'k')
906
+ builder.icmp_signed('<=', a, b, 'l')
907
+ builder.icmp_signed('>', a, b, 'm')
908
+ builder.icmp_signed('>=', a, b, 'n')
909
+ with self.assertRaises(ValueError):
910
+ builder.icmp_signed('uno', a, b, 'zz')
911
+ with self.assertRaises(ValueError):
912
+ builder.icmp_signed('foo', a, b, 'zz')
913
+ self.assertFalse(block.is_terminated)
914
+ self.check_block(block, """\
915
+ my_block:
916
+ %"c" = icmp eq i32 %".1", %".2"
917
+ %"d" = icmp ne i32 %".1", %".2"
918
+ %"e" = icmp ult i32 %".1", %".2"
919
+ %"f" = icmp ule i32 %".1", %".2"
920
+ %"g" = icmp ugt i32 %".1", %".2"
921
+ %"h" = icmp uge i32 %".1", %".2"
922
+ %"i" = icmp eq i32 %".1", %".2"
923
+ %"j" = icmp ne i32 %".1", %".2"
924
+ %"k" = icmp slt i32 %".1", %".2"
925
+ %"l" = icmp sle i32 %".1", %".2"
926
+ %"m" = icmp sgt i32 %".1", %".2"
927
+ %"n" = icmp sge i32 %".1", %".2"
928
+ """)
929
+
930
+ def test_float_comparisons(self):
931
+ block = self.block(name='my_block')
932
+ builder = ir.IRBuilder(block)
933
+ a, b = builder.function.args[:2]
934
+ builder.fcmp_ordered('==', a, b, 'c')
935
+ builder.fcmp_ordered('!=', a, b, 'd')
936
+ builder.fcmp_ordered('<', a, b, 'e')
937
+ builder.fcmp_ordered('<=', a, b, 'f')
938
+ builder.fcmp_ordered('>', a, b, 'g')
939
+ builder.fcmp_ordered('>=', a, b, 'h')
940
+ builder.fcmp_unordered('==', a, b, 'i')
941
+ builder.fcmp_unordered('!=', a, b, 'j')
942
+ builder.fcmp_unordered('<', a, b, 'k')
943
+ builder.fcmp_unordered('<=', a, b, 'l')
944
+ builder.fcmp_unordered('>', a, b, 'm')
945
+ builder.fcmp_unordered('>=', a, b, 'n')
946
+ # fcmp_ordered and fcmp_unordered are the same for these cases
947
+ builder.fcmp_ordered('ord', a, b, 'u')
948
+ builder.fcmp_ordered('uno', a, b, 'v')
949
+ builder.fcmp_unordered('ord', a, b, 'w')
950
+ builder.fcmp_unordered('uno', a, b, 'x')
951
+ builder.fcmp_unordered('olt', a, b, 'y',
952
+ flags=['nnan', 'ninf', 'nsz', 'arcp', 'fast'])
953
+ self.assertFalse(block.is_terminated)
954
+ self.check_block(block, """\
955
+ my_block:
956
+ %"c" = fcmp oeq i32 %".1", %".2"
957
+ %"d" = fcmp one i32 %".1", %".2"
958
+ %"e" = fcmp olt i32 %".1", %".2"
959
+ %"f" = fcmp ole i32 %".1", %".2"
960
+ %"g" = fcmp ogt i32 %".1", %".2"
961
+ %"h" = fcmp oge i32 %".1", %".2"
962
+ %"i" = fcmp ueq i32 %".1", %".2"
963
+ %"j" = fcmp une i32 %".1", %".2"
964
+ %"k" = fcmp ult i32 %".1", %".2"
965
+ %"l" = fcmp ule i32 %".1", %".2"
966
+ %"m" = fcmp ugt i32 %".1", %".2"
967
+ %"n" = fcmp uge i32 %".1", %".2"
968
+ %"u" = fcmp ord i32 %".1", %".2"
969
+ %"v" = fcmp uno i32 %".1", %".2"
970
+ %"w" = fcmp ord i32 %".1", %".2"
971
+ %"x" = fcmp uno i32 %".1", %".2"
972
+ %"y" = fcmp nnan ninf nsz arcp fast olt i32 %".1", %".2"
973
+ """)
974
+
975
+ def test_misc_ops(self):
976
+ block = self.block(name='my_block')
977
+ t = ir.Constant(int1, True)
978
+ builder = ir.IRBuilder(block)
979
+ a, b = builder.function.args[:2]
980
+ builder.select(t, a, b, 'c', flags=('arcp', 'nnan'))
981
+ self.assertFalse(block.is_terminated)
982
+ builder.unreachable()
983
+ self.assertTrue(block.is_terminated)
984
+ self.check_block(block, """\
985
+ my_block:
986
+ %"c" = select arcp nnan i1 true, i32 %".1", i32 %".2"
987
+ unreachable
988
+ """)
989
+
990
+ def test_phi(self):
991
+ block = self.block(name='my_block')
992
+ builder = ir.IRBuilder(block)
993
+ a, b = builder.function.args[:2]
994
+ bb2 = builder.function.append_basic_block('b2')
995
+ bb3 = builder.function.append_basic_block('b3')
996
+ phi = builder.phi(int32, 'my_phi', flags=('fast',))
997
+ phi.add_incoming(a, bb2)
998
+ phi.add_incoming(b, bb3)
999
+ self.assertFalse(block.is_terminated)
1000
+ self.check_block(block, """\
1001
+ my_block:
1002
+ %"my_phi" = phi fast i32 [%".1", %"b2"], [%".2", %"b3"]
1003
+ """)
1004
+
1005
+ def test_mem_ops(self):
1006
+ block = self.block(name='my_block')
1007
+ builder = ir.IRBuilder(block)
1008
+ a, b, z = builder.function.args[:3]
1009
+ c = builder.alloca(int32, name='c')
1010
+ d = builder.alloca(int32, size=42, name='d') # noqa F841
1011
+ e = builder.alloca(dbl, size=a, name='e')
1012
+ e.align = 8
1013
+ self.assertEqual(e.type, ir.PointerType(dbl))
1014
+ ee = builder.store(z, e)
1015
+ self.assertEqual(ee.type, ir.VoidType())
1016
+ f = builder.store(b, c)
1017
+ self.assertEqual(f.type, ir.VoidType())
1018
+ g = builder.load(c, 'g')
1019
+ self.assertEqual(g.type, int32)
1020
+ # With alignment
1021
+ h = builder.store(b, c, align=1)
1022
+ self.assertEqual(h.type, ir.VoidType())
1023
+ i = builder.load(c, 'i', align=1)
1024
+ self.assertEqual(i.type, int32)
1025
+ # Atomics
1026
+ j = builder.store_atomic(b, c, ordering="seq_cst", align=4)
1027
+ self.assertEqual(j.type, ir.VoidType())
1028
+ k = builder.load_atomic(c, ordering="seq_cst", align=4, name='k')
1029
+ self.assertEqual(k.type, int32)
1030
+ # Not pointer types
1031
+ with self.assertRaises(TypeError):
1032
+ builder.store(b, a)
1033
+ with self.assertRaises(TypeError):
1034
+ builder.load(b)
1035
+ # Mismatching pointer type
1036
+ with self.assertRaises(TypeError) as cm:
1037
+ builder.store(b, e)
1038
+ # FIXME: Remove `else' once TP are no longer supported.
1039
+ if opaque_pointers_enabled:
1040
+ self.assertEqual(str(cm.exception),
1041
+ "cannot store i32 to ptr: mismatching types")
1042
+ self.check_block(block, """\
1043
+ my_block:
1044
+ %"c" = alloca i32
1045
+ %"d" = alloca i32, i32 42
1046
+ %"e" = alloca double, i32 %".1", align 8
1047
+ store double %".3", ptr %"e"
1048
+ store i32 %".2", ptr %"c"
1049
+ %"g" = load i32, ptr %"c"
1050
+ store i32 %".2", ptr %"c", align 1
1051
+ %"i" = load i32, ptr %"c", align 1
1052
+ store atomic i32 %".2", ptr %"c" seq_cst, align 4
1053
+ %"k" = load atomic i32, ptr %"c" seq_cst, align 4
1054
+ """)
1055
+ else:
1056
+ self.assertEqual(str(cm.exception),
1057
+ "cannot store i32 to double*: mismatching types")
1058
+ self.check_block(block, """\
1059
+ my_block:
1060
+ %"c" = alloca i32
1061
+ %"d" = alloca i32, i32 42
1062
+ %"e" = alloca double, i32 %".1", align 8
1063
+ store double %".3", double* %"e"
1064
+ store i32 %".2", i32* %"c"
1065
+ %"g" = load i32, i32* %"c"
1066
+ store i32 %".2", i32* %"c", align 1
1067
+ %"i" = load i32, i32* %"c", align 1
1068
+ store atomic i32 %".2", i32* %"c" seq_cst, align 4
1069
+ %"k" = load atomic i32, i32* %"c" seq_cst, align 4
1070
+ """)
1071
+
1072
+ def test_gep(self):
1073
+ block = self.block(name='my_block')
1074
+ builder = ir.IRBuilder(block)
1075
+ a, b = builder.function.args[:2]
1076
+ c = builder.alloca(ir.PointerType(int32), name='c')
1077
+ d = builder.gep(c, [ir.Constant(int32, 5), a], name='d')
1078
+ self.assertEqual(d.type, ir.PointerType(int32))
1079
+ # FIXME: Remove `else' once TP are no longer supported.
1080
+ if opaque_pointers_enabled:
1081
+ self.check_block(block, """\
1082
+ my_block:
1083
+ %"c" = alloca ptr
1084
+ %"d" = getelementptr ptr, ptr %"c", i32 5, i32 %".1"
1085
+ """)
1086
+ else:
1087
+ self.check_block(block, """\
1088
+ my_block:
1089
+ %"c" = alloca i32*
1090
+ %"d" = getelementptr i32*, i32** %"c", i32 5, i32 %".1"
1091
+ """)
1092
+ # XXX test with more complex types
1093
+
1094
+ def test_gep_castinstr(self):
1095
+ # similar to:
1096
+ # numba::runtime::nrtdynmod.py_define_nrt_meminfo_data()
1097
+ block = self.block(name='my_block')
1098
+ builder = ir.IRBuilder(block)
1099
+ a, b = builder.function.args[:2]
1100
+ int8ptr = int8.as_pointer()
1101
+ ls = ir.LiteralStructType([int64, int8ptr, int8ptr, int8ptr, int64])
1102
+ d = builder.bitcast(a, ls.as_pointer(), name='d')
1103
+ e = builder.gep(d, [ir.Constant(int32, x) for x in [0, 3]], name='e')
1104
+ self.assertEqual(e.type, ir.PointerType(int8ptr))
1105
+ # FIXME: Remove `else' once TP are no longer supported.
1106
+ if opaque_pointers_enabled:
1107
+ self.check_block(block, """\
1108
+ my_block:
1109
+ %"d" = bitcast i32 %".1" to ptr
1110
+ %"e" = getelementptr {i64, ptr, ptr, ptr, i64}, ptr %"d", i32 0, i32 3
1111
+ """) # noqa E501
1112
+ else:
1113
+ self.check_block(block, """\
1114
+ my_block:
1115
+ %"d" = bitcast i32 %".1" to {i64, i8*, i8*, i8*, i64}*
1116
+ %"e" = getelementptr {i64, i8*, i8*, i8*, i64}, {i64, i8*, i8*, i8*, i64}* %"d", i32 0, i32 3
1117
+ """) # noqa E501
1118
+
1119
+ def test_gep_castinstr_addrspace(self):
1120
+ # similar to:
1121
+ # numba::runtime::nrtdynmod.py_define_nrt_meminfo_data()
1122
+ block = self.block(name='my_block')
1123
+ builder = ir.IRBuilder(block)
1124
+ a, b = builder.function.args[:2]
1125
+ addrspace = 4
1126
+ int8ptr = int8.as_pointer()
1127
+ ls = ir.LiteralStructType([int64, int8ptr, int8ptr, int8ptr, int64])
1128
+ d = builder.bitcast(a, ls.as_pointer(addrspace=addrspace), name='d')
1129
+ e = builder.gep(d, [ir.Constant(int32, x) for x in [0, 3]], name='e')
1130
+ self.assertEqual(e.type.addrspace, addrspace)
1131
+ self.assertEqual(e.type, ir.PointerType(int8ptr, addrspace=addrspace))
1132
+ # FIXME: Remove `else' once TP are no longer supported.
1133
+ if opaque_pointers_enabled:
1134
+ self.check_block(block, """\
1135
+ my_block:
1136
+ %"d" = bitcast i32 %".1" to ptr addrspace(4)
1137
+ %"e" = getelementptr {i64, ptr, ptr, ptr, i64}, ptr addrspace(4) %"d", i32 0, i32 3
1138
+ """) # noqa E501
1139
+ else:
1140
+ self.check_block(block, """\
1141
+ my_block:
1142
+ %"d" = bitcast i32 %".1" to {i64, i8*, i8*, i8*, i64} addrspace(4)*
1143
+ %"e" = getelementptr {i64, i8*, i8*, i8*, i64}, {i64, i8*, i8*, i8*, i64} addrspace(4)* %"d", i32 0, i32 3
1144
+ """) # noqa E501
1145
+
1146
+ def test_gep_addrspace(self):
1147
+ block = self.block(name='my_block')
1148
+ builder = ir.IRBuilder(block)
1149
+ a, b = builder.function.args[:2]
1150
+ addrspace = 4
1151
+ c = builder.alloca(ir.PointerType(int32, addrspace=addrspace), name='c')
1152
+ # FIXME: Remove `else' once TP are no longer supported.
1153
+ if opaque_pointers_enabled:
1154
+ self.assertEqual(str(c.type), 'ptr')
1155
+ else:
1156
+ self.assertEqual(str(c.type), 'i32 addrspace(4)**')
1157
+ self.assertEqual(c.type.pointee.addrspace, addrspace)
1158
+ d = builder.gep(c, [ir.Constant(int32, 5), a], name='d')
1159
+ self.assertEqual(d.type.addrspace, addrspace)
1160
+ e = builder.gep(d, [ir.Constant(int32, 10)], name='e')
1161
+ self.assertEqual(e.type.addrspace, addrspace)
1162
+ # FIXME: Remove `else' once TP are no longer supported.
1163
+ if opaque_pointers_enabled:
1164
+ self.check_block(block, """\
1165
+ my_block:
1166
+ %"c" = alloca ptr addrspace(4)
1167
+ %"d" = getelementptr ptr addrspace(4), ptr %"c", i32 5, i32 %".1"
1168
+ %"e" = getelementptr i32, ptr addrspace(4) %"d", i32 10
1169
+ """) # noqa E501
1170
+ else:
1171
+ self.check_block(block, """\
1172
+ my_block:
1173
+ %"c" = alloca i32 addrspace(4)*
1174
+ %"d" = getelementptr i32 addrspace(4)*, i32 addrspace(4)** %"c", i32 5, i32 %".1"
1175
+ %"e" = getelementptr i32, i32 addrspace(4)* %"d", i32 10
1176
+ """) # noqa E501
1177
+
1178
+ def test_extract_insert_value(self):
1179
+ block = self.block(name='my_block')
1180
+ builder = ir.IRBuilder(block)
1181
+ a, b = builder.function.args[:2]
1182
+ tp_inner = ir.LiteralStructType([int32, int1])
1183
+ tp_outer = ir.LiteralStructType([int8, tp_inner])
1184
+ c_inner = ir.Constant(tp_inner, (ir.Constant(int32, 4),
1185
+ ir.Constant(int1, True)))
1186
+ # Flat structure
1187
+ c = builder.extract_value(c_inner, 0, name='c') # noqa F841
1188
+ d = builder.insert_value(c_inner, a, 0, name='d') # noqa F841
1189
+ e = builder.insert_value(d, ir.Constant(int1, False), 1, name='e') # noqa F841 E501
1190
+ self.assertEqual(d.type, tp_inner)
1191
+ self.assertEqual(e.type, tp_inner)
1192
+ # Nested structure
1193
+ p_outer = builder.alloca(tp_outer, name='ptr')
1194
+ j = builder.load(p_outer, name='j')
1195
+ k = builder.extract_value(j, 0, name='k')
1196
+ l = builder.extract_value(j, 1, name='l')
1197
+ m = builder.extract_value(j, (1, 0), name='m')
1198
+ n = builder.extract_value(j, (1, 1), name='n')
1199
+ o = builder.insert_value(j, l, 1, name='o')
1200
+ p = builder.insert_value(j, a, (1, 0), name='p')
1201
+ self.assertEqual(k.type, int8)
1202
+ self.assertEqual(l.type, tp_inner)
1203
+ self.assertEqual(m.type, int32)
1204
+ self.assertEqual(n.type, int1)
1205
+ self.assertEqual(o.type, tp_outer)
1206
+ self.assertEqual(p.type, tp_outer)
1207
+
1208
+ with self.assertRaises(TypeError):
1209
+ # Not an aggregate
1210
+ builder.extract_value(p_outer, 0)
1211
+ with self.assertRaises(TypeError):
1212
+ # Indexing too deep
1213
+ builder.extract_value(c_inner, (0, 0))
1214
+ with self.assertRaises(TypeError):
1215
+ # Index out of structure bounds
1216
+ builder.extract_value(c_inner, 5)
1217
+ with self.assertRaises(TypeError):
1218
+ # Not an aggregate
1219
+ builder.insert_value(a, b, 0)
1220
+ with self.assertRaises(TypeError):
1221
+ # Replacement value has the wrong type
1222
+ builder.insert_value(c_inner, a, 1)
1223
+
1224
+ # FIXME: Remove `else' once TP are no longer supported.
1225
+ if opaque_pointers_enabled:
1226
+ self.check_block(block, """\
1227
+ my_block:
1228
+ %"c" = extractvalue {i32, i1} {i32 4, i1 true}, 0
1229
+ %"d" = insertvalue {i32, i1} {i32 4, i1 true}, i32 %".1", 0
1230
+ %"e" = insertvalue {i32, i1} %"d", i1 false, 1
1231
+ %"ptr" = alloca {i8, {i32, i1}}
1232
+ %"j" = load {i8, {i32, i1}}, ptr %"ptr"
1233
+ %"k" = extractvalue {i8, {i32, i1}} %"j", 0
1234
+ %"l" = extractvalue {i8, {i32, i1}} %"j", 1
1235
+ %"m" = extractvalue {i8, {i32, i1}} %"j", 1, 0
1236
+ %"n" = extractvalue {i8, {i32, i1}} %"j", 1, 1
1237
+ %"o" = insertvalue {i8, {i32, i1}} %"j", {i32, i1} %"l", 1
1238
+ %"p" = insertvalue {i8, {i32, i1}} %"j", i32 %".1", 1, 0
1239
+ """)
1240
+ else:
1241
+ self.check_block(block, """\
1242
+ my_block:
1243
+ %"c" = extractvalue {i32, i1} {i32 4, i1 true}, 0
1244
+ %"d" = insertvalue {i32, i1} {i32 4, i1 true}, i32 %".1", 0
1245
+ %"e" = insertvalue {i32, i1} %"d", i1 false, 1
1246
+ %"ptr" = alloca {i8, {i32, i1}}
1247
+ %"j" = load {i8, {i32, i1}}, {i8, {i32, i1}}* %"ptr"
1248
+ %"k" = extractvalue {i8, {i32, i1}} %"j", 0
1249
+ %"l" = extractvalue {i8, {i32, i1}} %"j", 1
1250
+ %"m" = extractvalue {i8, {i32, i1}} %"j", 1, 0
1251
+ %"n" = extractvalue {i8, {i32, i1}} %"j", 1, 1
1252
+ %"o" = insertvalue {i8, {i32, i1}} %"j", {i32, i1} %"l", 1
1253
+ %"p" = insertvalue {i8, {i32, i1}} %"j", i32 %".1", 1, 0
1254
+ """)
1255
+
1256
+ def test_cast_ops(self):
1257
+ block = self.block(name='my_block')
1258
+ builder = ir.IRBuilder(block)
1259
+ a, b, fa, ptr = builder.function.args[:4]
1260
+ c = builder.trunc(a, int8, name='c')
1261
+ d = builder.zext(c, int32, name='d') # noqa F841
1262
+ e = builder.sext(c, int32, name='e') # noqa F841
1263
+ fb = builder.fptrunc(fa, flt, 'fb')
1264
+ fc = builder.fpext(fb, dbl, 'fc') # noqa F841
1265
+ g = builder.fptoui(fa, int32, 'g')
1266
+ h = builder.fptosi(fa, int8, 'h')
1267
+ fd = builder.uitofp(g, flt, 'fd') # noqa F841
1268
+ fe = builder.sitofp(h, dbl, 'fe') # noqa F841
1269
+ i = builder.ptrtoint(ptr, int32, 'i')
1270
+ j = builder.inttoptr(i, ir.PointerType(int8), 'j') # noqa F841
1271
+ k = builder.bitcast(a, flt, "k") # noqa F841
1272
+ self.assertFalse(block.is_terminated)
1273
+ # FIXME: Remove `else' once TP are no longer supported.
1274
+ if opaque_pointers_enabled:
1275
+ self.check_block(block, """\
1276
+ my_block:
1277
+ %"c" = trunc i32 %".1" to i8
1278
+ %"d" = zext i8 %"c" to i32
1279
+ %"e" = sext i8 %"c" to i32
1280
+ %"fb" = fptrunc double %".3" to float
1281
+ %"fc" = fpext float %"fb" to double
1282
+ %"g" = fptoui double %".3" to i32
1283
+ %"h" = fptosi double %".3" to i8
1284
+ %"fd" = uitofp i32 %"g" to float
1285
+ %"fe" = sitofp i8 %"h" to double
1286
+ %"i" = ptrtoint ptr %".4" to i32
1287
+ %"j" = inttoptr i32 %"i" to ptr
1288
+ %"k" = bitcast i32 %".1" to float
1289
+ """)
1290
+ else:
1291
+ self.check_block(block, """\
1292
+ my_block:
1293
+ %"c" = trunc i32 %".1" to i8
1294
+ %"d" = zext i8 %"c" to i32
1295
+ %"e" = sext i8 %"c" to i32
1296
+ %"fb" = fptrunc double %".3" to float
1297
+ %"fc" = fpext float %"fb" to double
1298
+ %"g" = fptoui double %".3" to i32
1299
+ %"h" = fptosi double %".3" to i8
1300
+ %"fd" = uitofp i32 %"g" to float
1301
+ %"fe" = sitofp i8 %"h" to double
1302
+ %"i" = ptrtoint i32* %".4" to i32
1303
+ %"j" = inttoptr i32 %"i" to i8*
1304
+ %"k" = bitcast i32 %".1" to float
1305
+ """)
1306
+
1307
+ def test_atomicrmw(self):
1308
+ block = self.block(name='my_block')
1309
+ builder = ir.IRBuilder(block)
1310
+ a, b = builder.function.args[:2]
1311
+ c = builder.alloca(int32, name='c')
1312
+ d = builder.atomic_rmw('add', c, a, 'monotonic', 'd')
1313
+ self.assertEqual(d.type, int32)
1314
+ # FIXME: Remove `else' once TP are no longer supported.
1315
+ if opaque_pointers_enabled:
1316
+ self.check_block(block, """\
1317
+ my_block:
1318
+ %"c" = alloca i32
1319
+ %"d" = atomicrmw add ptr %"c", i32 %".1" monotonic
1320
+ """)
1321
+ else:
1322
+ self.check_block(block, """\
1323
+ my_block:
1324
+ %"c" = alloca i32
1325
+ %"d" = atomicrmw add i32* %"c", i32 %".1" monotonic
1326
+ """)
1327
+
1328
+ def test_branch(self):
1329
+ block = self.block(name='my_block')
1330
+ builder = ir.IRBuilder(block)
1331
+ bb_target = builder.function.append_basic_block(name='target')
1332
+ builder.branch(bb_target)
1333
+ self.assertTrue(block.is_terminated)
1334
+ self.check_block(block, """\
1335
+ my_block:
1336
+ br label %"target"
1337
+ """)
1338
+
1339
+ def test_cbranch(self):
1340
+ block = self.block(name='my_block')
1341
+ builder = ir.IRBuilder(block)
1342
+ bb_true = builder.function.append_basic_block(name='b_true')
1343
+ bb_false = builder.function.append_basic_block(name='b_false')
1344
+ builder.cbranch(ir.Constant(int1, False), bb_true, bb_false)
1345
+ self.assertTrue(block.is_terminated)
1346
+ self.check_block(block, """\
1347
+ my_block:
1348
+ br i1 false, label %"b_true", label %"b_false"
1349
+ """)
1350
+
1351
+ def test_cbranch_weights(self):
1352
+ block = self.block(name='my_block')
1353
+ builder = ir.IRBuilder(block)
1354
+ bb_true = builder.function.append_basic_block(name='b_true')
1355
+ bb_false = builder.function.append_basic_block(name='b_false')
1356
+ br = builder.cbranch(ir.Constant(int1, False), bb_true, bb_false)
1357
+ br.set_weights([5, 42])
1358
+ self.assertTrue(block.is_terminated)
1359
+ self.check_block(block, """\
1360
+ my_block:
1361
+ br i1 false, label %"b_true", label %"b_false", !prof !0
1362
+ """)
1363
+ self.check_metadata(builder.module, """\
1364
+ !0 = !{ !"branch_weights", i32 5, i32 42 }
1365
+ """)
1366
+
1367
+ def test_branch_indirect(self):
1368
+ block = self.block(name='my_block')
1369
+ builder = ir.IRBuilder(block)
1370
+ bb_1 = builder.function.append_basic_block(name='b_1')
1371
+ bb_2 = builder.function.append_basic_block(name='b_2')
1372
+ indirectbr = builder.branch_indirect(
1373
+ ir.BlockAddress(builder.function, bb_1))
1374
+ indirectbr.add_destination(bb_1)
1375
+ indirectbr.add_destination(bb_2)
1376
+ self.assertTrue(block.is_terminated)
1377
+ # FIXME: Remove `else' once TP are no longer supported.
1378
+ if opaque_pointers_enabled:
1379
+ self.check_block(block, """\
1380
+ my_block:
1381
+ indirectbr ptr blockaddress(@"my_func", %"b_1"), [label %"b_1", label %"b_2"]
1382
+ """) # noqa E501
1383
+ else:
1384
+ self.check_block(block, """\
1385
+ my_block:
1386
+ indirectbr i8* blockaddress(@"my_func", %"b_1"), [label %"b_1", label %"b_2"]
1387
+ """) # noqa E501
1388
+
1389
+ def test_returns(self):
1390
+ def check(block, expected_ir):
1391
+ self.assertTrue(block.is_terminated)
1392
+ self.check_block(block, expected_ir)
1393
+
1394
+ block = self.block(name='my_block')
1395
+ builder = ir.IRBuilder(block)
1396
+ builder.ret_void()
1397
+ check(block, """\
1398
+ my_block:
1399
+ ret void
1400
+ """)
1401
+
1402
+ block = self.block(name='other_block')
1403
+ builder = ir.IRBuilder(block)
1404
+ builder.ret(int32(5))
1405
+ check(block, """\
1406
+ other_block:
1407
+ ret i32 5
1408
+ """)
1409
+
1410
+ # With metadata
1411
+ block = self.block(name='my_block')
1412
+ builder = ir.IRBuilder(block)
1413
+ inst = builder.ret_void()
1414
+ inst.set_metadata("dbg", block.module.add_metadata(()))
1415
+ check(block, """\
1416
+ my_block:
1417
+ ret void, !dbg !0
1418
+ """)
1419
+
1420
+ block = self.block(name='my_block')
1421
+ builder = ir.IRBuilder(block)
1422
+ inst = builder.ret(int32(6))
1423
+ inst.set_metadata("dbg", block.module.add_metadata(()))
1424
+ check(block, """\
1425
+ my_block:
1426
+ ret i32 6, !dbg !0
1427
+ """)
1428
+
1429
+ def test_switch(self):
1430
+ block = self.block(name='my_block')
1431
+ builder = ir.IRBuilder(block)
1432
+ a, b = builder.function.args[:2]
1433
+ bb_onzero = builder.function.append_basic_block(name='onzero')
1434
+ bb_onone = builder.function.append_basic_block(name='onone')
1435
+ bb_ontwo = builder.function.append_basic_block(name='ontwo')
1436
+ bb_else = builder.function.append_basic_block(name='otherwise')
1437
+ sw = builder.switch(a, bb_else)
1438
+ sw.add_case(ir.Constant(int32, 0), bb_onzero)
1439
+ sw.add_case(ir.Constant(int32, 1), bb_onone)
1440
+ # A plain Python value gets converted into the right IR constant
1441
+ sw.add_case(2, bb_ontwo)
1442
+ self.assertTrue(block.is_terminated)
1443
+ self.check_block(block, """\
1444
+ my_block:
1445
+ switch i32 %".1", label %"otherwise" [i32 0, label %"onzero" i32 1, label %"onone" i32 2, label %"ontwo"]
1446
+ """) # noqa E501
1447
+
1448
+ def test_call(self):
1449
+ block = self.block(name='my_block')
1450
+ builder = ir.IRBuilder(block)
1451
+ a, b = builder.function.args[:2]
1452
+ tp_f = ir.FunctionType(flt, (int32, int32))
1453
+ tp_g = ir.FunctionType(dbl, (int32,), var_arg=True)
1454
+ tp_h = ir.FunctionType(hlf, (int32, int32))
1455
+ f = ir.Function(builder.function.module, tp_f, 'f')
1456
+ g = ir.Function(builder.function.module, tp_g, 'g')
1457
+ h = ir.Function(builder.function.module, tp_h, 'h')
1458
+ builder.call(f, (a, b), 'res_f')
1459
+ builder.call(g, (b, a), 'res_g')
1460
+ builder.call(h, (a, b), 'res_h')
1461
+ builder.call(f, (a, b), 'res_f_fast', cconv='fastcc')
1462
+ res_f_readonly = builder.call(f, (a, b), 'res_f_readonly')
1463
+ res_f_readonly.attributes.add('readonly')
1464
+ builder.call(f, (a, b), 'res_fast', fastmath='fast')
1465
+ builder.call(f, (a, b), 'res_nnan_ninf', fastmath=('nnan', 'ninf'))
1466
+ builder.call(f, (a, b), 'res_noinline', attrs='noinline')
1467
+ builder.call(f, (a, b), 'res_alwaysinline', attrs='alwaysinline')
1468
+ builder.call(f, (a, b), 'res_noinline_ro', attrs=('noinline',
1469
+ 'readonly'))
1470
+ builder.call(f, (a, b), 'res_convergent', attrs='convergent')
1471
+ self.check_block(block, """\
1472
+ my_block:
1473
+ %"res_f" = call float @"f"(i32 %".1", i32 %".2")
1474
+ %"res_g" = call double (i32, ...) @"g"(i32 %".2", i32 %".1")
1475
+ %"res_h" = call half @"h"(i32 %".1", i32 %".2")
1476
+ %"res_f_fast" = call fastcc float @"f"(i32 %".1", i32 %".2")
1477
+ %"res_f_readonly" = call float @"f"(i32 %".1", i32 %".2") readonly
1478
+ %"res_fast" = call fast float @"f"(i32 %".1", i32 %".2")
1479
+ %"res_nnan_ninf" = call ninf nnan float @"f"(i32 %".1", i32 %".2")
1480
+ %"res_noinline" = call float @"f"(i32 %".1", i32 %".2") noinline
1481
+ %"res_alwaysinline" = call float @"f"(i32 %".1", i32 %".2") alwaysinline
1482
+ %"res_noinline_ro" = call float @"f"(i32 %".1", i32 %".2") noinline readonly
1483
+ %"res_convergent" = call float @"f"(i32 %".1", i32 %".2") convergent
1484
+ """) # noqa E501
1485
+
1486
+ def test_call_metadata(self):
1487
+ """
1488
+ Function calls with metadata arguments.
1489
+ """
1490
+ block = self.block(name='my_block')
1491
+ builder = ir.IRBuilder(block)
1492
+ dbg_declare_ty = ir.FunctionType(ir.VoidType(), [ir.MetaDataType()] * 3)
1493
+ dbg_declare = ir.Function(
1494
+ builder.module,
1495
+ dbg_declare_ty,
1496
+ 'llvm.dbg.declare')
1497
+ a = builder.alloca(int32, name="a")
1498
+ b = builder.module.add_metadata(())
1499
+ builder.call(dbg_declare, (a, b, b))
1500
+ # FIXME: Remove `else' once TP are no longer supported.
1501
+ if opaque_pointers_enabled:
1502
+ self.check_block(block, """\
1503
+ my_block:
1504
+ %"a" = alloca i32
1505
+ call void @"llvm.dbg.declare"(metadata ptr %"a", metadata !0, metadata !0)
1506
+ """) # noqa E501
1507
+ else:
1508
+ self.check_block(block, """\
1509
+ my_block:
1510
+ %"a" = alloca i32
1511
+ call void @"llvm.dbg.declare"(metadata i32* %"a", metadata !0, metadata !0)
1512
+ """) # noqa E501
1513
+
1514
+ def test_call_attributes(self):
1515
+ block = self.block(name='my_block')
1516
+ builder = ir.IRBuilder(block)
1517
+ fun_ty = ir.FunctionType(
1518
+ ir.VoidType(), (int32.as_pointer(), int32, int32.as_pointer()))
1519
+ fun = ir.Function(builder.function.module, fun_ty, 'fun')
1520
+ fun.args[0].add_attribute('sret')
1521
+ retval = builder.alloca(int32, name='retval')
1522
+ other = builder.alloca(int32, name='other')
1523
+ builder.call(
1524
+ fun,
1525
+ (retval, ir.Constant(int32, 42), other),
1526
+ arg_attrs={
1527
+ 0: ('sret', 'noalias'),
1528
+ 2: 'noalias'
1529
+ }
1530
+ )
1531
+ # FIXME: Remove `else' once TP are no longer supported.
1532
+ if opaque_pointers_enabled:
1533
+ self.check_block_regex(block, """\
1534
+ my_block:
1535
+ %"retval" = alloca i32
1536
+ %"other" = alloca i32
1537
+ call void @"fun"\\(ptr noalias sret(\\(i32\\))? %"retval", i32 42, ptr noalias %"other"\\)
1538
+ """) # noqa E501
1539
+ else:
1540
+ self.check_block_regex(block, """\
1541
+ my_block:
1542
+ %"retval" = alloca i32
1543
+ %"other" = alloca i32
1544
+ call void @"fun"\\(i32\\* noalias sret(\\(i32\\))? %"retval", i32 42, i32\\* noalias %"other"\\)
1545
+ """) # noqa E501
1546
+
1547
+ def test_call_tail(self):
1548
+ block = self.block(name='my_block')
1549
+ builder = ir.IRBuilder(block)
1550
+ fun_ty = ir.FunctionType(ir.VoidType(), ())
1551
+ fun = ir.Function(builder.function.module, fun_ty, 'my_fun')
1552
+
1553
+ builder.call(fun, ())
1554
+ builder.call(fun, (), tail=False)
1555
+ builder.call(fun, (), tail=True)
1556
+ builder.call(fun, (), tail='tail')
1557
+ builder.call(fun, (), tail='notail')
1558
+ builder.call(fun, (), tail='musttail')
1559
+ builder.call(fun, (), tail=[]) # This is a falsy value
1560
+ builder.call(fun, (), tail='not a marker') # This is a truthy value
1561
+
1562
+ self.check_block(block, """\
1563
+ my_block:
1564
+ call void @"my_fun"()
1565
+ call void @"my_fun"()
1566
+ tail call void @"my_fun"()
1567
+ tail call void @"my_fun"()
1568
+ notail call void @"my_fun"()
1569
+ musttail call void @"my_fun"()
1570
+ call void @"my_fun"()
1571
+ tail call void @"my_fun"()
1572
+ """) # noqa E501
1573
+
1574
+ def test_invalid_call_attributes(self):
1575
+ block = self.block()
1576
+ builder = ir.IRBuilder(block)
1577
+ fun_ty = ir.FunctionType(ir.VoidType(), ())
1578
+ fun = ir.Function(builder.function.module, fun_ty, 'fun')
1579
+ with self.assertRaises(ValueError):
1580
+ # The function has no arguments, so this should fail.
1581
+ builder.call(fun, (), arg_attrs={0: 'sret'})
1582
+
1583
+ def test_invoke(self):
1584
+ block = self.block(name='my_block')
1585
+ builder = ir.IRBuilder(block)
1586
+ a, b = builder.function.args[:2]
1587
+ tp_f = ir.FunctionType(flt, (int32, int32))
1588
+ f = ir.Function(builder.function.module, tp_f, 'f')
1589
+ bb_normal = builder.function.append_basic_block(name='normal')
1590
+ bb_unwind = builder.function.append_basic_block(name='unwind')
1591
+ builder.invoke(f, (a, b), bb_normal, bb_unwind, 'res_f')
1592
+ self.check_block(block, """\
1593
+ my_block:
1594
+ %"res_f" = invoke float @"f"(i32 %".1", i32 %".2")
1595
+ to label %"normal" unwind label %"unwind"
1596
+ """)
1597
+
1598
+ def test_invoke_attributes(self):
1599
+ block = self.block(name='my_block')
1600
+ builder = ir.IRBuilder(block)
1601
+ fun_ty = ir.FunctionType(
1602
+ ir.VoidType(), (int32.as_pointer(), int32, int32.as_pointer()))
1603
+ fun = ir.Function(builder.function.module, fun_ty, 'fun')
1604
+ fun.calling_convention = "fastcc"
1605
+ fun.args[0].add_attribute('sret')
1606
+ retval = builder.alloca(int32, name='retval')
1607
+ other = builder.alloca(int32, name='other')
1608
+ bb_normal = builder.function.append_basic_block(name='normal')
1609
+ bb_unwind = builder.function.append_basic_block(name='unwind')
1610
+ builder.invoke(
1611
+ fun,
1612
+ (retval, ir.Constant(int32, 42), other),
1613
+ bb_normal,
1614
+ bb_unwind,
1615
+ cconv='fastcc',
1616
+ fastmath='fast',
1617
+ attrs='noinline',
1618
+ arg_attrs={
1619
+ 0: ('sret', 'noalias'),
1620
+ 2: 'noalias'
1621
+ }
1622
+ )
1623
+ # FIXME: Remove `else' once TP are no longer supported.
1624
+ if opaque_pointers_enabled:
1625
+ self.check_block_regex(block, """\
1626
+ my_block:
1627
+ %"retval" = alloca i32
1628
+ %"other" = alloca i32
1629
+ invoke fast fastcc void @"fun"\\(ptr noalias sret(\\(i32\\))? %"retval", i32 42, ptr noalias %"other"\\) noinline
1630
+ to label %"normal" unwind label %"unwind"
1631
+ """) # noqa E501
1632
+ else:
1633
+ self.check_block_regex(block, """\
1634
+ my_block:
1635
+ %"retval" = alloca i32
1636
+ %"other" = alloca i32
1637
+ invoke fast fastcc void @"fun"\\(i32\\* noalias sret(\\(i32\\))? %"retval", i32 42, i32\\* noalias %"other"\\) noinline
1638
+ to label %"normal" unwind label %"unwind"
1639
+ """) # noqa E501
1640
+
1641
+ def test_landingpad(self):
1642
+ block = self.block(name='my_block')
1643
+ builder = ir.IRBuilder(block)
1644
+ lp = builder.landingpad(ir.LiteralStructType([int32,
1645
+ int8.as_pointer()]), 'lp')
1646
+ int_typeinfo = ir.GlobalVariable(builder.function.module,
1647
+ int8.as_pointer(), "_ZTIi")
1648
+ int_typeinfo.global_constant = True
1649
+ lp.add_clause(ir.CatchClause(int_typeinfo))
1650
+ lp.add_clause(ir.FilterClause(ir.Constant(ir.ArrayType(
1651
+ int_typeinfo.type, 1), [int_typeinfo])))
1652
+ builder.resume(lp)
1653
+ # FIXME: Remove `else' once TP are no longer supported.
1654
+ if opaque_pointers_enabled:
1655
+ self.check_block(block, """\
1656
+ my_block:
1657
+ %"lp" = landingpad {i32, ptr}
1658
+ catch ptr @"_ZTIi"
1659
+ filter [1 x ptr] [ptr @"_ZTIi"]
1660
+ resume {i32, ptr} %"lp"
1661
+ """)
1662
+ else:
1663
+ self.check_block(block, """\
1664
+ my_block:
1665
+ %"lp" = landingpad {i32, i8*}
1666
+ catch i8** @"_ZTIi"
1667
+ filter [1 x i8**] [i8** @"_ZTIi"]
1668
+ resume {i32, i8*} %"lp"
1669
+ """)
1670
+
1671
+ def test_assume(self):
1672
+ block = self.block(name='my_block')
1673
+ builder = ir.IRBuilder(block)
1674
+ a, b = builder.function.args[:2]
1675
+ c = builder.icmp_signed('>', a, b, name='c')
1676
+ builder.assume(c)
1677
+ self.check_block(block, """\
1678
+ my_block:
1679
+ %"c" = icmp sgt i32 %".1", %".2"
1680
+ call void @"llvm.assume"(i1 %"c")
1681
+ """)
1682
+
1683
+ def test_vector_ops(self):
1684
+ block = self.block(name='insert_block')
1685
+ builder = ir.IRBuilder(block)
1686
+ a, b = builder.function.args[:2]
1687
+ a.name = 'a'
1688
+ b.name = 'b'
1689
+
1690
+ vecty = ir.VectorType(a.type, 2)
1691
+ vec = ir.Constant(vecty, ir.Undefined)
1692
+ idxty = ir.IntType(32)
1693
+ vec = builder.insert_element(vec, a, idxty(0), name='vec1')
1694
+ vec = builder.insert_element(vec, b, idxty(1), name='vec2')
1695
+
1696
+ self.check_block(block, """\
1697
+ insert_block:
1698
+ %"vec1" = insertelement <2 x i32> <i32 undef, i32 undef>, i32 %"a", i32 0
1699
+ %"vec2" = insertelement <2 x i32> %"vec1", i32 %"b", i32 1
1700
+ """)
1701
+
1702
+ block = builder.append_basic_block("shuffle_block")
1703
+ builder.branch(block)
1704
+ builder.position_at_end(block)
1705
+
1706
+ mask = ir.Constant(vecty, [1, 0])
1707
+ builder.shuffle_vector(vec, vec, mask, name='shuf')
1708
+
1709
+ self.check_block(block, """\
1710
+ shuffle_block:
1711
+ %"shuf" = shufflevector <2 x i32> %"vec2", <2 x i32> %"vec2", <2 x i32> <i32 1, i32 0>
1712
+ """) # noqa E501
1713
+
1714
+ block = builder.append_basic_block("add_block")
1715
+ builder.branch(block)
1716
+ builder.position_at_end(block)
1717
+
1718
+ builder.add(vec, vec, name='sum')
1719
+
1720
+ self.check_block(block, """\
1721
+ add_block:
1722
+ %"sum" = add <2 x i32> %"vec2", %"vec2"
1723
+ """)
1724
+
1725
+ block = builder.append_basic_block("extract_block")
1726
+ builder.branch(block)
1727
+ builder.position_at_end(block)
1728
+
1729
+ c = builder.extract_element(vec, idxty(0), name='ex1')
1730
+ d = builder.extract_element(vec, idxty(1), name='ex2')
1731
+
1732
+ self.check_block(block, """\
1733
+ extract_block:
1734
+ %"ex1" = extractelement <2 x i32> %"vec2", i32 0
1735
+ %"ex2" = extractelement <2 x i32> %"vec2", i32 1
1736
+ """)
1737
+
1738
+ builder.ret(builder.add(c, d))
1739
+ self.assert_valid_ir(builder.module)
1740
+
1741
+ def test_bitreverse(self):
1742
+ block = self.block(name='my_block')
1743
+ builder = ir.IRBuilder(block)
1744
+ a = ir.Constant(int64, 5)
1745
+ c = builder.bitreverse(a, name='c')
1746
+ builder.ret(c)
1747
+ self.check_block(block, """\
1748
+ my_block:
1749
+ %"c" = call i64 @"llvm.bitreverse.i64"(i64 5)
1750
+ ret i64 %"c"
1751
+ """)
1752
+
1753
+ def test_bitreverse_wrongtype(self):
1754
+ block = self.block(name='my_block')
1755
+ builder = ir.IRBuilder(block)
1756
+ a = ir.Constant(flt, 5)
1757
+
1758
+ with self.assertRaises(TypeError) as raises:
1759
+ builder.bitreverse(a, name='c')
1760
+ self.assertIn(
1761
+ "expected an integer type, got float",
1762
+ str(raises.exception))
1763
+
1764
+ def test_fence(self):
1765
+ block = self.block(name='my_block')
1766
+ builder = ir.IRBuilder(block)
1767
+ with self.assertRaises(ValueError) as raises:
1768
+ builder.fence("monotonic", None)
1769
+ self.assertIn(
1770
+ "Invalid fence ordering \"monotonic\"!",
1771
+ str(raises.exception))
1772
+ with self.assertRaises(ValueError) as raises:
1773
+ builder.fence(None, "monotonic")
1774
+ self.assertIn(
1775
+ "Invalid fence ordering \"None\"!",
1776
+ str(raises.exception))
1777
+ builder.fence("acquire", None)
1778
+ builder.fence("release", "singlethread")
1779
+ builder.fence("acq_rel", "singlethread")
1780
+ builder.fence("seq_cst")
1781
+ builder.ret_void()
1782
+ self.check_block(block, """\
1783
+ my_block:
1784
+ fence acquire
1785
+ fence syncscope("singlethread") release
1786
+ fence syncscope("singlethread") acq_rel
1787
+ fence seq_cst
1788
+ ret void
1789
+ """)
1790
+
1791
+ def test_comment(self):
1792
+ block = self.block(name='my_block')
1793
+ builder = ir.IRBuilder(block)
1794
+ with self.assertRaises(AssertionError):
1795
+ builder.comment("so\nmany lines")
1796
+ builder.comment("my comment")
1797
+ builder.ret_void()
1798
+ self.check_block(block, """\
1799
+ my_block:
1800
+ ; my comment
1801
+ ret void
1802
+ """)
1803
+
1804
+ def test_bswap(self):
1805
+ block = self.block(name='my_block')
1806
+ builder = ir.IRBuilder(block)
1807
+ a = ir.Constant(int32, 5)
1808
+ c = builder.bswap(a, name='c')
1809
+ builder.ret(c)
1810
+ self.check_block(block, """\
1811
+ my_block:
1812
+ %"c" = call i32 @"llvm.bswap.i32"(i32 5)
1813
+ ret i32 %"c"
1814
+ """)
1815
+
1816
+ def test_ctpop(self):
1817
+ block = self.block(name='my_block')
1818
+ builder = ir.IRBuilder(block)
1819
+ a = ir.Constant(int16, 5)
1820
+ c = builder.ctpop(a, name='c')
1821
+ builder.ret(c)
1822
+ self.check_block(block, """\
1823
+ my_block:
1824
+ %"c" = call i16 @"llvm.ctpop.i16"(i16 5)
1825
+ ret i16 %"c"
1826
+ """)
1827
+
1828
+ def test_ctlz(self):
1829
+ block = self.block(name='my_block')
1830
+ builder = ir.IRBuilder(block)
1831
+ a = ir.Constant(int16, 5)
1832
+ b = ir.Constant(int1, 1)
1833
+ c = builder.ctlz(a, b, name='c')
1834
+ builder.ret(c)
1835
+ self.check_block(block, """\
1836
+ my_block:
1837
+ %"c" = call i16 @"llvm.ctlz.i16"(i16 5, i1 1)
1838
+ ret i16 %"c"
1839
+ """)
1840
+
1841
+ def test_convert_to_fp16_f32(self):
1842
+ block = self.block(name='my_block')
1843
+ builder = ir.IRBuilder(block)
1844
+ a = ir.Constant(flt, 5.0)
1845
+ b = builder.convert_to_fp16(a, name='b')
1846
+ builder.ret(b)
1847
+ self.check_block(block, """\
1848
+ my_block:
1849
+ %"b" = call i16 @"llvm.convert.to.fp16.f32"(float 0x4014000000000000)
1850
+ ret i16 %"b"
1851
+ """) # noqa E501
1852
+
1853
+ def test_convert_to_fp16_f32_wrongtype(self):
1854
+ block = self.block(name='my_block')
1855
+ builder = ir.IRBuilder(block)
1856
+ a = ir.Constant(int16, 5)
1857
+
1858
+ with self.assertRaises(TypeError) as raises:
1859
+ builder.convert_to_fp16(a, name='b')
1860
+ self.assertIn(
1861
+ "expected a float type, got i16",
1862
+ str(raises.exception))
1863
+
1864
+ def test_convert_from_fp16_f32(self):
1865
+ block = self.block(name='my_block')
1866
+ builder = ir.IRBuilder(block)
1867
+ a = ir.Constant(int16, 5)
1868
+ b = builder.convert_from_fp16(a, name='b', to=flt)
1869
+ builder.ret(b)
1870
+ self.check_block(block, """\
1871
+ my_block:
1872
+ %"b" = call float @"llvm.convert.from.fp16.f32"(i16 5)
1873
+ ret float %"b"
1874
+ """)
1875
+
1876
+ def test_convert_from_fp16_f32_notype(self):
1877
+ block = self.block(name='my_block')
1878
+ builder = ir.IRBuilder(block)
1879
+ a = ir.Constant(flt, 5.5)
1880
+
1881
+ with self.assertRaises(TypeError) as raises:
1882
+ builder.convert_from_fp16(a, name='b')
1883
+ self.assertIn(
1884
+ "expected a float return type",
1885
+ str(raises.exception))
1886
+
1887
+ def test_convert_from_fp16_f32_wrongtype(self):
1888
+ block = self.block(name='my_block')
1889
+ builder = ir.IRBuilder(block)
1890
+ a = ir.Constant(flt, 5.5)
1891
+
1892
+ with self.assertRaises(TypeError) as raises:
1893
+ builder.convert_from_fp16(a, name='b', to=flt)
1894
+ self.assertIn(
1895
+ "expected an i16 type, got float",
1896
+ str(raises.exception))
1897
+
1898
+ def test_convert_from_fp16_f32_wrongtype2(self):
1899
+ block = self.block(name='my_block')
1900
+ builder = ir.IRBuilder(block)
1901
+ a = ir.Constant(flt, 5.5)
1902
+
1903
+ with self.assertRaises(TypeError) as raises:
1904
+ builder.convert_from_fp16(a, name='b', to=int16)
1905
+ self.assertIn(
1906
+ "expected a float type, got i16",
1907
+ str(raises.exception))
1908
+
1909
+ def test_cttz(self):
1910
+ block = self.block(name='my_block')
1911
+ builder = ir.IRBuilder(block)
1912
+ a = ir.Constant(int64, 5)
1913
+ b = ir.Constant(int1, 1)
1914
+ c = builder.cttz(a, b, name='c')
1915
+ builder.ret(c)
1916
+ self.check_block(block, """\
1917
+ my_block:
1918
+ %"c" = call i64 @"llvm.cttz.i64"(i64 5, i1 1)
1919
+ ret i64 %"c"
1920
+ """)
1921
+
1922
+ def test_cttz_wrongflag(self):
1923
+ block = self.block(name='my_block')
1924
+ builder = ir.IRBuilder(block)
1925
+ a = ir.Constant(int64, 5)
1926
+ b = ir.Constant(int32, 3)
1927
+
1928
+ with self.assertRaises(TypeError) as raises:
1929
+ builder.cttz(a, b, name='c')
1930
+ self.assertIn(
1931
+ "expected an i1 type, got i32",
1932
+ str(raises.exception))
1933
+
1934
+ def test_cttz_wrongtype(self):
1935
+ block = self.block(name='my_block')
1936
+ builder = ir.IRBuilder(block)
1937
+ a = ir.Constant(flt, 5)
1938
+ b = ir.Constant(int1, 1)
1939
+
1940
+ with self.assertRaises(TypeError) as raises:
1941
+ builder.cttz(a, b, name='c')
1942
+ self.assertIn(
1943
+ "expected an integer type, got float",
1944
+ str(raises.exception))
1945
+
1946
+ def test_fma(self):
1947
+ block = self.block(name='my_block')
1948
+ builder = ir.IRBuilder(block)
1949
+ a = ir.Constant(flt, 5)
1950
+ b = ir.Constant(flt, 1)
1951
+ c = ir.Constant(flt, 2)
1952
+ fma = builder.fma(a, b, c, name='fma')
1953
+ builder.ret(fma)
1954
+ self.check_block(block, """\
1955
+ my_block:
1956
+ %"fma" = call float @"llvm.fma.f32"(float 0x4014000000000000, float 0x3ff0000000000000, float 0x4000000000000000)
1957
+ ret float %"fma"
1958
+ """) # noqa E501
1959
+
1960
+ def test_fma_wrongtype(self):
1961
+ block = self.block(name='my_block')
1962
+ builder = ir.IRBuilder(block)
1963
+ a = ir.Constant(int32, 5)
1964
+ b = ir.Constant(int32, 1)
1965
+ c = ir.Constant(int32, 2)
1966
+
1967
+ with self.assertRaises(TypeError) as raises:
1968
+ builder.fma(a, b, c, name='fma')
1969
+ self.assertIn(
1970
+ "expected an floating point type, got i32",
1971
+ str(raises.exception))
1972
+
1973
+ def test_fma_mixedtypes(self):
1974
+ block = self.block(name='my_block')
1975
+ builder = ir.IRBuilder(block)
1976
+ a = ir.Constant(flt, 5)
1977
+ b = ir.Constant(dbl, 1)
1978
+ c = ir.Constant(flt, 2)
1979
+
1980
+ with self.assertRaises(TypeError) as raises:
1981
+ builder.fma(a, b, c, name='fma')
1982
+ self.assertIn(
1983
+ "expected types to be the same, got float, double, float",
1984
+ str(raises.exception))
1985
+
1986
+ def test_arg_attributes(self):
1987
+ def gen_code(attr_name):
1988
+ fnty = ir.FunctionType(ir.IntType(32), [ir.IntType(32).as_pointer(),
1989
+ ir.IntType(32)])
1990
+ module = ir.Module()
1991
+
1992
+ func = ir.Function(module, fnty, name="sum")
1993
+
1994
+ bb_entry = func.append_basic_block()
1995
+ bb_loop = func.append_basic_block()
1996
+ bb_exit = func.append_basic_block()
1997
+
1998
+ builder = ir.IRBuilder()
1999
+ builder.position_at_end(bb_entry)
2000
+
2001
+ builder.branch(bb_loop)
2002
+ builder.position_at_end(bb_loop)
2003
+
2004
+ index = builder.phi(ir.IntType(32))
2005
+ index.add_incoming(ir.Constant(index.type, 0), bb_entry)
2006
+ accum = builder.phi(ir.IntType(32))
2007
+ accum.add_incoming(ir.Constant(accum.type, 0), bb_entry)
2008
+
2009
+ func.args[0].add_attribute(attr_name)
2010
+ ptr = builder.gep(func.args[0], [index])
2011
+ value = builder.load(ptr)
2012
+
2013
+ added = builder.add(accum, value)
2014
+ accum.add_incoming(added, bb_loop)
2015
+
2016
+ indexp1 = builder.add(index, ir.Constant(index.type, 1))
2017
+ index.add_incoming(indexp1, bb_loop)
2018
+
2019
+ cond = builder.icmp_unsigned('<', indexp1, func.args[1])
2020
+ builder.cbranch(cond, bb_loop, bb_exit)
2021
+
2022
+ builder.position_at_end(bb_exit)
2023
+ builder.ret(added)
2024
+
2025
+ return str(module)
2026
+
2027
+ for attr_name in (
2028
+ 'byref',
2029
+ 'byval',
2030
+ 'elementtype',
2031
+ 'immarg',
2032
+ 'inalloca',
2033
+ 'inreg',
2034
+ 'nest',
2035
+ 'noalias',
2036
+ 'nocapture',
2037
+ 'nofree',
2038
+ 'nonnull',
2039
+ 'noundef',
2040
+ 'preallocated',
2041
+ 'returned',
2042
+ 'signext',
2043
+ 'swiftasync',
2044
+ 'swifterror',
2045
+ 'swiftself',
2046
+ 'zeroext',
2047
+ ):
2048
+ # If this parses, we emitted the right byval attribute format
2049
+ llvm.parse_assembly(gen_code(attr_name))
2050
+ # sret doesn't fit this pattern and is tested in test_call_attributes
2051
+
2052
+
2053
+ class TestBuilderMisc(TestBase):
2054
+ """
2055
+ Test various other features of the IRBuilder class.
2056
+ """
2057
+
2058
+ def test_attributes(self):
2059
+ block = self.block(name='start')
2060
+ builder = ir.IRBuilder(block)
2061
+ self.assertIs(builder.function, block.parent)
2062
+ self.assertIsInstance(builder.function, ir.Function)
2063
+ self.assertIs(builder.module, block.parent.module)
2064
+ self.assertIsInstance(builder.module, ir.Module)
2065
+
2066
+ def test_goto_block(self):
2067
+ block = self.block(name='my_block')
2068
+ builder = ir.IRBuilder(block)
2069
+ a, b = builder.function.args[:2]
2070
+ builder.add(a, b, 'c')
2071
+ bb_new = builder.append_basic_block(name='foo')
2072
+ with builder.goto_block(bb_new):
2073
+ builder.fadd(a, b, 'd')
2074
+ with builder.goto_entry_block():
2075
+ builder.sub(a, b, 'e')
2076
+ builder.fsub(a, b, 'f')
2077
+ builder.branch(bb_new)
2078
+ builder.mul(a, b, 'g')
2079
+ with builder.goto_block(bb_new):
2080
+ builder.fmul(a, b, 'h')
2081
+ self.check_block(block, """\
2082
+ my_block:
2083
+ %"c" = add i32 %".1", %".2"
2084
+ %"e" = sub i32 %".1", %".2"
2085
+ %"g" = mul i32 %".1", %".2"
2086
+ """)
2087
+ self.check_block(bb_new, """\
2088
+ foo:
2089
+ %"d" = fadd i32 %".1", %".2"
2090
+ %"f" = fsub i32 %".1", %".2"
2091
+ %"h" = fmul i32 %".1", %".2"
2092
+ br label %"foo"
2093
+ """)
2094
+
2095
+ def test_if_then(self):
2096
+ block = self.block(name='one')
2097
+ builder = ir.IRBuilder(block)
2098
+ z = ir.Constant(int1, 0)
2099
+ a = builder.add(z, z, 'a')
2100
+ with builder.if_then(a) as bbend:
2101
+ builder.add(z, z, 'b')
2102
+ # Block will be terminated implicitly
2103
+ self.assertIs(builder.block, bbend)
2104
+ c = builder.add(z, z, 'c')
2105
+ with builder.if_then(c):
2106
+ builder.add(z, z, 'd')
2107
+ builder.branch(block)
2108
+ # No implicit termination
2109
+ self.check_func_body(builder.function, """\
2110
+ one:
2111
+ %"a" = add i1 0, 0
2112
+ br i1 %"a", label %"one.if", label %"one.endif"
2113
+ one.if:
2114
+ %"b" = add i1 0, 0
2115
+ br label %"one.endif"
2116
+ one.endif:
2117
+ %"c" = add i1 0, 0
2118
+ br i1 %"c", label %"one.endif.if", label %"one.endif.endif"
2119
+ one.endif.if:
2120
+ %"d" = add i1 0, 0
2121
+ br label %"one"
2122
+ one.endif.endif:
2123
+ """)
2124
+
2125
+ def test_if_then_nested(self):
2126
+ # Implicit termination in a nested if/then
2127
+ block = self.block(name='one')
2128
+ builder = ir.IRBuilder(block)
2129
+ z = ir.Constant(int1, 0)
2130
+ a = builder.add(z, z, 'a')
2131
+ with builder.if_then(a):
2132
+ b = builder.add(z, z, 'b')
2133
+ with builder.if_then(b):
2134
+ builder.add(z, z, 'c')
2135
+ builder.ret_void()
2136
+ self.check_func_body(builder.function, """\
2137
+ one:
2138
+ %"a" = add i1 0, 0
2139
+ br i1 %"a", label %"one.if", label %"one.endif"
2140
+ one.if:
2141
+ %"b" = add i1 0, 0
2142
+ br i1 %"b", label %"one.if.if", label %"one.if.endif"
2143
+ one.endif:
2144
+ ret void
2145
+ one.if.if:
2146
+ %"c" = add i1 0, 0
2147
+ br label %"one.if.endif"
2148
+ one.if.endif:
2149
+ br label %"one.endif"
2150
+ """)
2151
+
2152
+ def test_if_then_long_label(self):
2153
+ full_label = 'Long' * 20
2154
+ block = self.block(name=full_label)
2155
+ builder = ir.IRBuilder(block)
2156
+ z = ir.Constant(int1, 0)
2157
+ a = builder.add(z, z, 'a')
2158
+ with builder.if_then(a):
2159
+ b = builder.add(z, z, 'b')
2160
+ with builder.if_then(b):
2161
+ builder.add(z, z, 'c')
2162
+ builder.ret_void()
2163
+ self.check_func_body(builder.function, """\
2164
+ {full_label}:
2165
+ %"a" = add i1 0, 0
2166
+ br i1 %"a", label %"{label}.if", label %"{label}.endif"
2167
+ {label}.if:
2168
+ %"b" = add i1 0, 0
2169
+ br i1 %"b", label %"{label}.if.if", label %"{label}.if.endif"
2170
+ {label}.endif:
2171
+ ret void
2172
+ {label}.if.if:
2173
+ %"c" = add i1 0, 0
2174
+ br label %"{label}.if.endif"
2175
+ {label}.if.endif:
2176
+ br label %"{label}.endif"
2177
+ """.format(full_label=full_label, label=full_label[:25] + '..'))
2178
+
2179
+ def test_if_then_likely(self):
2180
+ def check(likely):
2181
+ block = self.block(name='one')
2182
+ builder = ir.IRBuilder(block)
2183
+ z = ir.Constant(int1, 0)
2184
+ with builder.if_then(z, likely=likely):
2185
+ pass
2186
+ self.check_block(block, """\
2187
+ one:
2188
+ br i1 0, label %"one.if", label %"one.endif", !prof !0
2189
+ """)
2190
+ return builder
2191
+ builder = check(True)
2192
+ self.check_metadata(builder.module, """\
2193
+ !0 = !{ !"branch_weights", i32 99, i32 1 }
2194
+ """)
2195
+ builder = check(False)
2196
+ self.check_metadata(builder.module, """\
2197
+ !0 = !{ !"branch_weights", i32 1, i32 99 }
2198
+ """)
2199
+
2200
+ def test_if_else(self):
2201
+ block = self.block(name='one')
2202
+ builder = ir.IRBuilder(block)
2203
+ z = ir.Constant(int1, 0)
2204
+ a = builder.add(z, z, 'a')
2205
+ with builder.if_else(a) as (then, otherwise):
2206
+ with then:
2207
+ builder.add(z, z, 'b')
2208
+ with otherwise:
2209
+ builder.add(z, z, 'c')
2210
+ # Each block will be terminated implicitly
2211
+ with builder.if_else(a) as (then, otherwise):
2212
+ with then:
2213
+ builder.branch(block)
2214
+ with otherwise:
2215
+ builder.ret_void()
2216
+ # No implicit termination
2217
+ self.check_func_body(builder.function, """\
2218
+ one:
2219
+ %"a" = add i1 0, 0
2220
+ br i1 %"a", label %"one.if", label %"one.else"
2221
+ one.if:
2222
+ %"b" = add i1 0, 0
2223
+ br label %"one.endif"
2224
+ one.else:
2225
+ %"c" = add i1 0, 0
2226
+ br label %"one.endif"
2227
+ one.endif:
2228
+ br i1 %"a", label %"one.endif.if", label %"one.endif.else"
2229
+ one.endif.if:
2230
+ br label %"one"
2231
+ one.endif.else:
2232
+ ret void
2233
+ one.endif.endif:
2234
+ """)
2235
+
2236
+ def test_if_else_likely(self):
2237
+ def check(likely):
2238
+ block = self.block(name='one')
2239
+ builder = ir.IRBuilder(block)
2240
+ z = ir.Constant(int1, 0)
2241
+ with builder.if_else(z, likely=likely) as (then, otherwise):
2242
+ with then:
2243
+ builder.branch(block)
2244
+ with otherwise:
2245
+ builder.ret_void()
2246
+ self.check_func_body(builder.function, """\
2247
+ one:
2248
+ br i1 0, label %"one.if", label %"one.else", !prof !0
2249
+ one.if:
2250
+ br label %"one"
2251
+ one.else:
2252
+ ret void
2253
+ one.endif:
2254
+ """)
2255
+ return builder
2256
+ builder = check(True)
2257
+ self.check_metadata(builder.module, """\
2258
+ !0 = !{ !"branch_weights", i32 99, i32 1 }
2259
+ """)
2260
+ builder = check(False)
2261
+ self.check_metadata(builder.module, """\
2262
+ !0 = !{ !"branch_weights", i32 1, i32 99 }
2263
+ """)
2264
+
2265
+ def test_positioning(self):
2266
+ """
2267
+ Test IRBuilder.position_{before,after,at_start,at_end}.
2268
+ """
2269
+ func = self.function()
2270
+ builder = ir.IRBuilder()
2271
+ z = ir.Constant(int32, 0)
2272
+ bb_one = func.append_basic_block(name='one')
2273
+ bb_two = func.append_basic_block(name='two')
2274
+ bb_three = func.append_basic_block(name='three')
2275
+ # .at_start(empty block)
2276
+ builder.position_at_start(bb_one)
2277
+ builder.add(z, z, 'a')
2278
+ # .at_end(empty block)
2279
+ builder.position_at_end(bb_two)
2280
+ builder.add(z, z, 'm')
2281
+ builder.add(z, z, 'n')
2282
+ # .at_start(block)
2283
+ builder.position_at_start(bb_two)
2284
+ o = builder.add(z, z, 'o')
2285
+ builder.add(z, z, 'p')
2286
+ # .at_end(block)
2287
+ builder.position_at_end(bb_one)
2288
+ b = builder.add(z, z, 'b')
2289
+ # .after(instr)
2290
+ builder.position_after(o)
2291
+ builder.add(z, z, 'q')
2292
+ # .before(instr)
2293
+ builder.position_before(b)
2294
+ builder.add(z, z, 'c')
2295
+ self.check_block(bb_one, """\
2296
+ one:
2297
+ %"a" = add i32 0, 0
2298
+ %"c" = add i32 0, 0
2299
+ %"b" = add i32 0, 0
2300
+ """)
2301
+ self.check_block(bb_two, """\
2302
+ two:
2303
+ %"o" = add i32 0, 0
2304
+ %"q" = add i32 0, 0
2305
+ %"p" = add i32 0, 0
2306
+ %"m" = add i32 0, 0
2307
+ %"n" = add i32 0, 0
2308
+ """)
2309
+ self.check_block(bb_three, """\
2310
+ three:
2311
+ """)
2312
+
2313
+ def test_instruction_removal(self):
2314
+ func = self.function()
2315
+ builder = ir.IRBuilder()
2316
+ blk = func.append_basic_block(name='entry')
2317
+ builder.position_at_end(blk)
2318
+ k = ir.Constant(int32, 1234)
2319
+ a = builder.add(k, k, 'a')
2320
+ retvoid = builder.ret_void()
2321
+ self.assertTrue(blk.is_terminated)
2322
+ builder.remove(retvoid)
2323
+ self.assertFalse(blk.is_terminated)
2324
+ b = builder.mul(a, a, 'b')
2325
+ c = builder.add(b, b, 'c')
2326
+ builder.remove(c)
2327
+ builder.ret_void()
2328
+ self.assertTrue(blk.is_terminated)
2329
+ self.check_block(blk, """\
2330
+ entry:
2331
+ %"a" = add i32 1234, 1234
2332
+ %"b" = mul i32 %"a", %"a"
2333
+ ret void
2334
+ """)
2335
+
2336
+ def test_metadata(self):
2337
+ block = self.block(name='my_block')
2338
+ builder = ir.IRBuilder(block)
2339
+ builder.debug_metadata = builder.module.add_metadata([])
2340
+ builder.alloca(ir.PointerType(int32), name='c')
2341
+ # FIXME: Remove `else' once TP are no longer supported.
2342
+ if opaque_pointers_enabled:
2343
+ self.check_block(block, """\
2344
+ my_block:
2345
+ %"c" = alloca ptr, !dbg !0
2346
+ """)
2347
+ else:
2348
+ self.check_block(block, """\
2349
+ my_block:
2350
+ %"c" = alloca i32*, !dbg !0
2351
+ """)
2352
+
2353
+
2354
+ class TestTypes(TestBase):
2355
+
2356
+ def has_logical_equality(self, ty):
2357
+ while isinstance(ty, ir.PointerType):
2358
+ ty = ty.pointee
2359
+ return not isinstance(ty, ir.LabelType)
2360
+
2361
+ def assorted_types(self):
2362
+ """
2363
+ A bunch of mutually unequal types
2364
+ """
2365
+ # Avoid polluting the namespace
2366
+ context = ir.Context()
2367
+ types = [
2368
+ ir.LabelType(), ir.VoidType(),
2369
+ ir.FunctionType(int1, (int8, int8)), ir.FunctionType(int1, (int8,)),
2370
+ ir.FunctionType(int1, (int8,), var_arg=True),
2371
+ ir.FunctionType(int8, (int8,)),
2372
+ int1, int8, int32, flt, dbl,
2373
+ ir.ArrayType(flt, 5), ir.ArrayType(dbl, 5), ir.ArrayType(dbl, 4),
2374
+ ir.LiteralStructType((int1, int8)), ir.LiteralStructType((int8,
2375
+ int1)),
2376
+ context.get_identified_type("MyType1"),
2377
+ context.get_identified_type("MyType2"),
2378
+ ]
2379
+ types += [ir.PointerType(tp) for tp in types
2380
+ if not isinstance(tp, (ir.VoidType, ir.LabelType))]
2381
+
2382
+ return types
2383
+
2384
+ def test_pickling(self):
2385
+ types = self.assorted_types()
2386
+ for ty in types:
2387
+ newty = self.assert_pickle_correctly(ty)
2388
+ if self.has_logical_equality(ty):
2389
+ self.assertEqual(newty, ty)
2390
+
2391
+ def test_comparisons(self):
2392
+ types = self.assorted_types()
2393
+ for a, b in itertools.product(types, types):
2394
+ if a is not b:
2395
+ self.assertFalse(a == b, (a, b))
2396
+ self.assertTrue(a != b, (a, b))
2397
+ # We assume copy.copy() works fine here...
2398
+ for tp in types:
2399
+ other = copy.copy(tp)
2400
+ if self.has_logical_equality(tp):
2401
+ self.assertTrue(tp == other, (tp, other))
2402
+ self.assertFalse(tp != other, (tp, other))
2403
+ else:
2404
+ self.assertFalse(tp == other, (tp, other))
2405
+ self.assertTrue(tp != other, (tp, other))
2406
+
2407
+ def test_str(self):
2408
+ """
2409
+ Test the string representation of types.
2410
+ """
2411
+ self.assertEqual(str(int1), 'i1')
2412
+ self.assertEqual(str(ir.IntType(29)), 'i29')
2413
+ self.assertEqual(str(flt), 'float')
2414
+ self.assertEqual(str(dbl), 'double')
2415
+ self.assertEqual(str(ir.VoidType()), 'void')
2416
+ self.assertEqual(str(ir.FunctionType(int1, ())), 'i1 ()')
2417
+ self.assertEqual(str(ir.FunctionType(int1, (flt,))), 'i1 (float)')
2418
+ self.assertEqual(str(ir.FunctionType(int1, (flt, dbl))),
2419
+ 'i1 (float, double)')
2420
+ self.assertEqual(str(ir.FunctionType(int1, (), var_arg=True)),
2421
+ 'i1 (...)')
2422
+ self.assertEqual(str(ir.FunctionType(int1, (flt,), var_arg=True)),
2423
+ 'i1 (float, ...)')
2424
+ self.assertEqual(str(ir.FunctionType(int1, (flt, dbl), var_arg=True)),
2425
+ 'i1 (float, double, ...)')
2426
+ # FIXME: Remove `else' once TP are no longer supported.
2427
+ if opaque_pointers_enabled:
2428
+ self.assertEqual(str(ir.PointerType(int32)), 'ptr')
2429
+ self.assertEqual(str(ir.PointerType(ir.PointerType(int32))), 'ptr')
2430
+ else:
2431
+ self.assertEqual(str(ir.PointerType(int32)), 'i32*')
2432
+ self.assertEqual(str(ir.PointerType(ir.PointerType(int32))),
2433
+ 'i32**')
2434
+ self.assertEqual(str(ir.ArrayType(int1, 5)), '[5 x i1]')
2435
+ # FIXME: Remove `else' once TP are no longer supported.
2436
+ if opaque_pointers_enabled:
2437
+ self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)),
2438
+ '[5 x ptr]')
2439
+ self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))), 'ptr')
2440
+ else:
2441
+ self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)),
2442
+ '[5 x i1*]')
2443
+ self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))),
2444
+ '[5 x i1]*')
2445
+ self.assertEqual(str(ir.LiteralStructType((int1,))), '{i1}')
2446
+ self.assertEqual(str(ir.LiteralStructType((int1, flt))), '{i1, float}')
2447
+ # FIXME: Remove `else' once TP are no longer supported.
2448
+ if opaque_pointers_enabled:
2449
+ self.assertEqual(str(ir.LiteralStructType((
2450
+ ir.PointerType(int1), ir.LiteralStructType((int32, int8))))),
2451
+ '{ptr, {i32, i8}}')
2452
+ else:
2453
+ self.assertEqual(str(ir.LiteralStructType((
2454
+ ir.PointerType(int1), ir.LiteralStructType((int32, int8))))),
2455
+ '{i1*, {i32, i8}}')
2456
+ self.assertEqual(str(ir.LiteralStructType((int1,), packed=True)),
2457
+ '<{i1}>')
2458
+ self.assertEqual(str(ir.LiteralStructType((int1, flt), packed=True)),
2459
+ '<{i1, float}>')
2460
+
2461
+ # Avoid polluting the namespace
2462
+ context = ir.Context()
2463
+ mytype = context.get_identified_type("MyType")
2464
+ self.assertEqual(str(mytype), "%\"MyType\"")
2465
+ mytype1 = context.get_identified_type("MyType\\")
2466
+ self.assertEqual(str(mytype1), "%\"MyType\\5c\"")
2467
+ mytype2 = context.get_identified_type("MyType\"")
2468
+ self.assertEqual(str(mytype2), "%\"MyType\\22\"")
2469
+
2470
+ def test_hash(self):
2471
+ for typ in filter(self.has_logical_equality, self.assorted_types()):
2472
+ self.assertEqual(hash(typ), hash(copy.copy(typ)))
2473
+
2474
+ def test_gep(self):
2475
+ def check_constant(tp, i, expected):
2476
+ actual = tp.gep(ir.Constant(int32, i))
2477
+ self.assertEqual(actual, expected)
2478
+
2479
+ def check_index_type(tp):
2480
+ index = ir.Constant(dbl, 1.0)
2481
+ with self.assertRaises(TypeError):
2482
+ tp.gep(index)
2483
+
2484
+ tp = ir.PointerType(dbl)
2485
+ for i in range(5):
2486
+ check_constant(tp, i, dbl)
2487
+ check_index_type(tp)
2488
+
2489
+ tp = ir.ArrayType(int1, 3)
2490
+ for i in range(3):
2491
+ check_constant(tp, i, int1)
2492
+ check_index_type(tp)
2493
+
2494
+ tp = ir.LiteralStructType((dbl, ir.LiteralStructType((int1, int8))))
2495
+ check_constant(tp, 0, dbl)
2496
+ check_constant(tp, 1, ir.LiteralStructType((int1, int8)))
2497
+ with self.assertRaises(IndexError):
2498
+ tp.gep(ir.Constant(int32, 2))
2499
+ check_index_type(tp)
2500
+
2501
+ context = ir.Context()
2502
+ tp = ir.IdentifiedStructType(context, "MyType")
2503
+ tp.set_body(dbl, ir.LiteralStructType((int1, int8)))
2504
+ check_constant(tp, 0, dbl)
2505
+ check_constant(tp, 1, ir.LiteralStructType((int1, int8)))
2506
+ with self.assertRaises(IndexError):
2507
+ tp.gep(ir.Constant(int32, 2))
2508
+ check_index_type(tp)
2509
+
2510
+ def test_abi_size(self):
2511
+ td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")
2512
+
2513
+ def check(tp, expected):
2514
+ self.assertEqual(tp.get_abi_size(td), expected)
2515
+ check(int8, 1)
2516
+ check(int32, 4)
2517
+ check(int64, 8)
2518
+ check(ir.ArrayType(int8, 5), 5)
2519
+ check(ir.ArrayType(int32, 5), 20)
2520
+ check(ir.LiteralStructType((dbl, flt, flt)), 16)
2521
+
2522
+ def test_abi_alignment(self):
2523
+ td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")
2524
+
2525
+ def check(tp, expected):
2526
+ self.assertIn(tp.get_abi_alignment(td), expected)
2527
+ check(int8, (1, 2, 4))
2528
+ check(int32, (4,))
2529
+ check(int64, (8,))
2530
+ check(ir.ArrayType(int8, 5), (1, 2, 4))
2531
+ check(ir.ArrayType(int32, 5), (4,))
2532
+ check(ir.LiteralStructType((dbl, flt, flt)), (8,))
2533
+
2534
+ def test_identified_struct(self):
2535
+ context = ir.Context()
2536
+ mytype = context.get_identified_type("MyType")
2537
+ module = ir.Module(context=context)
2538
+ self.assertTrue(mytype.is_opaque)
2539
+ self.assert_valid_ir(module)
2540
+ oldstr = str(module)
2541
+ mytype.set_body(ir.IntType(32), ir.IntType(64), ir.FloatType())
2542
+ self.assertFalse(mytype.is_opaque)
2543
+ self.assert_valid_ir(module)
2544
+ self.assertNotEqual(oldstr, str(module))
2545
+
2546
+ def test_identified_struct_packed(self):
2547
+ td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")
2548
+ context = ir.Context()
2549
+ mytype = context.get_identified_type("MyType", True)
2550
+ module = ir.Module(context=context)
2551
+ self.assertTrue(mytype.is_opaque)
2552
+ self.assert_valid_ir(module)
2553
+ oldstr = str(module)
2554
+ mytype.set_body(ir.IntType(16), ir.IntType(64), ir.FloatType())
2555
+ self.assertEqual(mytype.get_element_offset(td, 1, context), 2)
2556
+ self.assertFalse(mytype.is_opaque)
2557
+ self.assert_valid_ir(module)
2558
+ self.assertNotEqual(oldstr, str(module))
2559
+
2560
+ def test_target_data_non_default_context(self):
2561
+ context = ir.Context()
2562
+ mytype = context.get_identified_type("MyType")
2563
+ mytype.elements = [ir.IntType(32)]
2564
+ td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")
2565
+ self.assertEqual(mytype.get_abi_size(td, context=context), 4)
2566
+
2567
+ def test_vector(self):
2568
+ vecty = ir.VectorType(ir.IntType(32), 8)
2569
+ self.assertEqual(str(vecty), "<8 x i32>")
2570
+
2571
+
2572
+ def c32(i):
2573
+ return ir.Constant(int32, i)
2574
+
2575
+
2576
+ class TestConstant(TestBase):
2577
+
2578
+ def test_integers(self):
2579
+ c = ir.Constant(int32, 42)
2580
+ self.assertEqual(str(c), 'i32 42')
2581
+ c = ir.Constant(int1, 1)
2582
+ self.assertEqual(str(c), 'i1 1')
2583
+ c = ir.Constant(int1, 0)
2584
+ self.assertEqual(str(c), 'i1 0')
2585
+ c = ir.Constant(int1, True)
2586
+ self.assertEqual(str(c), 'i1 true')
2587
+ c = ir.Constant(int1, False)
2588
+ self.assertEqual(str(c), 'i1 false')
2589
+ c = ir.Constant(int1, ir.Undefined)
2590
+ self.assertEqual(str(c), 'i1 undef')
2591
+ c = ir.Constant(int1, None)
2592
+ self.assertEqual(str(c), 'i1 0')
2593
+
2594
+ def test_reals(self):
2595
+ # XXX Test NaNs and infs
2596
+ c = ir.Constant(flt, 1.5)
2597
+ self.assertEqual(str(c), 'float 0x3ff8000000000000')
2598
+ c = ir.Constant(flt, -1.5)
2599
+ self.assertEqual(str(c), 'float 0xbff8000000000000')
2600
+ c = ir.Constant(dbl, 1.5)
2601
+ self.assertEqual(str(c), 'double 0x3ff8000000000000')
2602
+ c = ir.Constant(dbl, -1.5)
2603
+ self.assertEqual(str(c), 'double 0xbff8000000000000')
2604
+ c = ir.Constant(dbl, ir.Undefined)
2605
+ self.assertEqual(str(c), 'double undef')
2606
+ c = ir.Constant(dbl, None)
2607
+ self.assertEqual(str(c), 'double 0.0')
2608
+
2609
+ def test_arrays(self):
2610
+ c = ir.Constant(ir.ArrayType(int32, 3), (c32(5), c32(6), c32(4)))
2611
+ self.assertEqual(str(c), '[3 x i32] [i32 5, i32 6, i32 4]')
2612
+ c = ir.Constant(ir.ArrayType(int32, 2), (c32(5), c32(ir.Undefined)))
2613
+ self.assertEqual(str(c), '[2 x i32] [i32 5, i32 undef]')
2614
+
2615
+ c = ir.Constant.literal_array((c32(5), c32(6), c32(ir.Undefined)))
2616
+ self.assertEqual(str(c), '[3 x i32] [i32 5, i32 6, i32 undef]')
2617
+ with self.assertRaises(TypeError) as raises:
2618
+ ir.Constant.literal_array((c32(5), ir.Constant(flt, 1.5)))
2619
+ self.assertEqual(str(raises.exception),
2620
+ "all elements must have the same type")
2621
+
2622
+ c = ir.Constant(ir.ArrayType(int32, 2), ir.Undefined)
2623
+ self.assertEqual(str(c), '[2 x i32] undef')
2624
+ c = ir.Constant(ir.ArrayType(int32, 2), None)
2625
+ self.assertEqual(str(c), '[2 x i32] zeroinitializer')
2626
+ # Raw array syntax
2627
+ c = ir.Constant(ir.ArrayType(int8, 11), bytearray(b"foobar_123\x80"))
2628
+ self.assertEqual(str(c), r'[11 x i8] c"foobar_123\80"')
2629
+ c = ir.Constant(ir.ArrayType(int8, 4), bytearray(b"\x00\x01\x04\xff"))
2630
+ self.assertEqual(str(c), r'[4 x i8] c"\00\01\04\ff"')
2631
+ # Recursive instantiation of inner constants
2632
+ c = ir.Constant(ir.ArrayType(int32, 3), (5, ir.Undefined, 6))
2633
+ self.assertEqual(str(c), '[3 x i32] [i32 5, i32 undef, i32 6]')
2634
+ # Invalid number of args
2635
+ with self.assertRaises(ValueError):
2636
+ ir.Constant(ir.ArrayType(int32, 3), (5, 6))
2637
+
2638
+ def test_vector(self):
2639
+ vecty = ir.VectorType(ir.IntType(32), 8)
2640
+ vals = [1, 2, 4, 3, 8, 6, 9, 7]
2641
+ vec = ir.Constant(vecty, vals)
2642
+ vec_repr = "<8 x i32> <{}>".format(
2643
+ ', '.join(map('i32 {}'.format, vals)))
2644
+ self.assertEqual(str(vec), vec_repr)
2645
+
2646
+ def test_non_nullable_int(self):
2647
+ constant = ir.Constant(ir.IntType(32), None).constant
2648
+ self.assertEqual(constant, 0)
2649
+
2650
+ def test_structs(self):
2651
+ st1 = ir.LiteralStructType((flt, int1))
2652
+ st2 = ir.LiteralStructType((int32, st1))
2653
+ c = ir.Constant(st1, (ir.Constant(ir.FloatType(), 1.5),
2654
+ ir.Constant(int1, True)))
2655
+ self.assertEqual(str(c),
2656
+ '{float, i1} {float 0x3ff8000000000000, i1 true}')
2657
+ c = ir.Constant.literal_struct((ir.Constant(ir.FloatType(), 1.5),
2658
+ ir.Constant(int1, True)))
2659
+ self.assertEqual(c.type, st1)
2660
+ self.assertEqual(str(c),
2661
+ '{float, i1} {float 0x3ff8000000000000, i1 true}')
2662
+ c = ir.Constant.literal_struct((ir.Constant(ir.FloatType(), 1.5),
2663
+ ir.Constant(int1, ir.Undefined)))
2664
+ self.assertEqual(c.type, st1)
2665
+ self.assertEqual(str(c),
2666
+ '{float, i1} {float 0x3ff8000000000000, i1 undef}')
2667
+ c = ir.Constant(st1, ir.Undefined)
2668
+ self.assertEqual(str(c), '{float, i1} undef')
2669
+ c = ir.Constant(st1, None)
2670
+ self.assertEqual(str(c), '{float, i1} zeroinitializer')
2671
+ # Recursive instantiation of inner constants
2672
+ c1 = ir.Constant(st1, (1.5, True))
2673
+ self.assertEqual(str(c1),
2674
+ '{float, i1} {float 0x3ff8000000000000, i1 true}')
2675
+ c2 = ir.Constant(st2, (42, c1))
2676
+ self.assertEqual(str(c2), ('{i32, {float, i1}} {i32 42, {float, i1} '
2677
+ '{float 0x3ff8000000000000, i1 true}}'))
2678
+ c3 = ir.Constant(st2, (42, (1.5, True)))
2679
+ self.assertEqual(str(c3), str(c2))
2680
+ # Invalid number of args
2681
+ with self.assertRaises(ValueError):
2682
+ ir.Constant(st2, (4, 5, 6))
2683
+
2684
+ def test_undefined_literal_struct_pickling(self):
2685
+ i8 = ir.IntType(8)
2686
+ st = ir.Constant(ir.LiteralStructType([i8, i8]), ir.Undefined)
2687
+ self.assert_pickle_correctly(st)
2688
+
2689
+ def test_type_instantiaton(self):
2690
+ """
2691
+ Instantiating a type should create a constant.
2692
+ """
2693
+ c = int8(42)
2694
+ self.assertIsInstance(c, ir.Constant)
2695
+ self.assertEqual(str(c), 'i8 42')
2696
+ c = int1(True)
2697
+ self.assertIsInstance(c, ir.Constant)
2698
+ self.assertEqual(str(c), 'i1 true')
2699
+ # Arrays
2700
+ at = ir.ArrayType(int32, 3)
2701
+ c = at([c32(4), c32(5), c32(6)])
2702
+ self.assertEqual(str(c), '[3 x i32] [i32 4, i32 5, i32 6]')
2703
+ c = at([4, 5, 6])
2704
+ self.assertEqual(str(c), '[3 x i32] [i32 4, i32 5, i32 6]')
2705
+ c = at(None)
2706
+ self.assertEqual(str(c), '[3 x i32] zeroinitializer')
2707
+ with self.assertRaises(ValueError):
2708
+ at([4, 5, 6, 7])
2709
+ # Structs
2710
+ st1 = ir.LiteralStructType((flt, int1))
2711
+ st2 = ir.LiteralStructType((int32, st1))
2712
+ c = st1((1.5, True))
2713
+ self.assertEqual(str(c), ('{float, i1} {float 0x3ff8000000000000, i1 '
2714
+ 'true}'))
2715
+ c = st2((42, (1.5, True)))
2716
+ self.assertEqual(str(c), ('{i32, {float, i1}} {i32 42, {float, i1} '
2717
+ '{float 0x3ff8000000000000, i1 true}}'))
2718
+
2719
+ def test_repr(self):
2720
+ """
2721
+ Constants should have a useful repr().
2722
+ """
2723
+ c = int32(42)
2724
+ self.assertEqual(repr(c), "<ir.Constant type='i32' value=42>")
2725
+
2726
+ def test_encoding_problem(self):
2727
+ c = ir.Constant(ir.ArrayType(ir.IntType(8), 256),
2728
+ bytearray(range(256)))
2729
+ m = self.module()
2730
+ gv = ir.GlobalVariable(m, c.type, "myconstant")
2731
+ gv.global_constant = True
2732
+ gv.initializer = c
2733
+ # With utf-8, the following will cause:
2734
+ # UnicodeDecodeError: 'utf-8' codec can't decode byte 0xe0 in position
2735
+ # 136: invalid continuation byte
2736
+ parsed = llvm.parse_assembly(str(m))
2737
+ # Make sure the encoding does not modify the IR
2738
+ reparsed = llvm.parse_assembly(str(parsed))
2739
+ self.assertEqual(str(parsed), str(reparsed))
2740
+
2741
+ def test_gep(self):
2742
+ m = self.module()
2743
+ tp = ir.LiteralStructType((flt, int1))
2744
+ gv = ir.GlobalVariable(m, tp, "myconstant")
2745
+ c = gv.gep([ir.Constant(int32, x) for x in (0, 1)])
2746
+ # FIXME: Remove `else' once TP are no longer supported.
2747
+ if opaque_pointers_enabled:
2748
+ self.assertEqual(str(c),
2749
+ 'getelementptr ({float, i1}, ptr @"myconstant", i32 0, i32 1)') # noqa E501
2750
+ else:
2751
+ self.assertEqual(str(c),
2752
+ 'getelementptr ({float, i1}, {float, i1}* @"myconstant", i32 0, i32 1)') # noqa E501
2753
+ self.assertEqual(c.type, ir.PointerType(int1))
2754
+
2755
+ const = ir.Constant(tp, None)
2756
+ with self.assertRaises(TypeError):
2757
+ const.gep([ir.Constant(int32, 0)])
2758
+
2759
+ const_ptr = ir.Constant(tp.as_pointer(), None)
2760
+ c2 = const_ptr.gep([ir.Constant(int32, 0)])
2761
+ # FIXME: Remove `else' once TP are no longer supported.
2762
+ if opaque_pointers_enabled:
2763
+ self.assertEqual(str(c2),
2764
+ 'getelementptr ({float, i1}, ptr null, i32 0)') # noqa E501
2765
+ else:
2766
+ self.assertEqual(str(c2),
2767
+ 'getelementptr ({float, i1}, {float, i1}* null, i32 0)') # noqa E501
2768
+ self.assertEqual(c.type, ir.PointerType(int1))
2769
+
2770
+ def test_gep_addrspace_globalvar(self):
2771
+ m = self.module()
2772
+ tp = ir.LiteralStructType((flt, int1))
2773
+ addrspace = 4
2774
+
2775
+ gv = ir.GlobalVariable(m, tp, "myconstant", addrspace=addrspace)
2776
+ self.assertEqual(gv.addrspace, addrspace)
2777
+ c = gv.gep([ir.Constant(int32, x) for x in (0, 1)])
2778
+ self.assertEqual(c.type.addrspace, addrspace)
2779
+ # FIXME: Remove `else' once TP are no longer supported.
2780
+ if opaque_pointers_enabled:
2781
+ self.assertEqual(str(c),
2782
+ ('getelementptr ({float, i1}, ptr '
2783
+ 'addrspace(4) @"myconstant", i32 0, i32 1)'))
2784
+ else:
2785
+ self.assertEqual(str(c),
2786
+ ('getelementptr ({float, i1}, {float, i1} '
2787
+ 'addrspace(4)* @"myconstant", i32 0, i32 1)'))
2788
+ self.assertEqual(c.type, ir.PointerType(int1, addrspace=addrspace))
2789
+
2790
+ def test_trunc(self):
2791
+ c = ir.Constant(int64, 1).trunc(int32)
2792
+ self.assertEqual(str(c), 'trunc (i64 1 to i32)')
2793
+
2794
+ def test_zext(self):
2795
+ c = ir.Constant(int32, 1).zext(int64)
2796
+ self.assertEqual(str(c), 'zext (i32 1 to i64)')
2797
+
2798
+ def test_sext(self):
2799
+ c = ir.Constant(int32, -1).sext(int64)
2800
+ self.assertEqual(str(c), 'sext (i32 -1 to i64)')
2801
+
2802
+ def test_fptrunc(self):
2803
+ c = ir.Constant(flt, 1).fptrunc(hlf)
2804
+ self.assertEqual(str(c), 'fptrunc (float 0x3ff0000000000000 to half)')
2805
+
2806
+ def test_fpext(self):
2807
+ c = ir.Constant(flt, 1).fpext(dbl)
2808
+ self.assertEqual(str(c), 'fpext (float 0x3ff0000000000000 to double)')
2809
+
2810
+ def test_bitcast(self):
2811
+ m = self.module()
2812
+ gv = ir.GlobalVariable(m, int32, "myconstant")
2813
+ c = gv.bitcast(int64.as_pointer())
2814
+ # FIXME: Remove `else' once TP are no longer supported.
2815
+ if opaque_pointers_enabled:
2816
+ self.assertEqual(str(c), 'bitcast (ptr @"myconstant" to ptr)')
2817
+ else:
2818
+ self.assertEqual(str(c), 'bitcast (i32* @"myconstant" to i64*)')
2819
+
2820
+ def test_fptoui(self):
2821
+ c = ir.Constant(flt, 1).fptoui(int32)
2822
+ self.assertEqual(str(c), 'fptoui (float 0x3ff0000000000000 to i32)')
2823
+
2824
+ def test_uitofp(self):
2825
+ c = ir.Constant(int32, 1).uitofp(flt)
2826
+ self.assertEqual(str(c), 'uitofp (i32 1 to float)')
2827
+
2828
+ def test_fptosi(self):
2829
+ c = ir.Constant(flt, 1).fptosi(int32)
2830
+ self.assertEqual(str(c), 'fptosi (float 0x3ff0000000000000 to i32)')
2831
+
2832
+ def test_sitofp(self):
2833
+ c = ir.Constant(int32, 1).sitofp(flt)
2834
+ self.assertEqual(str(c), 'sitofp (i32 1 to float)')
2835
+
2836
+ def test_ptrtoint_1(self):
2837
+ ptr = ir.Constant(int64.as_pointer(), None)
2838
+ one = ir.Constant(int32, 1)
2839
+ c = ptr.ptrtoint(int32)
2840
+
2841
+ self.assertRaises(TypeError, one.ptrtoint, int64)
2842
+ self.assertRaises(TypeError, ptr.ptrtoint, flt)
2843
+ # FIXME: Remove `else' once TP are no longer supported.
2844
+ if opaque_pointers_enabled:
2845
+ self.assertEqual(str(c), 'ptrtoint (ptr null to i32)')
2846
+ else:
2847
+ self.assertEqual(str(c), 'ptrtoint (i64* null to i32)')
2848
+
2849
+ def test_ptrtoint_2(self):
2850
+ m = self.module()
2851
+ gv = ir.GlobalVariable(m, int32, "myconstant")
2852
+ c = gv.ptrtoint(int64)
2853
+ # FIXME: Remove `else' once TP are no longer supported.
2854
+ if opaque_pointers_enabled:
2855
+ self.assertEqual(str(c), 'ptrtoint (ptr @"myconstant" to i64)')
2856
+
2857
+ self.assertRaisesRegex(
2858
+ TypeError,
2859
+ r"can only ptrtoint\(\) to integer type, not 'ptr'",
2860
+ gv.ptrtoint,
2861
+ int64.as_pointer())
2862
+ else:
2863
+ self.assertEqual(str(c), 'ptrtoint (i32* @"myconstant" to i64)')
2864
+
2865
+ self.assertRaisesRegex(
2866
+ TypeError,
2867
+ r"can only ptrtoint\(\) to integer type, not 'i64\*'",
2868
+ gv.ptrtoint,
2869
+ int64.as_pointer())
2870
+
2871
+ c2 = ir.Constant(int32, 0)
2872
+ self.assertRaisesRegex(
2873
+ TypeError,
2874
+ r"can only call ptrtoint\(\) on pointer type, not 'i32'",
2875
+ c2.ptrtoint,
2876
+ int64)
2877
+
2878
+ def test_inttoptr(self):
2879
+ one = ir.Constant(int32, 1)
2880
+ pi = ir.Constant(flt, 3.14)
2881
+ c = one.inttoptr(int64.as_pointer())
2882
+
2883
+ self.assertRaises(TypeError, one.inttoptr, int64)
2884
+ self.assertRaises(TypeError, pi.inttoptr, int64.as_pointer())
2885
+ # FIXME: Remove `else' once TP are no longer supported.
2886
+ if opaque_pointers_enabled:
2887
+ self.assertEqual(str(c), 'inttoptr (i32 1 to ptr)')
2888
+ else:
2889
+ self.assertEqual(str(c), 'inttoptr (i32 1 to i64*)')
2890
+
2891
+ def test_neg(self):
2892
+ one = ir.Constant(int32, 1)
2893
+ self.assertEqual(str(one.neg()), 'sub (i32 0, i32 1)')
2894
+
2895
+ def test_not(self):
2896
+ one = ir.Constant(int32, 1)
2897
+ self.assertEqual(str(one.not_()), 'xor (i32 1, i32 -1)')
2898
+
2899
+ def test_fneg(self):
2900
+ one = ir.Constant(flt, 1)
2901
+ self.assertEqual(str(one.fneg()), 'fneg (float 0x3ff0000000000000)')
2902
+
2903
+ def test_int_binops(self):
2904
+ one = ir.Constant(int32, 1)
2905
+ two = ir.Constant(int32, 2)
2906
+
2907
+ oracle = {one.shl: 'shl', one.lshr: 'lshr', one.ashr: 'ashr',
2908
+ one.add: 'add', one.sub: 'sub', one.mul: 'mul',
2909
+ one.udiv: 'udiv', one.sdiv: 'sdiv', one.urem: 'urem',
2910
+ one.srem: 'srem', one.or_: 'or', one.and_: 'and',
2911
+ one.xor: 'xor'}
2912
+ for fn, irop in oracle.items():
2913
+ self.assertEqual(str(fn(two)), irop + ' (i32 1, i32 2)')
2914
+
2915
+ # unsigned integer compare
2916
+ oracle = {'==': 'eq', '!=': 'ne', '>':
2917
+ 'ugt', '>=': 'uge', '<': 'ult', '<=': 'ule'}
2918
+ for cop, cond in oracle.items():
2919
+ actual = str(one.icmp_unsigned(cop, two))
2920
+ expected = 'icmp ' + cond + ' (i32 1, i32 2)'
2921
+ self.assertEqual(actual, expected)
2922
+
2923
+ # signed integer compare
2924
+ oracle = {'==': 'eq', '!=': 'ne',
2925
+ '>': 'sgt', '>=': 'sge', '<': 'slt', '<=': 'sle'}
2926
+ for cop, cond in oracle.items():
2927
+ actual = str(one.icmp_signed(cop, two))
2928
+ expected = 'icmp ' + cond + ' (i32 1, i32 2)'
2929
+ self.assertEqual(actual, expected)
2930
+
2931
+ def test_flt_binops(self):
2932
+ one = ir.Constant(flt, 1)
2933
+ two = ir.Constant(flt, 2)
2934
+
2935
+ oracle = {one.fadd: 'fadd', one.fsub: 'fsub', one.fmul: 'fmul',
2936
+ one.fdiv: 'fdiv', one.frem: 'frem'}
2937
+ for fn, irop in oracle.items():
2938
+ actual = str(fn(two))
2939
+ expected = irop + (' (float 0x3ff0000000000000,'
2940
+ ' float 0x4000000000000000)')
2941
+ self.assertEqual(actual, expected)
2942
+
2943
+ # ordered float compare
2944
+ oracle = {'==': 'oeq', '!=': 'one', '>': 'ogt', '>=': 'oge',
2945
+ '<': 'olt', '<=': 'ole'}
2946
+ for cop, cond in oracle.items():
2947
+ actual = str(one.fcmp_ordered(cop, two))
2948
+ expected = 'fcmp ' + cond + (' (float 0x3ff0000000000000,'
2949
+ ' float 0x4000000000000000)')
2950
+ self.assertEqual(actual, expected)
2951
+
2952
+ # unordered float compare
2953
+ oracle = {'==': 'ueq', '!=': 'une', '>': 'ugt', '>=': 'uge',
2954
+ '<': 'ult', '<=': 'ule'}
2955
+ for cop, cond in oracle.items():
2956
+ actual = str(one.fcmp_unordered(cop, two))
2957
+ expected = 'fcmp ' + cond + (' (float 0x3ff0000000000000,'
2958
+ ' float 0x4000000000000000)')
2959
+ self.assertEqual(actual, expected)
2960
+
2961
+
2962
+ class TestTransforms(TestBase):
2963
+ def test_call_transform(self):
2964
+ mod = ir.Module()
2965
+ foo = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "foo")
2966
+ bar = ir.Function(mod, ir.FunctionType(ir.VoidType(), ()), "bar")
2967
+ builder = ir.IRBuilder()
2968
+ builder.position_at_end(foo.append_basic_block())
2969
+ call = builder.call(foo, ())
2970
+ self.assertEqual(call.callee, foo)
2971
+ modified = ir.replace_all_calls(mod, foo, bar)
2972
+ self.assertIn(call, modified)
2973
+ self.assertNotEqual(call.callee, foo)
2974
+ self.assertEqual(call.callee, bar)
2975
+
2976
+
2977
+ class TestSingleton(TestBase):
2978
+ def test_undefined(self):
2979
+ self.assertIs(ir.Undefined, ir.values._Undefined())
2980
+ self.assertIs(ir.Undefined, copy.copy(ir.Undefined))
2981
+ self.assertIs(ir.Undefined, copy.deepcopy(ir.Undefined))
2982
+ self.assert_pickle_correctly(ir.Undefined)
2983
+
2984
+
2985
+ if __name__ == '__main__':
2986
+ unittest.main()