llvmlite 0.43.0__cp311-cp311-win_amd64.whl → 0.44.0__cp311-cp311-win_amd64.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 (47) hide show
  1. llvmlite/__init__.py +10 -3
  2. llvmlite/_version.py +2 -2
  3. llvmlite/binding/__init__.py +19 -18
  4. llvmlite/binding/analysis.py +69 -69
  5. llvmlite/binding/common.py +34 -34
  6. llvmlite/binding/context.py +39 -29
  7. llvmlite/binding/dylib.py +45 -45
  8. llvmlite/binding/executionengine.py +330 -330
  9. llvmlite/binding/ffi.py +395 -390
  10. llvmlite/binding/initfini.py +73 -73
  11. llvmlite/binding/linker.py +20 -20
  12. llvmlite/binding/llvmlite.dll +0 -0
  13. llvmlite/binding/module.py +349 -349
  14. llvmlite/binding/newpassmanagers.py +357 -0
  15. llvmlite/binding/object_file.py +82 -82
  16. llvmlite/binding/options.py +17 -17
  17. llvmlite/binding/orcjit.py +342 -342
  18. llvmlite/binding/passmanagers.py +946 -939
  19. llvmlite/binding/targets.py +520 -450
  20. llvmlite/binding/transforms.py +151 -151
  21. llvmlite/binding/typeref.py +285 -198
  22. llvmlite/binding/value.py +632 -618
  23. llvmlite/ir/__init__.py +11 -11
  24. llvmlite/ir/_utils.py +80 -80
  25. llvmlite/ir/builder.py +1120 -1119
  26. llvmlite/ir/context.py +20 -20
  27. llvmlite/ir/instructions.py +920 -893
  28. llvmlite/ir/module.py +246 -246
  29. llvmlite/ir/transforms.py +64 -64
  30. llvmlite/ir/types.py +734 -614
  31. llvmlite/ir/values.py +1217 -1217
  32. llvmlite/tests/__init__.py +57 -57
  33. llvmlite/tests/__main__.py +3 -3
  34. llvmlite/tests/customize.py +407 -407
  35. llvmlite/tests/refprune_proto.py +329 -329
  36. llvmlite/tests/test_binding.py +3208 -2585
  37. llvmlite/tests/test_ir.py +2994 -2729
  38. llvmlite/tests/test_refprune.py +730 -557
  39. llvmlite/tests/test_valuerepr.py +60 -60
  40. llvmlite/utils.py +29 -29
  41. {llvmlite-0.43.0.dist-info → llvmlite-0.44.0.dist-info}/LICENSE +24 -24
  42. {llvmlite-0.43.0.dist-info → llvmlite-0.44.0.dist-info}/LICENSE.thirdparty +225 -225
  43. {llvmlite-0.43.0.dist-info → llvmlite-0.44.0.dist-info}/METADATA +7 -6
  44. llvmlite-0.44.0.dist-info/RECORD +46 -0
  45. {llvmlite-0.43.0.dist-info → llvmlite-0.44.0.dist-info}/WHEEL +1 -1
  46. llvmlite-0.43.0.dist-info/RECORD +0 -45
  47. {llvmlite-0.43.0.dist-info → llvmlite-0.44.0.dist-info}/top_level.txt +0 -0
llvmlite/binding/ffi.py CHANGED
@@ -1,390 +1,395 @@
1
- import sys
2
- import ctypes
3
- import threading
4
- import importlib.resources as _impres
5
-
6
- from llvmlite.binding.common import _decode_string, _is_shutting_down
7
- from llvmlite.utils import get_library_name
8
-
9
-
10
- def _make_opaque_ref(name):
11
- newcls = type(name, (ctypes.Structure,), {})
12
- return ctypes.POINTER(newcls)
13
-
14
-
15
- LLVMContextRef = _make_opaque_ref("LLVMContext")
16
- LLVMModuleRef = _make_opaque_ref("LLVMModule")
17
- LLVMValueRef = _make_opaque_ref("LLVMValue")
18
- LLVMTypeRef = _make_opaque_ref("LLVMType")
19
- LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine")
20
- LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder")
21
- LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager")
22
- LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData")
23
- LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo")
24
- LLVMTargetRef = _make_opaque_ref("LLVMTarget")
25
- LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine")
26
- LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer")
27
- LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator")
28
- LLVMElementIterator = _make_opaque_ref("LLVMElementIterator")
29
- LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator")
30
- LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator")
31
- LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator")
32
- LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator")
33
- LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator")
34
- LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator")
35
- LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator")
36
- LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator")
37
- LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator")
38
- LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache")
39
- LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile")
40
- LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator")
41
- LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef")
42
- LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef")
43
-
44
-
45
- class _LLVMLock:
46
- """A Lock to guarantee thread-safety for the LLVM C-API.
47
-
48
- This class implements __enter__ and __exit__ for acquiring and releasing
49
- the lock as a context manager.
50
-
51
- Also, callbacks can be attached so that every time the lock is acquired
52
- and released the corresponding callbacks will be invoked.
53
- """
54
- def __init__(self):
55
- # The reentrant lock is needed for callbacks that re-enter
56
- # the Python interpreter.
57
- self._lock = threading.RLock()
58
- self._cblist = []
59
-
60
- def register(self, acq_fn, rel_fn):
61
- """Register callbacks that are invoked immediately after the lock is
62
- acquired (``acq_fn()``) and immediately before the lock is released
63
- (``rel_fn()``).
64
- """
65
- self._cblist.append((acq_fn, rel_fn))
66
-
67
- def unregister(self, acq_fn, rel_fn):
68
- """Remove the registered callbacks.
69
- """
70
- self._cblist.remove((acq_fn, rel_fn))
71
-
72
- def __enter__(self):
73
- self._lock.acquire()
74
- # Invoke all callbacks
75
- for acq_fn, rel_fn in self._cblist:
76
- acq_fn()
77
-
78
- def __exit__(self, *exc_details):
79
- # Invoke all callbacks
80
- for acq_fn, rel_fn in self._cblist:
81
- rel_fn()
82
- self._lock.release()
83
-
84
-
85
- class _suppress_cleanup_errors:
86
- def __init__(self, context):
87
- self._context = context
88
-
89
- def __enter__(self):
90
- return self._context.__enter__()
91
-
92
- def __exit__(self, exc_type, exc_value, traceback):
93
- try:
94
- return self._context.__exit__(exc_type, exc_value, traceback)
95
- except PermissionError:
96
- pass # Resource dylibs can't be deleted on Windows.
97
-
98
-
99
- class _lib_wrapper(object):
100
- """Wrap libllvmlite with a lock such that only one thread may access it at
101
- a time.
102
-
103
- This class duck-types a CDLL.
104
- """
105
- __slots__ = ['_lib_handle', '_fntab', '_lock']
106
-
107
- def __init__(self):
108
- self._lib_handle = None
109
- self._fntab = {}
110
- self._lock = _LLVMLock()
111
-
112
- def _load_lib(self):
113
- try:
114
- with _suppress_cleanup_errors(_importlib_resources_path(
115
- __name__.rpartition(".")[0],
116
- get_library_name())) as lib_path:
117
- self._lib_handle = ctypes.CDLL(str(lib_path))
118
- # Check that we can look up expected symbols.
119
- _ = self._lib_handle.LLVMPY_GetVersionInfo()
120
- except (OSError, AttributeError) as e:
121
- # OSError may be raised if the file cannot be opened, or is not
122
- # a shared library.
123
- # AttributeError is raised if LLVMPY_GetVersionInfo does not
124
- # exist.
125
- raise OSError("Could not find/load shared object file") from e
126
-
127
- @property
128
- def _lib(self):
129
- # Not threadsafe.
130
- if not self._lib_handle:
131
- self._load_lib()
132
- return self._lib_handle
133
-
134
- def __getattr__(self, name):
135
- try:
136
- return self._fntab[name]
137
- except KeyError:
138
- # Lazily wraps new functions as they are requested
139
- cfn = getattr(self._lib, name)
140
- wrapped = _lib_fn_wrapper(self._lock, cfn)
141
- self._fntab[name] = wrapped
142
- return wrapped
143
-
144
- @property
145
- def _name(self):
146
- """The name of the library passed in the CDLL constructor.
147
-
148
- For duck-typing a ctypes.CDLL
149
- """
150
- return self._lib._name
151
-
152
- @property
153
- def _handle(self):
154
- """The system handle used to access the library.
155
-
156
- For duck-typing a ctypes.CDLL
157
- """
158
- return self._lib._handle
159
-
160
-
161
- class _lib_fn_wrapper(object):
162
- """Wraps and duck-types a ctypes.CFUNCTYPE to provide
163
- automatic locking when the wrapped function is called.
164
-
165
- TODO: we can add methods to mark the function as threadsafe
166
- and remove the locking-step on call when marked.
167
- """
168
- __slots__ = ['_lock', '_cfn']
169
-
170
- def __init__(self, lock, cfn):
171
- self._lock = lock
172
- self._cfn = cfn
173
-
174
- @property
175
- def argtypes(self):
176
- return self._cfn.argtypes
177
-
178
- @argtypes.setter
179
- def argtypes(self, argtypes):
180
- self._cfn.argtypes = argtypes
181
-
182
- @property
183
- def restype(self):
184
- return self._cfn.restype
185
-
186
- @restype.setter
187
- def restype(self, restype):
188
- self._cfn.restype = restype
189
-
190
- def __call__(self, *args, **kwargs):
191
- with self._lock:
192
- return self._cfn(*args, **kwargs)
193
-
194
-
195
- def _importlib_resources_path_repl(package, resource):
196
- """Replacement implementation of `import.resources.path` to avoid
197
- deprecation warning following code at importlib_resources/_legacy.py
198
- as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy
199
-
200
- Notes on differences from importlib.resources implementation:
201
-
202
- The `_common.normalize_path(resource)` call is skipped because it is an
203
- internal API and it is unnecessary for the use here. What it does is
204
- ensuring `resource` is a str and that it does not contain path separators.
205
- """ # noqa E501
206
- return _impres.as_file(_impres.files(package) / resource)
207
-
208
-
209
- _importlib_resources_path = (_importlib_resources_path_repl
210
- if sys.version_info[:2] >= (3, 9)
211
- else _impres.path)
212
-
213
-
214
- lib = _lib_wrapper()
215
-
216
-
217
- def register_lock_callback(acq_fn, rel_fn):
218
- """Register callback functions for lock acquire and release.
219
- *acq_fn* and *rel_fn* are callables that take no arguments.
220
- """
221
- lib._lock.register(acq_fn, rel_fn)
222
-
223
-
224
- def unregister_lock_callback(acq_fn, rel_fn):
225
- """Remove the registered callback functions for lock acquire and release.
226
- The arguments are the same as used in `register_lock_callback()`.
227
- """
228
- lib._lock.unregister(acq_fn, rel_fn)
229
-
230
-
231
- class _DeadPointer(object):
232
- """
233
- Dummy class to make error messages more helpful.
234
- """
235
-
236
-
237
- class OutputString(object):
238
- """
239
- Object for managing the char* output of LLVM APIs.
240
- """
241
- _as_parameter_ = _DeadPointer()
242
-
243
- @classmethod
244
- def from_return(cls, ptr):
245
- """Constructing from a pointer returned from the C-API.
246
- The pointer must be allocated with LLVMPY_CreateString.
247
-
248
- Note
249
- ----
250
- Because ctypes auto-converts *restype* of *c_char_p* into a python
251
- string, we must use *c_void_p* to obtain the raw pointer.
252
- """
253
- return cls(init=ctypes.cast(ptr, ctypes.c_char_p))
254
-
255
- def __init__(self, owned=True, init=None):
256
- self._ptr = init if init is not None else ctypes.c_char_p(None)
257
- self._as_parameter_ = ctypes.byref(self._ptr)
258
- self._owned = owned
259
-
260
- def close(self):
261
- if self._ptr is not None:
262
- if self._owned:
263
- lib.LLVMPY_DisposeString(self._ptr)
264
- self._ptr = None
265
- del self._as_parameter_
266
-
267
- def __enter__(self):
268
- return self
269
-
270
- def __exit__(self, exc_type, exc_val, exc_tb):
271
- self.close()
272
-
273
- def __del__(self, _is_shutting_down=_is_shutting_down):
274
- # Avoid errors trying to rely on globals and modules at interpreter
275
- # shutdown.
276
- if not _is_shutting_down():
277
- if self.close is not None:
278
- self.close()
279
-
280
- def __str__(self):
281
- if self._ptr is None:
282
- return "<dead OutputString>"
283
- s = self._ptr.value
284
- assert s is not None
285
- return _decode_string(s)
286
-
287
- def __bool__(self):
288
- return bool(self._ptr)
289
-
290
- __nonzero__ = __bool__
291
-
292
- @property
293
- def bytes(self):
294
- """Get the raw bytes of content of the char pointer.
295
- """
296
- return self._ptr.value
297
-
298
-
299
- def ret_string(ptr):
300
- """To wrap string return-value from C-API.
301
- """
302
- if ptr is not None:
303
- return str(OutputString.from_return(ptr))
304
-
305
-
306
- def ret_bytes(ptr):
307
- """To wrap bytes return-value from C-API.
308
- """
309
- if ptr is not None:
310
- return OutputString.from_return(ptr).bytes
311
-
312
-
313
- class ObjectRef(object):
314
- """
315
- A wrapper around a ctypes pointer to a LLVM object ("resource").
316
- """
317
- _closed = False
318
- _as_parameter_ = _DeadPointer()
319
- # Whether this object pointer is owned by another one.
320
- _owned = False
321
-
322
- def __init__(self, ptr):
323
- if ptr is None:
324
- raise ValueError("NULL pointer")
325
- self._ptr = ptr
326
- self._as_parameter_ = ptr
327
- self._capi = lib
328
-
329
- def close(self):
330
- """
331
- Close this object and do any required clean-up actions.
332
- """
333
- try:
334
- if not self._closed and not self._owned:
335
- self._dispose()
336
- finally:
337
- self.detach()
338
-
339
- def detach(self):
340
- """
341
- Detach the underlying LLVM resource without disposing of it.
342
- """
343
- if not self._closed:
344
- del self._as_parameter_
345
- self._closed = True
346
- self._ptr = None
347
-
348
- def _dispose(self):
349
- """
350
- Dispose of the underlying LLVM resource. Should be overriden
351
- by subclasses. Automatically called by close(), __del__() and
352
- __exit__() (unless the resource has been detached).
353
- """
354
-
355
- @property
356
- def closed(self):
357
- """
358
- Whether this object has been closed. A closed object can't
359
- be used anymore.
360
- """
361
- return self._closed
362
-
363
- def __enter__(self):
364
- assert hasattr(self, "close")
365
- if self._closed:
366
- raise RuntimeError("%s instance already closed" % (self.__class__,))
367
- return self
368
-
369
- def __exit__(self, exc_type, exc_val, exc_tb):
370
- self.close()
371
-
372
- def __del__(self, _is_shutting_down=_is_shutting_down):
373
- if not _is_shutting_down():
374
- if self.close is not None:
375
- self.close()
376
-
377
- def __bool__(self):
378
- return bool(self._ptr)
379
-
380
- def __eq__(self, other):
381
- if not hasattr(other, "_ptr"):
382
- return False
383
- return ctypes.addressof(self._ptr[0]) == \
384
- ctypes.addressof(other._ptr[0])
385
-
386
- __nonzero__ = __bool__
387
-
388
- # XXX useful?
389
- def __hash__(self):
390
- return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value)
1
+ import sys
2
+ import ctypes
3
+ import threading
4
+ import importlib.resources as _impres
5
+
6
+ from llvmlite.binding.common import _decode_string, _is_shutting_down
7
+ from llvmlite.utils import get_library_name
8
+
9
+
10
+ def _make_opaque_ref(name):
11
+ newcls = type(name, (ctypes.Structure,), {})
12
+ return ctypes.POINTER(newcls)
13
+
14
+
15
+ LLVMContextRef = _make_opaque_ref("LLVMContext")
16
+ LLVMModuleRef = _make_opaque_ref("LLVMModule")
17
+ LLVMValueRef = _make_opaque_ref("LLVMValue")
18
+ LLVMTypeRef = _make_opaque_ref("LLVMType")
19
+ LLVMExecutionEngineRef = _make_opaque_ref("LLVMExecutionEngine")
20
+ LLVMPassManagerBuilderRef = _make_opaque_ref("LLVMPassManagerBuilder")
21
+ LLVMPassManagerRef = _make_opaque_ref("LLVMPassManager")
22
+ LLVMTargetDataRef = _make_opaque_ref("LLVMTargetData")
23
+ LLVMTargetLibraryInfoRef = _make_opaque_ref("LLVMTargetLibraryInfo")
24
+ LLVMTargetRef = _make_opaque_ref("LLVMTarget")
25
+ LLVMTargetMachineRef = _make_opaque_ref("LLVMTargetMachine")
26
+ LLVMMemoryBufferRef = _make_opaque_ref("LLVMMemoryBuffer")
27
+ LLVMAttributeListIterator = _make_opaque_ref("LLVMAttributeListIterator")
28
+ LLVMElementIterator = _make_opaque_ref("LLVMElementIterator")
29
+ LLVMAttributeSetIterator = _make_opaque_ref("LLVMAttributeSetIterator")
30
+ LLVMGlobalsIterator = _make_opaque_ref("LLVMGlobalsIterator")
31
+ LLVMFunctionsIterator = _make_opaque_ref("LLVMFunctionsIterator")
32
+ LLVMBlocksIterator = _make_opaque_ref("LLVMBlocksIterator")
33
+ LLVMArgumentsIterator = _make_opaque_ref("LLVMArgumentsIterator")
34
+ LLVMInstructionsIterator = _make_opaque_ref("LLVMInstructionsIterator")
35
+ LLVMOperandsIterator = _make_opaque_ref("LLVMOperandsIterator")
36
+ LLVMIncomingBlocksIterator = _make_opaque_ref("LLVMIncomingBlocksIterator")
37
+ LLVMTypesIterator = _make_opaque_ref("LLVMTypesIterator")
38
+ LLVMObjectCacheRef = _make_opaque_ref("LLVMObjectCache")
39
+ LLVMObjectFileRef = _make_opaque_ref("LLVMObjectFile")
40
+ LLVMSectionIteratorRef = _make_opaque_ref("LLVMSectionIterator")
41
+ LLVMOrcLLJITRef = _make_opaque_ref("LLVMOrcLLJITRef")
42
+ LLVMOrcDylibTrackerRef = _make_opaque_ref("LLVMOrcDylibTrackerRef")
43
+
44
+ LLVMPipelineTuningOptionsRef = _make_opaque_ref("LLVMPipeLineTuningOptions")
45
+ LLVMModulePassManagerRef = _make_opaque_ref("LLVMModulePassManager")
46
+ LLVMFunctionPassManagerRef = _make_opaque_ref("LLVMFunctionPassManager")
47
+ LLVMPassBuilderRef = _make_opaque_ref("LLVMPassBuilder")
48
+
49
+
50
+ class _LLVMLock:
51
+ """A Lock to guarantee thread-safety for the LLVM C-API.
52
+
53
+ This class implements __enter__ and __exit__ for acquiring and releasing
54
+ the lock as a context manager.
55
+
56
+ Also, callbacks can be attached so that every time the lock is acquired
57
+ and released the corresponding callbacks will be invoked.
58
+ """
59
+ def __init__(self):
60
+ # The reentrant lock is needed for callbacks that re-enter
61
+ # the Python interpreter.
62
+ self._lock = threading.RLock()
63
+ self._cblist = []
64
+
65
+ def register(self, acq_fn, rel_fn):
66
+ """Register callbacks that are invoked immediately after the lock is
67
+ acquired (``acq_fn()``) and immediately before the lock is released
68
+ (``rel_fn()``).
69
+ """
70
+ self._cblist.append((acq_fn, rel_fn))
71
+
72
+ def unregister(self, acq_fn, rel_fn):
73
+ """Remove the registered callbacks.
74
+ """
75
+ self._cblist.remove((acq_fn, rel_fn))
76
+
77
+ def __enter__(self):
78
+ self._lock.acquire()
79
+ # Invoke all callbacks
80
+ for acq_fn, rel_fn in self._cblist:
81
+ acq_fn()
82
+
83
+ def __exit__(self, *exc_details):
84
+ # Invoke all callbacks
85
+ for acq_fn, rel_fn in self._cblist:
86
+ rel_fn()
87
+ self._lock.release()
88
+
89
+
90
+ class _suppress_cleanup_errors:
91
+ def __init__(self, context):
92
+ self._context = context
93
+
94
+ def __enter__(self):
95
+ return self._context.__enter__()
96
+
97
+ def __exit__(self, exc_type, exc_value, traceback):
98
+ try:
99
+ return self._context.__exit__(exc_type, exc_value, traceback)
100
+ except PermissionError:
101
+ pass # Resource dylibs can't be deleted on Windows.
102
+
103
+
104
+ class _lib_wrapper(object):
105
+ """Wrap libllvmlite with a lock such that only one thread may access it at
106
+ a time.
107
+
108
+ This class duck-types a CDLL.
109
+ """
110
+ __slots__ = ['_lib_handle', '_fntab', '_lock']
111
+
112
+ def __init__(self):
113
+ self._lib_handle = None
114
+ self._fntab = {}
115
+ self._lock = _LLVMLock()
116
+
117
+ def _load_lib(self):
118
+ try:
119
+ with _suppress_cleanup_errors(_importlib_resources_path(
120
+ __name__.rpartition(".")[0],
121
+ get_library_name())) as lib_path:
122
+ self._lib_handle = ctypes.CDLL(str(lib_path))
123
+ # Check that we can look up expected symbols.
124
+ _ = self._lib_handle.LLVMPY_GetVersionInfo()
125
+ except (OSError, AttributeError) as e:
126
+ # OSError may be raised if the file cannot be opened, or is not
127
+ # a shared library.
128
+ # AttributeError is raised if LLVMPY_GetVersionInfo does not
129
+ # exist.
130
+ raise OSError("Could not find/load shared object file") from e
131
+
132
+ @property
133
+ def _lib(self):
134
+ # Not threadsafe.
135
+ if not self._lib_handle:
136
+ self._load_lib()
137
+ return self._lib_handle
138
+
139
+ def __getattr__(self, name):
140
+ try:
141
+ return self._fntab[name]
142
+ except KeyError:
143
+ # Lazily wraps new functions as they are requested
144
+ cfn = getattr(self._lib, name)
145
+ wrapped = _lib_fn_wrapper(self._lock, cfn)
146
+ self._fntab[name] = wrapped
147
+ return wrapped
148
+
149
+ @property
150
+ def _name(self):
151
+ """The name of the library passed in the CDLL constructor.
152
+
153
+ For duck-typing a ctypes.CDLL
154
+ """
155
+ return self._lib._name
156
+
157
+ @property
158
+ def _handle(self):
159
+ """The system handle used to access the library.
160
+
161
+ For duck-typing a ctypes.CDLL
162
+ """
163
+ return self._lib._handle
164
+
165
+
166
+ class _lib_fn_wrapper(object):
167
+ """Wraps and duck-types a ctypes.CFUNCTYPE to provide
168
+ automatic locking when the wrapped function is called.
169
+
170
+ TODO: we can add methods to mark the function as threadsafe
171
+ and remove the locking-step on call when marked.
172
+ """
173
+ __slots__ = ['_lock', '_cfn']
174
+
175
+ def __init__(self, lock, cfn):
176
+ self._lock = lock
177
+ self._cfn = cfn
178
+
179
+ @property
180
+ def argtypes(self):
181
+ return self._cfn.argtypes
182
+
183
+ @argtypes.setter
184
+ def argtypes(self, argtypes):
185
+ self._cfn.argtypes = argtypes
186
+
187
+ @property
188
+ def restype(self):
189
+ return self._cfn.restype
190
+
191
+ @restype.setter
192
+ def restype(self, restype):
193
+ self._cfn.restype = restype
194
+
195
+ def __call__(self, *args, **kwargs):
196
+ with self._lock:
197
+ return self._cfn(*args, **kwargs)
198
+
199
+
200
+ def _importlib_resources_path_repl(package, resource):
201
+ """Replacement implementation of `import.resources.path` to avoid
202
+ deprecation warning following code at importlib_resources/_legacy.py
203
+ as suggested by https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy
204
+
205
+ Notes on differences from importlib.resources implementation:
206
+
207
+ The `_common.normalize_path(resource)` call is skipped because it is an
208
+ internal API and it is unnecessary for the use here. What it does is
209
+ ensuring `resource` is a str and that it does not contain path separators.
210
+ """ # noqa E501
211
+ return _impres.as_file(_impres.files(package) / resource)
212
+
213
+
214
+ _importlib_resources_path = (_importlib_resources_path_repl
215
+ if sys.version_info[:2] >= (3, 10)
216
+ else _impres.path)
217
+
218
+
219
+ lib = _lib_wrapper()
220
+
221
+
222
+ def register_lock_callback(acq_fn, rel_fn):
223
+ """Register callback functions for lock acquire and release.
224
+ *acq_fn* and *rel_fn* are callables that take no arguments.
225
+ """
226
+ lib._lock.register(acq_fn, rel_fn)
227
+
228
+
229
+ def unregister_lock_callback(acq_fn, rel_fn):
230
+ """Remove the registered callback functions for lock acquire and release.
231
+ The arguments are the same as used in `register_lock_callback()`.
232
+ """
233
+ lib._lock.unregister(acq_fn, rel_fn)
234
+
235
+
236
+ class _DeadPointer(object):
237
+ """
238
+ Dummy class to make error messages more helpful.
239
+ """
240
+
241
+
242
+ class OutputString(object):
243
+ """
244
+ Object for managing the char* output of LLVM APIs.
245
+ """
246
+ _as_parameter_ = _DeadPointer()
247
+
248
+ @classmethod
249
+ def from_return(cls, ptr):
250
+ """Constructing from a pointer returned from the C-API.
251
+ The pointer must be allocated with LLVMPY_CreateString.
252
+
253
+ Note
254
+ ----
255
+ Because ctypes auto-converts *restype* of *c_char_p* into a python
256
+ string, we must use *c_void_p* to obtain the raw pointer.
257
+ """
258
+ return cls(init=ctypes.cast(ptr, ctypes.c_char_p))
259
+
260
+ def __init__(self, owned=True, init=None):
261
+ self._ptr = init if init is not None else ctypes.c_char_p(None)
262
+ self._as_parameter_ = ctypes.byref(self._ptr)
263
+ self._owned = owned
264
+
265
+ def close(self):
266
+ if self._ptr is not None:
267
+ if self._owned:
268
+ lib.LLVMPY_DisposeString(self._ptr)
269
+ self._ptr = None
270
+ del self._as_parameter_
271
+
272
+ def __enter__(self):
273
+ return self
274
+
275
+ def __exit__(self, exc_type, exc_val, exc_tb):
276
+ self.close()
277
+
278
+ def __del__(self, _is_shutting_down=_is_shutting_down):
279
+ # Avoid errors trying to rely on globals and modules at interpreter
280
+ # shutdown.
281
+ if not _is_shutting_down():
282
+ if self.close is not None:
283
+ self.close()
284
+
285
+ def __str__(self):
286
+ if self._ptr is None:
287
+ return "<dead OutputString>"
288
+ s = self._ptr.value
289
+ assert s is not None
290
+ return _decode_string(s)
291
+
292
+ def __bool__(self):
293
+ return bool(self._ptr)
294
+
295
+ __nonzero__ = __bool__
296
+
297
+ @property
298
+ def bytes(self):
299
+ """Get the raw bytes of content of the char pointer.
300
+ """
301
+ return self._ptr.value
302
+
303
+
304
+ def ret_string(ptr):
305
+ """To wrap string return-value from C-API.
306
+ """
307
+ if ptr is not None:
308
+ return str(OutputString.from_return(ptr))
309
+
310
+
311
+ def ret_bytes(ptr):
312
+ """To wrap bytes return-value from C-API.
313
+ """
314
+ if ptr is not None:
315
+ return OutputString.from_return(ptr).bytes
316
+
317
+
318
+ class ObjectRef(object):
319
+ """
320
+ A wrapper around a ctypes pointer to a LLVM object ("resource").
321
+ """
322
+ _closed = False
323
+ _as_parameter_ = _DeadPointer()
324
+ # Whether this object pointer is owned by another one.
325
+ _owned = False
326
+
327
+ def __init__(self, ptr):
328
+ if ptr is None:
329
+ raise ValueError("NULL pointer")
330
+ self._ptr = ptr
331
+ self._as_parameter_ = ptr
332
+ self._capi = lib
333
+
334
+ def close(self):
335
+ """
336
+ Close this object and do any required clean-up actions.
337
+ """
338
+ try:
339
+ if not self._closed and not self._owned:
340
+ self._dispose()
341
+ finally:
342
+ self.detach()
343
+
344
+ def detach(self):
345
+ """
346
+ Detach the underlying LLVM resource without disposing of it.
347
+ """
348
+ if not self._closed:
349
+ del self._as_parameter_
350
+ self._closed = True
351
+ self._ptr = None
352
+
353
+ def _dispose(self):
354
+ """
355
+ Dispose of the underlying LLVM resource. Should be overriden
356
+ by subclasses. Automatically called by close(), __del__() and
357
+ __exit__() (unless the resource has been detached).
358
+ """
359
+
360
+ @property
361
+ def closed(self):
362
+ """
363
+ Whether this object has been closed. A closed object can't
364
+ be used anymore.
365
+ """
366
+ return self._closed
367
+
368
+ def __enter__(self):
369
+ assert hasattr(self, "close")
370
+ if self._closed:
371
+ raise RuntimeError("%s instance already closed" % (self.__class__,))
372
+ return self
373
+
374
+ def __exit__(self, exc_type, exc_val, exc_tb):
375
+ self.close()
376
+
377
+ def __del__(self, _is_shutting_down=_is_shutting_down):
378
+ if not _is_shutting_down():
379
+ if self.close is not None:
380
+ self.close()
381
+
382
+ def __bool__(self):
383
+ return bool(self._ptr)
384
+
385
+ def __eq__(self, other):
386
+ if not hasattr(other, "_ptr"):
387
+ return False
388
+ return ctypes.addressof(self._ptr[0]) == \
389
+ ctypes.addressof(other._ptr[0])
390
+
391
+ __nonzero__ = __bool__
392
+
393
+ # XXX useful?
394
+ def __hash__(self):
395
+ return hash(ctypes.cast(self._ptr, ctypes.c_void_p).value)