Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitattributes +1 -0
- vllm/lib/python3.10/site-packages/et_xmlfile/__init__.py +8 -0
- vllm/lib/python3.10/site-packages/et_xmlfile/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/et_xmlfile/__pycache__/incremental_tree.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/et_xmlfile/__pycache__/xmlfile.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/et_xmlfile/incremental_tree.py +917 -0
- vllm/lib/python3.10/site-packages/et_xmlfile/xmlfile.py +158 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/INSTALLER +1 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/LICENSE +21 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/METADATA +226 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/RECORD +14 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/REQUESTED +0 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/WHEEL +7 -0
- vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/top_level.txt +1 -0
- vllm/lib/python3.10/site-packages/llvmlite/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/__pycache__/_version.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/__pycache__/utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__init__.py +11 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/_utils.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/builder.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/context.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/instructions.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/module.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/transforms.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/types.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/values.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/_utils.py +80 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/builder.py +1119 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/context.py +20 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/instructions.py +893 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/module.py +246 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/transforms.py +64 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/types.py +614 -0
- vllm/lib/python3.10/site-packages/llvmlite/ir/values.py +1217 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/__main__.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/customize.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/refprune_proto.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_binding.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_ir.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_refprune.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_valuerepr.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/refprune_proto.py +329 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/test_binding.py +2585 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/test_ir.py +0 -0
- vllm/lib/python3.10/site-packages/llvmlite/tests/test_refprune.py +557 -0
- vllm/lib/python3.10/site-packages/mpl_toolkits/axisartist/__init__.py +14 -0
- vllm/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-310.pyc +0 -0
- vllm/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-310.pyc +0 -0
.gitattributes
CHANGED
|
@@ -1694,3 +1694,4 @@ vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/solvers.cpython-310.
|
|
| 1694 |
vllm/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1695 |
parrot/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1696 |
vllm/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solveset.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
| 1694 |
vllm/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1695 |
parrot/lib/python3.10/site-packages/scipy/linalg/_solve_toeplitz.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
|
| 1696 |
vllm/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solveset.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
| 1697 |
+
vllm/lib/python3.10/site-packages/sympy/solvers/ode/__pycache__/ode.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
|
vllm/lib/python3.10/site-packages/et_xmlfile/__init__.py
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .xmlfile import xmlfile
|
| 2 |
+
|
| 3 |
+
# constants
|
| 4 |
+
__version__ = '2.0.0'
|
| 5 |
+
__author__ = 'See AUTHORS.txt'
|
| 6 |
+
__license__ = 'MIT'
|
| 7 |
+
__author_email__ = 'charlie.clark@clark-consulting.eu'
|
| 8 |
+
__url__ = 'https://foss.heptapod.net/openpyxl/et_xmlfile'
|
vllm/lib/python3.10/site-packages/et_xmlfile/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (396 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/et_xmlfile/__pycache__/incremental_tree.cpython-310.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/et_xmlfile/__pycache__/xmlfile.cpython-310.pyc
ADDED
|
Binary file (3.66 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/et_xmlfile/incremental_tree.py
ADDED
|
@@ -0,0 +1,917 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Code modified from cPython's Lib/xml/etree/ElementTree.py
|
| 2 |
+
# The write() code is modified to allow specifying a particular namespace
|
| 3 |
+
# uri -> prefix mapping.
|
| 4 |
+
#
|
| 5 |
+
# ---------------------------------------------------------------------
|
| 6 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 7 |
+
# See https://www.python.org/psf/license for licensing details.
|
| 8 |
+
#
|
| 9 |
+
# ElementTree
|
| 10 |
+
# Copyright (c) 1999-2008 by Fredrik Lundh. All rights reserved.
|
| 11 |
+
#
|
| 12 |
+
# fredrik@pythonware.com
|
| 13 |
+
# http://www.pythonware.com
|
| 14 |
+
# --------------------------------------------------------------------
|
| 15 |
+
# The ElementTree toolkit is
|
| 16 |
+
#
|
| 17 |
+
# Copyright (c) 1999-2008 by Fredrik Lundh
|
| 18 |
+
#
|
| 19 |
+
# By obtaining, using, and/or copying this software and/or its
|
| 20 |
+
# associated documentation, you agree that you have read, understood,
|
| 21 |
+
# and will comply with the following terms and conditions:
|
| 22 |
+
#
|
| 23 |
+
# Permission to use, copy, modify, and distribute this software and
|
| 24 |
+
# its associated documentation for any purpose and without fee is
|
| 25 |
+
# hereby granted, provided that the above copyright notice appears in
|
| 26 |
+
# all copies, and that both that copyright notice and this permission
|
| 27 |
+
# notice appear in supporting documentation, and that the name of
|
| 28 |
+
# Secret Labs AB or the author not be used in advertising or publicity
|
| 29 |
+
# pertaining to distribution of the software without specific, written
|
| 30 |
+
# prior permission.
|
| 31 |
+
#
|
| 32 |
+
# SECRET LABS AB AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
|
| 33 |
+
# TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANT-
|
| 34 |
+
# ABILITY AND FITNESS. IN NO EVENT SHALL SECRET LABS AB OR THE AUTHOR
|
| 35 |
+
# BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY
|
| 36 |
+
# DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
|
| 37 |
+
# WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS
|
| 38 |
+
# ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
|
| 39 |
+
# OF THIS SOFTWARE.
|
| 40 |
+
# --------------------------------------------------------------------
|
| 41 |
+
import contextlib
|
| 42 |
+
import io
|
| 43 |
+
|
| 44 |
+
import xml.etree.ElementTree as ET
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def current_global_nsmap():
|
| 48 |
+
return {
|
| 49 |
+
prefix: uri for uri, prefix in ET._namespace_map.items()
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class IncrementalTree(ET.ElementTree):
|
| 54 |
+
|
| 55 |
+
def write(
|
| 56 |
+
self,
|
| 57 |
+
file_or_filename,
|
| 58 |
+
encoding=None,
|
| 59 |
+
xml_declaration=None,
|
| 60 |
+
default_namespace=None,
|
| 61 |
+
method=None,
|
| 62 |
+
*,
|
| 63 |
+
short_empty_elements=True,
|
| 64 |
+
nsmap=None,
|
| 65 |
+
root_ns_only=False,
|
| 66 |
+
minimal_ns_only=False,
|
| 67 |
+
):
|
| 68 |
+
"""Write element tree to a file as XML.
|
| 69 |
+
|
| 70 |
+
Arguments:
|
| 71 |
+
*file_or_filename* -- file name or a file object opened for writing
|
| 72 |
+
|
| 73 |
+
*encoding* -- the output encoding (default: US-ASCII)
|
| 74 |
+
|
| 75 |
+
*xml_declaration* -- bool indicating if an XML declaration should be
|
| 76 |
+
added to the output. If None, an XML declaration
|
| 77 |
+
is added if encoding IS NOT either of:
|
| 78 |
+
US-ASCII, UTF-8, or Unicode
|
| 79 |
+
|
| 80 |
+
*default_namespace* -- sets the default XML namespace (for "xmlns").
|
| 81 |
+
Takes precedence over any default namespace
|
| 82 |
+
provided in nsmap or
|
| 83 |
+
xml.etree.ElementTree.register_namespace().
|
| 84 |
+
|
| 85 |
+
*method* -- either "xml" (default), "html, "text", or "c14n"
|
| 86 |
+
|
| 87 |
+
*short_empty_elements* -- controls the formatting of elements
|
| 88 |
+
that contain no content. If True (default)
|
| 89 |
+
they are emitted as a single self-closed
|
| 90 |
+
tag, otherwise they are emitted as a pair
|
| 91 |
+
of start/end tags
|
| 92 |
+
|
| 93 |
+
*nsmap* -- a mapping of namespace prefixes to URIs. These take
|
| 94 |
+
precedence over any mappings registered using
|
| 95 |
+
xml.etree.ElementTree.register_namespace(). The
|
| 96 |
+
default_namespace argument, if supplied, takes precedence
|
| 97 |
+
over any default namespace supplied in nsmap. All supplied
|
| 98 |
+
namespaces will be declared on the root element, even if
|
| 99 |
+
unused in the document.
|
| 100 |
+
|
| 101 |
+
*root_ns_only* -- bool indicating namespace declrations should only
|
| 102 |
+
be written on the root element. This requires two
|
| 103 |
+
passes of the xml tree adding additional time to
|
| 104 |
+
the writing process. This is primarily meant to
|
| 105 |
+
mimic xml.etree.ElementTree's behaviour.
|
| 106 |
+
|
| 107 |
+
*minimal_ns_only* -- bool indicating only namespaces that were used
|
| 108 |
+
to qualify elements or attributes should be
|
| 109 |
+
declared. All namespace declarations will be
|
| 110 |
+
written on the root element regardless of the
|
| 111 |
+
value of the root_ns_only arg. Requires two
|
| 112 |
+
passes of the xml tree adding additional time to
|
| 113 |
+
the writing process.
|
| 114 |
+
|
| 115 |
+
"""
|
| 116 |
+
if not method:
|
| 117 |
+
method = "xml"
|
| 118 |
+
elif method not in ("text", "xml", "html"):
|
| 119 |
+
raise ValueError("unknown method %r" % method)
|
| 120 |
+
if not encoding:
|
| 121 |
+
encoding = "us-ascii"
|
| 122 |
+
|
| 123 |
+
with _get_writer(file_or_filename, encoding) as (write, declared_encoding):
|
| 124 |
+
if method == "xml" and (
|
| 125 |
+
xml_declaration
|
| 126 |
+
or (
|
| 127 |
+
xml_declaration is None
|
| 128 |
+
and encoding.lower() != "unicode"
|
| 129 |
+
and declared_encoding.lower() not in ("utf-8", "us-ascii")
|
| 130 |
+
)
|
| 131 |
+
):
|
| 132 |
+
write("<?xml version='1.0' encoding='%s'?>\n" % (declared_encoding,))
|
| 133 |
+
if method == "text":
|
| 134 |
+
ET._serialize_text(write, self._root)
|
| 135 |
+
else:
|
| 136 |
+
if method == "xml":
|
| 137 |
+
is_html = False
|
| 138 |
+
else:
|
| 139 |
+
is_html = True
|
| 140 |
+
if nsmap:
|
| 141 |
+
if None in nsmap:
|
| 142 |
+
raise ValueError(
|
| 143 |
+
'Found None as default nsmap prefix in nsmap. '
|
| 144 |
+
'Use "" as the default namespace prefix.'
|
| 145 |
+
)
|
| 146 |
+
new_nsmap = nsmap.copy()
|
| 147 |
+
else:
|
| 148 |
+
new_nsmap = {}
|
| 149 |
+
if default_namespace:
|
| 150 |
+
new_nsmap[""] = default_namespace
|
| 151 |
+
if root_ns_only or minimal_ns_only:
|
| 152 |
+
# _namespaces returns a mapping of only the namespaces that
|
| 153 |
+
# were used.
|
| 154 |
+
new_nsmap = _namespaces(
|
| 155 |
+
self._root,
|
| 156 |
+
default_namespace,
|
| 157 |
+
new_nsmap,
|
| 158 |
+
)
|
| 159 |
+
if not minimal_ns_only:
|
| 160 |
+
if nsmap:
|
| 161 |
+
# We want all namespaces defined in the provided
|
| 162 |
+
# nsmap to be declared regardless of whether
|
| 163 |
+
# they've been used.
|
| 164 |
+
new_nsmap.update(nsmap)
|
| 165 |
+
if default_namespace:
|
| 166 |
+
new_nsmap[""] = default_namespace
|
| 167 |
+
global_nsmap = {
|
| 168 |
+
prefix: uri for uri, prefix in ET._namespace_map.items()
|
| 169 |
+
}
|
| 170 |
+
if None in global_nsmap:
|
| 171 |
+
raise ValueError(
|
| 172 |
+
'Found None as default nsmap prefix in nsmap registered with '
|
| 173 |
+
'register_namespace. Use "" for the default namespace prefix.'
|
| 174 |
+
)
|
| 175 |
+
nsmap_scope = {}
|
| 176 |
+
_serialize_ns_xml(
|
| 177 |
+
write,
|
| 178 |
+
self._root,
|
| 179 |
+
nsmap_scope,
|
| 180 |
+
global_nsmap,
|
| 181 |
+
is_html=is_html,
|
| 182 |
+
is_root=True,
|
| 183 |
+
short_empty_elements=short_empty_elements,
|
| 184 |
+
new_nsmap=new_nsmap,
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _make_new_ns_prefix(
|
| 189 |
+
nsmap_scope,
|
| 190 |
+
global_prefixes,
|
| 191 |
+
local_nsmap=None,
|
| 192 |
+
default_namespace=None,
|
| 193 |
+
):
|
| 194 |
+
i = len(nsmap_scope)
|
| 195 |
+
if default_namespace is not None and "" not in nsmap_scope:
|
| 196 |
+
# Keep the same numbering scheme as python which assumes the default
|
| 197 |
+
# namespace is present if supplied.
|
| 198 |
+
i += 1
|
| 199 |
+
|
| 200 |
+
while True:
|
| 201 |
+
prefix = f"ns{i}"
|
| 202 |
+
if (
|
| 203 |
+
prefix not in nsmap_scope
|
| 204 |
+
and prefix not in global_prefixes
|
| 205 |
+
and (
|
| 206 |
+
not local_nsmap or prefix not in local_nsmap
|
| 207 |
+
)
|
| 208 |
+
):
|
| 209 |
+
return prefix
|
| 210 |
+
i += 1
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _get_or_create_prefix(
|
| 214 |
+
uri,
|
| 215 |
+
nsmap_scope,
|
| 216 |
+
global_nsmap,
|
| 217 |
+
new_namespace_prefixes,
|
| 218 |
+
uri_to_prefix,
|
| 219 |
+
for_default_namespace_attr_prefix=False,
|
| 220 |
+
):
|
| 221 |
+
"""Find a prefix that doesn't conflict with the ns scope or create a new prefix
|
| 222 |
+
|
| 223 |
+
This function mutates nsmap_scope, global_nsmap, new_namespace_prefixes and
|
| 224 |
+
uri_to_prefix. It is intended to keep state in _serialize_ns_xml consistent
|
| 225 |
+
while deduplicating the house keeping code or updating these dictionaries.
|
| 226 |
+
"""
|
| 227 |
+
# Check if we can reuse an existing (global) prefix within the current
|
| 228 |
+
# namespace scope. There maybe many prefixes pointing to a single URI by
|
| 229 |
+
# this point and we need to select a prefix that is not in use in the
|
| 230 |
+
# current scope.
|
| 231 |
+
for global_prefix, global_uri in global_nsmap.items():
|
| 232 |
+
if uri == global_uri and global_prefix not in nsmap_scope:
|
| 233 |
+
prefix = global_prefix
|
| 234 |
+
break
|
| 235 |
+
else: # no break
|
| 236 |
+
# We couldn't find a suitable existing prefix for this namespace scope,
|
| 237 |
+
# let's create a new one.
|
| 238 |
+
prefix = _make_new_ns_prefix(nsmap_scope, global_prefixes=global_nsmap)
|
| 239 |
+
global_nsmap[prefix] = uri
|
| 240 |
+
nsmap_scope[prefix] = uri
|
| 241 |
+
if not for_default_namespace_attr_prefix:
|
| 242 |
+
# Don't override the actual default namespace prefix
|
| 243 |
+
uri_to_prefix[uri] = prefix
|
| 244 |
+
if prefix != "xml":
|
| 245 |
+
new_namespace_prefixes.add(prefix)
|
| 246 |
+
return prefix
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _find_default_namespace_attr_prefix(
|
| 250 |
+
default_namespace,
|
| 251 |
+
nsmap,
|
| 252 |
+
local_nsmap,
|
| 253 |
+
global_prefixes,
|
| 254 |
+
provided_default_namespace=None,
|
| 255 |
+
):
|
| 256 |
+
# Search the provided nsmap for any prefixes for this uri that aren't the
|
| 257 |
+
# default namespace ""
|
| 258 |
+
for prefix, uri in nsmap.items():
|
| 259 |
+
if uri == default_namespace and prefix != "":
|
| 260 |
+
return prefix
|
| 261 |
+
|
| 262 |
+
for prefix, uri in local_nsmap.items():
|
| 263 |
+
if uri == default_namespace and prefix != "":
|
| 264 |
+
return prefix
|
| 265 |
+
|
| 266 |
+
# _namespace_map is a 1:1 mapping of uri -> prefix
|
| 267 |
+
prefix = ET._namespace_map.get(default_namespace)
|
| 268 |
+
if prefix and prefix not in nsmap:
|
| 269 |
+
return prefix
|
| 270 |
+
|
| 271 |
+
return _make_new_ns_prefix(
|
| 272 |
+
nsmap,
|
| 273 |
+
global_prefixes,
|
| 274 |
+
local_nsmap,
|
| 275 |
+
provided_default_namespace,
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
def process_attribs(
|
| 280 |
+
elem,
|
| 281 |
+
is_nsmap_scope_changed,
|
| 282 |
+
default_ns_attr_prefix,
|
| 283 |
+
nsmap_scope,
|
| 284 |
+
global_nsmap,
|
| 285 |
+
new_namespace_prefixes,
|
| 286 |
+
uri_to_prefix,
|
| 287 |
+
):
|
| 288 |
+
item_parts = []
|
| 289 |
+
for k, v in elem.items():
|
| 290 |
+
if isinstance(k, ET.QName):
|
| 291 |
+
k = k.text
|
| 292 |
+
try:
|
| 293 |
+
if k[:1] == "{":
|
| 294 |
+
uri_and_name = k[1:].rsplit("}", 1)
|
| 295 |
+
try:
|
| 296 |
+
prefix = uri_to_prefix[uri_and_name[0]]
|
| 297 |
+
except KeyError:
|
| 298 |
+
if not is_nsmap_scope_changed:
|
| 299 |
+
# We're about to mutate the these dicts so
|
| 300 |
+
# let's copy them first. We don't have to
|
| 301 |
+
# recompute other mappings as we're looking up
|
| 302 |
+
# or creating a new prefix
|
| 303 |
+
nsmap_scope = nsmap_scope.copy()
|
| 304 |
+
uri_to_prefix = uri_to_prefix.copy()
|
| 305 |
+
is_nsmap_scope_changed = True
|
| 306 |
+
prefix = _get_or_create_prefix(
|
| 307 |
+
uri_and_name[0],
|
| 308 |
+
nsmap_scope,
|
| 309 |
+
global_nsmap,
|
| 310 |
+
new_namespace_prefixes,
|
| 311 |
+
uri_to_prefix,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
if not prefix:
|
| 315 |
+
if default_ns_attr_prefix:
|
| 316 |
+
prefix = default_ns_attr_prefix
|
| 317 |
+
else:
|
| 318 |
+
for prefix, known_uri in nsmap_scope.items():
|
| 319 |
+
if known_uri == uri_and_name[0] and prefix != "":
|
| 320 |
+
default_ns_attr_prefix = prefix
|
| 321 |
+
break
|
| 322 |
+
else: # no break
|
| 323 |
+
if not is_nsmap_scope_changed:
|
| 324 |
+
# We're about to mutate the these dicts so
|
| 325 |
+
# let's copy them first. We don't have to
|
| 326 |
+
# recompute other mappings as we're looking up
|
| 327 |
+
# or creating a new prefix
|
| 328 |
+
nsmap_scope = nsmap_scope.copy()
|
| 329 |
+
uri_to_prefix = uri_to_prefix.copy()
|
| 330 |
+
is_nsmap_scope_changed = True
|
| 331 |
+
prefix = _get_or_create_prefix(
|
| 332 |
+
uri_and_name[0],
|
| 333 |
+
nsmap_scope,
|
| 334 |
+
global_nsmap,
|
| 335 |
+
new_namespace_prefixes,
|
| 336 |
+
uri_to_prefix,
|
| 337 |
+
for_default_namespace_attr_prefix=True,
|
| 338 |
+
)
|
| 339 |
+
default_ns_attr_prefix = prefix
|
| 340 |
+
k = f"{prefix}:{uri_and_name[1]}"
|
| 341 |
+
except TypeError:
|
| 342 |
+
ET._raise_serialization_error(k)
|
| 343 |
+
|
| 344 |
+
if isinstance(v, ET.QName):
|
| 345 |
+
if v.text[:1] != "{":
|
| 346 |
+
v = v.text
|
| 347 |
+
else:
|
| 348 |
+
uri_and_name = v.text[1:].rsplit("}", 1)
|
| 349 |
+
try:
|
| 350 |
+
prefix = uri_to_prefix[uri_and_name[0]]
|
| 351 |
+
except KeyError:
|
| 352 |
+
if not is_nsmap_scope_changed:
|
| 353 |
+
# We're about to mutate the these dicts so
|
| 354 |
+
# let's copy them first. We don't have to
|
| 355 |
+
# recompute other mappings as we're looking up
|
| 356 |
+
# or creating a new prefix
|
| 357 |
+
nsmap_scope = nsmap_scope.copy()
|
| 358 |
+
uri_to_prefix = uri_to_prefix.copy()
|
| 359 |
+
is_nsmap_scope_changed = True
|
| 360 |
+
prefix = _get_or_create_prefix(
|
| 361 |
+
uri_and_name[0],
|
| 362 |
+
nsmap_scope,
|
| 363 |
+
global_nsmap,
|
| 364 |
+
new_namespace_prefixes,
|
| 365 |
+
uri_to_prefix,
|
| 366 |
+
)
|
| 367 |
+
v = f"{prefix}:{uri_and_name[1]}"
|
| 368 |
+
item_parts.append((k, v))
|
| 369 |
+
return item_parts, default_ns_attr_prefix, nsmap_scope
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
def write_elem_start(
|
| 373 |
+
write,
|
| 374 |
+
elem,
|
| 375 |
+
nsmap_scope,
|
| 376 |
+
global_nsmap,
|
| 377 |
+
short_empty_elements,
|
| 378 |
+
is_html,
|
| 379 |
+
is_root=False,
|
| 380 |
+
uri_to_prefix=None,
|
| 381 |
+
default_ns_attr_prefix=None,
|
| 382 |
+
new_nsmap=None,
|
| 383 |
+
**kwargs,
|
| 384 |
+
):
|
| 385 |
+
"""Write the opening tag (including self closing) and element text.
|
| 386 |
+
|
| 387 |
+
Refer to _serialize_ns_xml for description of arguments.
|
| 388 |
+
|
| 389 |
+
nsmap_scope should be an empty dictionary on first call. All nsmap prefixes
|
| 390 |
+
must be strings with the default namespace prefix represented by "".
|
| 391 |
+
|
| 392 |
+
eg.
|
| 393 |
+
- <foo attr1="one"> (returns tag = 'foo')
|
| 394 |
+
- <foo attr1="one">text (returns tag = 'foo')
|
| 395 |
+
- <foo attr1="one" /> (returns tag = None)
|
| 396 |
+
|
| 397 |
+
Returns:
|
| 398 |
+
tag:
|
| 399 |
+
The tag name to be closed or None if no closing required.
|
| 400 |
+
nsmap_scope:
|
| 401 |
+
The current nsmap after any prefix to uri additions from this
|
| 402 |
+
element. This is the input dict if unmodified or an updated copy.
|
| 403 |
+
default_ns_attr_prefix:
|
| 404 |
+
The prefix for the default namespace to use with attrs.
|
| 405 |
+
uri_to_prefix:
|
| 406 |
+
The current uri to prefix map after any uri to prefix additions
|
| 407 |
+
from this element. This is the input dict if unmodified or an
|
| 408 |
+
updated copy.
|
| 409 |
+
next_remains_root:
|
| 410 |
+
A bool indicating if the child element(s) should be treated as
|
| 411 |
+
their own roots.
|
| 412 |
+
"""
|
| 413 |
+
tag = elem.tag
|
| 414 |
+
text = elem.text
|
| 415 |
+
|
| 416 |
+
if tag is ET.Comment:
|
| 417 |
+
write("<!--%s-->" % text)
|
| 418 |
+
tag = None
|
| 419 |
+
next_remains_root = False
|
| 420 |
+
elif tag is ET.ProcessingInstruction:
|
| 421 |
+
write("<?%s?>" % text)
|
| 422 |
+
tag = None
|
| 423 |
+
next_remains_root = False
|
| 424 |
+
else:
|
| 425 |
+
if new_nsmap:
|
| 426 |
+
is_nsmap_scope_changed = True
|
| 427 |
+
nsmap_scope = nsmap_scope.copy()
|
| 428 |
+
nsmap_scope.update(new_nsmap)
|
| 429 |
+
new_namespace_prefixes = set(new_nsmap.keys())
|
| 430 |
+
new_namespace_prefixes.discard("xml")
|
| 431 |
+
# We need to recompute the uri to prefixes
|
| 432 |
+
uri_to_prefix = None
|
| 433 |
+
default_ns_attr_prefix = None
|
| 434 |
+
else:
|
| 435 |
+
is_nsmap_scope_changed = False
|
| 436 |
+
new_namespace_prefixes = set()
|
| 437 |
+
|
| 438 |
+
if uri_to_prefix is None:
|
| 439 |
+
if None in nsmap_scope:
|
| 440 |
+
raise ValueError(
|
| 441 |
+
'Found None as a namespace prefix. Use "" as the default namespace prefix.'
|
| 442 |
+
)
|
| 443 |
+
uri_to_prefix = {uri: prefix for prefix, uri in nsmap_scope.items()}
|
| 444 |
+
if "" in nsmap_scope:
|
| 445 |
+
# There may be multiple prefixes for the default namespace but
|
| 446 |
+
# we want to make sure we preferentially use "" (for elements)
|
| 447 |
+
uri_to_prefix[nsmap_scope[""]] = ""
|
| 448 |
+
|
| 449 |
+
if tag is None:
|
| 450 |
+
# tag supression where tag is set to None
|
| 451 |
+
# Don't change is_root so namespaces can be passed down
|
| 452 |
+
next_remains_root = is_root
|
| 453 |
+
if text:
|
| 454 |
+
write(ET._escape_cdata(text))
|
| 455 |
+
else:
|
| 456 |
+
next_remains_root = False
|
| 457 |
+
if isinstance(tag, ET.QName):
|
| 458 |
+
tag = tag.text
|
| 459 |
+
try:
|
| 460 |
+
# These splits / fully qualified tag creationg are the
|
| 461 |
+
# bottleneck in this implementation vs the python
|
| 462 |
+
# implementation.
|
| 463 |
+
# The following split takes ~42ns with no uri and ~85ns if a
|
| 464 |
+
# prefix is present. If the uri was present, we then need to
|
| 465 |
+
# look up a prefix (~14ns) and create the fully qualified
|
| 466 |
+
# string (~41ns). This gives a total of ~140ns where a uri is
|
| 467 |
+
# present.
|
| 468 |
+
# Python's implementation needs to preprocess the tree to
|
| 469 |
+
# create a dict of qname -> tag by traversing the tree which
|
| 470 |
+
# takes a bit of extra time but it quickly makes that back by
|
| 471 |
+
# only having to do a dictionary look up (~14ns) for each tag /
|
| 472 |
+
# attrname vs our splitting (~140ns).
|
| 473 |
+
# So here we have the flexibility of being able to redefine the
|
| 474 |
+
# uri a prefix points to midway through serialisation at the
|
| 475 |
+
# expense of performance (~10% slower for a 1mb file on my
|
| 476 |
+
# machine).
|
| 477 |
+
if tag[:1] == "{":
|
| 478 |
+
uri_and_name = tag[1:].rsplit("}", 1)
|
| 479 |
+
try:
|
| 480 |
+
prefix = uri_to_prefix[uri_and_name[0]]
|
| 481 |
+
except KeyError:
|
| 482 |
+
if not is_nsmap_scope_changed:
|
| 483 |
+
# We're about to mutate the these dicts so let's
|
| 484 |
+
# copy them first. We don't have to recompute other
|
| 485 |
+
# mappings as we're looking up or creating a new
|
| 486 |
+
# prefix
|
| 487 |
+
nsmap_scope = nsmap_scope.copy()
|
| 488 |
+
uri_to_prefix = uri_to_prefix.copy()
|
| 489 |
+
is_nsmap_scope_changed = True
|
| 490 |
+
prefix = _get_or_create_prefix(
|
| 491 |
+
uri_and_name[0],
|
| 492 |
+
nsmap_scope,
|
| 493 |
+
global_nsmap,
|
| 494 |
+
new_namespace_prefixes,
|
| 495 |
+
uri_to_prefix,
|
| 496 |
+
)
|
| 497 |
+
if prefix:
|
| 498 |
+
tag = f"{prefix}:{uri_and_name[1]}"
|
| 499 |
+
else:
|
| 500 |
+
tag = uri_and_name[1]
|
| 501 |
+
elif "" in nsmap_scope:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
"cannot use non-qualified names with default_namespace option"
|
| 504 |
+
)
|
| 505 |
+
except TypeError:
|
| 506 |
+
ET._raise_serialization_error(tag)
|
| 507 |
+
|
| 508 |
+
write("<" + tag)
|
| 509 |
+
|
| 510 |
+
if elem.attrib:
|
| 511 |
+
item_parts, default_ns_attr_prefix, nsmap_scope = process_attribs(
|
| 512 |
+
elem,
|
| 513 |
+
is_nsmap_scope_changed,
|
| 514 |
+
default_ns_attr_prefix,
|
| 515 |
+
nsmap_scope,
|
| 516 |
+
global_nsmap,
|
| 517 |
+
new_namespace_prefixes,
|
| 518 |
+
uri_to_prefix,
|
| 519 |
+
)
|
| 520 |
+
else:
|
| 521 |
+
item_parts = []
|
| 522 |
+
if new_namespace_prefixes:
|
| 523 |
+
ns_attrs = []
|
| 524 |
+
for k in sorted(new_namespace_prefixes):
|
| 525 |
+
v = nsmap_scope[k]
|
| 526 |
+
if k:
|
| 527 |
+
k = "xmlns:" + k
|
| 528 |
+
else:
|
| 529 |
+
k = "xmlns"
|
| 530 |
+
ns_attrs.append((k, v))
|
| 531 |
+
if is_html:
|
| 532 |
+
write("".join([f' {k}="{ET._escape_attrib_html(v)}"' for k, v in ns_attrs]))
|
| 533 |
+
else:
|
| 534 |
+
write("".join([f' {k}="{ET._escape_attrib(v)}"' for k, v in ns_attrs]))
|
| 535 |
+
if item_parts:
|
| 536 |
+
if is_html:
|
| 537 |
+
write("".join([f' {k}="{ET._escape_attrib_html(v)}"' for k, v in item_parts]))
|
| 538 |
+
else:
|
| 539 |
+
write("".join([f' {k}="{ET._escape_attrib(v)}"' for k, v in item_parts]))
|
| 540 |
+
if is_html:
|
| 541 |
+
write(">")
|
| 542 |
+
ltag = tag.lower()
|
| 543 |
+
if text:
|
| 544 |
+
if ltag == "script" or ltag == "style":
|
| 545 |
+
write(text)
|
| 546 |
+
else:
|
| 547 |
+
write(ET._escape_cdata(text))
|
| 548 |
+
if ltag in ET.HTML_EMPTY:
|
| 549 |
+
tag = None
|
| 550 |
+
elif text or len(elem) or not short_empty_elements:
|
| 551 |
+
write(">")
|
| 552 |
+
if text:
|
| 553 |
+
write(ET._escape_cdata(text))
|
| 554 |
+
else:
|
| 555 |
+
tag = None
|
| 556 |
+
write(" />")
|
| 557 |
+
return (
|
| 558 |
+
tag,
|
| 559 |
+
nsmap_scope,
|
| 560 |
+
default_ns_attr_prefix,
|
| 561 |
+
uri_to_prefix,
|
| 562 |
+
next_remains_root,
|
| 563 |
+
)
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
def _serialize_ns_xml(
|
| 567 |
+
write,
|
| 568 |
+
elem,
|
| 569 |
+
nsmap_scope,
|
| 570 |
+
global_nsmap,
|
| 571 |
+
short_empty_elements,
|
| 572 |
+
is_html,
|
| 573 |
+
is_root=False,
|
| 574 |
+
uri_to_prefix=None,
|
| 575 |
+
default_ns_attr_prefix=None,
|
| 576 |
+
new_nsmap=None,
|
| 577 |
+
**kwargs,
|
| 578 |
+
):
|
| 579 |
+
"""Serialize an element or tree using 'write' for output.
|
| 580 |
+
|
| 581 |
+
Args:
|
| 582 |
+
write:
|
| 583 |
+
A function to write the xml to its destination.
|
| 584 |
+
elem:
|
| 585 |
+
The element to serialize.
|
| 586 |
+
nsmap_scope:
|
| 587 |
+
The current prefix to uri mapping for this element. This should be
|
| 588 |
+
an empty dictionary for the root element. Additional namespaces are
|
| 589 |
+
progressively added using the new_nsmap arg.
|
| 590 |
+
global_nsmap:
|
| 591 |
+
A dict copy of the globally registered _namespace_map in uri to
|
| 592 |
+
prefix form
|
| 593 |
+
short_empty_elements:
|
| 594 |
+
Controls the formatting of elements that contain no content. If True
|
| 595 |
+
(default) they are emitted as a single self-closed tag, otherwise
|
| 596 |
+
they are emitted as a pair of start/end tags.
|
| 597 |
+
is_html:
|
| 598 |
+
Set to True to serialize as HTML otherwise XML.
|
| 599 |
+
is_root:
|
| 600 |
+
Boolean indicating if this is a root element.
|
| 601 |
+
uri_to_prefix:
|
| 602 |
+
Current state of the mapping of uri to prefix.
|
| 603 |
+
default_ns_attr_prefix:
|
| 604 |
+
new_nsmap:
|
| 605 |
+
New prefix -> uri mapping to be applied to this element.
|
| 606 |
+
"""
|
| 607 |
+
(
|
| 608 |
+
tag,
|
| 609 |
+
nsmap_scope,
|
| 610 |
+
default_ns_attr_prefix,
|
| 611 |
+
uri_to_prefix,
|
| 612 |
+
next_remains_root,
|
| 613 |
+
) = write_elem_start(
|
| 614 |
+
write,
|
| 615 |
+
elem,
|
| 616 |
+
nsmap_scope,
|
| 617 |
+
global_nsmap,
|
| 618 |
+
short_empty_elements,
|
| 619 |
+
is_html,
|
| 620 |
+
is_root,
|
| 621 |
+
uri_to_prefix,
|
| 622 |
+
default_ns_attr_prefix,
|
| 623 |
+
new_nsmap=new_nsmap,
|
| 624 |
+
)
|
| 625 |
+
for e in elem:
|
| 626 |
+
_serialize_ns_xml(
|
| 627 |
+
write,
|
| 628 |
+
e,
|
| 629 |
+
nsmap_scope,
|
| 630 |
+
global_nsmap,
|
| 631 |
+
short_empty_elements,
|
| 632 |
+
is_html,
|
| 633 |
+
next_remains_root,
|
| 634 |
+
uri_to_prefix,
|
| 635 |
+
default_ns_attr_prefix,
|
| 636 |
+
new_nsmap=None,
|
| 637 |
+
)
|
| 638 |
+
if tag:
|
| 639 |
+
write(f"</{tag}>")
|
| 640 |
+
if elem.tail:
|
| 641 |
+
write(ET._escape_cdata(elem.tail))
|
| 642 |
+
|
| 643 |
+
|
| 644 |
+
def _qnames_iter(elem):
|
| 645 |
+
"""Iterate through all the qualified names in elem"""
|
| 646 |
+
seen_el_qnames = set()
|
| 647 |
+
seen_other_qnames = set()
|
| 648 |
+
for this_elem in elem.iter():
|
| 649 |
+
tag = this_elem.tag
|
| 650 |
+
if isinstance(tag, str):
|
| 651 |
+
if tag not in seen_el_qnames:
|
| 652 |
+
seen_el_qnames.add(tag)
|
| 653 |
+
yield tag, True
|
| 654 |
+
elif isinstance(tag, ET.QName):
|
| 655 |
+
tag = tag.text
|
| 656 |
+
if tag not in seen_el_qnames:
|
| 657 |
+
seen_el_qnames.add(tag)
|
| 658 |
+
yield tag, True
|
| 659 |
+
elif (
|
| 660 |
+
tag is not None
|
| 661 |
+
and tag is not ET.ProcessingInstruction
|
| 662 |
+
and tag is not ET.Comment
|
| 663 |
+
):
|
| 664 |
+
ET._raise_serialization_error(tag)
|
| 665 |
+
|
| 666 |
+
for key, value in this_elem.items():
|
| 667 |
+
if isinstance(key, ET.QName):
|
| 668 |
+
key = key.text
|
| 669 |
+
if key not in seen_other_qnames:
|
| 670 |
+
seen_other_qnames.add(key)
|
| 671 |
+
yield key, False
|
| 672 |
+
|
| 673 |
+
if isinstance(value, ET.QName):
|
| 674 |
+
if value.text not in seen_other_qnames:
|
| 675 |
+
seen_other_qnames.add(value.text)
|
| 676 |
+
yield value.text, False
|
| 677 |
+
|
| 678 |
+
text = this_elem.text
|
| 679 |
+
if isinstance(text, ET.QName):
|
| 680 |
+
if text.text not in seen_other_qnames:
|
| 681 |
+
seen_other_qnames.add(text.text)
|
| 682 |
+
yield text.text, False
|
| 683 |
+
|
| 684 |
+
|
| 685 |
+
def _namespaces(
|
| 686 |
+
elem,
|
| 687 |
+
default_namespace=None,
|
| 688 |
+
nsmap=None,
|
| 689 |
+
):
|
| 690 |
+
"""Find all namespaces used in the document and return a prefix to uri map"""
|
| 691 |
+
if nsmap is None:
|
| 692 |
+
nsmap = {}
|
| 693 |
+
|
| 694 |
+
out_nsmap = {}
|
| 695 |
+
|
| 696 |
+
seen_uri_to_prefix = {}
|
| 697 |
+
# Multiple prefixes may be present for a single uri. This will select the
|
| 698 |
+
# last prefix found in nsmap for a given uri.
|
| 699 |
+
local_prefix_map = {uri: prefix for prefix, uri in nsmap.items()}
|
| 700 |
+
if default_namespace is not None:
|
| 701 |
+
local_prefix_map[default_namespace] = ""
|
| 702 |
+
elif "" in nsmap:
|
| 703 |
+
# but we make sure the default prefix always take precedence
|
| 704 |
+
local_prefix_map[nsmap[""]] = ""
|
| 705 |
+
|
| 706 |
+
global_prefixes = set(ET._namespace_map.values())
|
| 707 |
+
has_unqual_el = False
|
| 708 |
+
default_namespace_attr_prefix = None
|
| 709 |
+
for qname, is_el in _qnames_iter(elem):
|
| 710 |
+
try:
|
| 711 |
+
if qname[:1] == "{":
|
| 712 |
+
uri_and_name = qname[1:].rsplit("}", 1)
|
| 713 |
+
|
| 714 |
+
prefix = seen_uri_to_prefix.get(uri_and_name[0])
|
| 715 |
+
if prefix is None:
|
| 716 |
+
prefix = local_prefix_map.get(uri_and_name[0])
|
| 717 |
+
if prefix is None or prefix in out_nsmap:
|
| 718 |
+
prefix = ET._namespace_map.get(uri_and_name[0])
|
| 719 |
+
if prefix is None or prefix in out_nsmap:
|
| 720 |
+
prefix = _make_new_ns_prefix(
|
| 721 |
+
out_nsmap,
|
| 722 |
+
global_prefixes,
|
| 723 |
+
nsmap,
|
| 724 |
+
default_namespace,
|
| 725 |
+
)
|
| 726 |
+
if prefix or is_el:
|
| 727 |
+
out_nsmap[prefix] = uri_and_name[0]
|
| 728 |
+
seen_uri_to_prefix[uri_and_name[0]] = prefix
|
| 729 |
+
|
| 730 |
+
if not is_el and not prefix and not default_namespace_attr_prefix:
|
| 731 |
+
# Find the alternative prefix to use with non-element
|
| 732 |
+
# names
|
| 733 |
+
default_namespace_attr_prefix = _find_default_namespace_attr_prefix(
|
| 734 |
+
uri_and_name[0],
|
| 735 |
+
out_nsmap,
|
| 736 |
+
nsmap,
|
| 737 |
+
global_prefixes,
|
| 738 |
+
default_namespace,
|
| 739 |
+
)
|
| 740 |
+
out_nsmap[default_namespace_attr_prefix] = uri_and_name[0]
|
| 741 |
+
# Don't add this uri to prefix mapping as it might override
|
| 742 |
+
# the uri -> "" default mapping. We'll fix this up at the
|
| 743 |
+
# end of the fn.
|
| 744 |
+
# local_prefix_map[uri_and_name[0]] = default_namespace_attr_prefix
|
| 745 |
+
else:
|
| 746 |
+
if is_el:
|
| 747 |
+
has_unqual_el = True
|
| 748 |
+
except TypeError:
|
| 749 |
+
ET._raise_serialization_error(qname)
|
| 750 |
+
|
| 751 |
+
if "" in out_nsmap and has_unqual_el:
|
| 752 |
+
# FIXME: can this be handled in XML 1.0?
|
| 753 |
+
raise ValueError(
|
| 754 |
+
"cannot use non-qualified names with default_namespace option"
|
| 755 |
+
)
|
| 756 |
+
|
| 757 |
+
# The xml prefix doesn't need to be declared but may have been used to
|
| 758 |
+
# prefix names. Let's remove it if it has been used
|
| 759 |
+
out_nsmap.pop("xml", None)
|
| 760 |
+
return out_nsmap
|
| 761 |
+
|
| 762 |
+
|
| 763 |
+
def tostring(
|
| 764 |
+
element,
|
| 765 |
+
encoding=None,
|
| 766 |
+
method=None,
|
| 767 |
+
*,
|
| 768 |
+
xml_declaration=None,
|
| 769 |
+
default_namespace=None,
|
| 770 |
+
short_empty_elements=True,
|
| 771 |
+
nsmap=None,
|
| 772 |
+
root_ns_only=False,
|
| 773 |
+
minimal_ns_only=False,
|
| 774 |
+
tree_cls=IncrementalTree,
|
| 775 |
+
):
|
| 776 |
+
"""Generate string representation of XML element.
|
| 777 |
+
|
| 778 |
+
All subelements are included. If encoding is "unicode", a string
|
| 779 |
+
is returned. Otherwise a bytestring is returned.
|
| 780 |
+
|
| 781 |
+
*element* is an Element instance, *encoding* is an optional output
|
| 782 |
+
encoding defaulting to US-ASCII, *method* is an optional output which can
|
| 783 |
+
be one of "xml" (default), "html", "text" or "c14n", *default_namespace*
|
| 784 |
+
sets the default XML namespace (for "xmlns").
|
| 785 |
+
|
| 786 |
+
Returns an (optionally) encoded string containing the XML data.
|
| 787 |
+
|
| 788 |
+
"""
|
| 789 |
+
stream = io.StringIO() if encoding == "unicode" else io.BytesIO()
|
| 790 |
+
tree_cls(element).write(
|
| 791 |
+
stream,
|
| 792 |
+
encoding,
|
| 793 |
+
xml_declaration=xml_declaration,
|
| 794 |
+
default_namespace=default_namespace,
|
| 795 |
+
method=method,
|
| 796 |
+
short_empty_elements=short_empty_elements,
|
| 797 |
+
nsmap=nsmap,
|
| 798 |
+
root_ns_only=root_ns_only,
|
| 799 |
+
minimal_ns_only=minimal_ns_only,
|
| 800 |
+
)
|
| 801 |
+
return stream.getvalue()
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
def tostringlist(
|
| 805 |
+
element,
|
| 806 |
+
encoding=None,
|
| 807 |
+
method=None,
|
| 808 |
+
*,
|
| 809 |
+
xml_declaration=None,
|
| 810 |
+
default_namespace=None,
|
| 811 |
+
short_empty_elements=True,
|
| 812 |
+
nsmap=None,
|
| 813 |
+
root_ns_only=False,
|
| 814 |
+
minimal_ns_only=False,
|
| 815 |
+
tree_cls=IncrementalTree,
|
| 816 |
+
):
|
| 817 |
+
lst = []
|
| 818 |
+
stream = ET._ListDataStream(lst)
|
| 819 |
+
tree_cls(element).write(
|
| 820 |
+
stream,
|
| 821 |
+
encoding,
|
| 822 |
+
xml_declaration=xml_declaration,
|
| 823 |
+
default_namespace=default_namespace,
|
| 824 |
+
method=method,
|
| 825 |
+
short_empty_elements=short_empty_elements,
|
| 826 |
+
nsmap=nsmap,
|
| 827 |
+
root_ns_only=root_ns_only,
|
| 828 |
+
minimal_ns_only=minimal_ns_only,
|
| 829 |
+
)
|
| 830 |
+
return lst
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def compat_tostring(
|
| 834 |
+
element,
|
| 835 |
+
encoding=None,
|
| 836 |
+
method=None,
|
| 837 |
+
*,
|
| 838 |
+
xml_declaration=None,
|
| 839 |
+
default_namespace=None,
|
| 840 |
+
short_empty_elements=True,
|
| 841 |
+
nsmap=None,
|
| 842 |
+
root_ns_only=True,
|
| 843 |
+
minimal_ns_only=False,
|
| 844 |
+
tree_cls=IncrementalTree,
|
| 845 |
+
):
|
| 846 |
+
"""tostring with options that produce the same results as xml.etree.ElementTree.tostring
|
| 847 |
+
|
| 848 |
+
root_ns_only=True is a bit slower than False as it needs to traverse the
|
| 849 |
+
tree one more time to collect all the namespaces.
|
| 850 |
+
"""
|
| 851 |
+
return tostring(
|
| 852 |
+
element,
|
| 853 |
+
encoding=encoding,
|
| 854 |
+
method=method,
|
| 855 |
+
xml_declaration=xml_declaration,
|
| 856 |
+
default_namespace=default_namespace,
|
| 857 |
+
short_empty_elements=short_empty_elements,
|
| 858 |
+
nsmap=nsmap,
|
| 859 |
+
root_ns_only=root_ns_only,
|
| 860 |
+
minimal_ns_only=minimal_ns_only,
|
| 861 |
+
tree_cls=tree_cls,
|
| 862 |
+
)
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
# --------------------------------------------------------------------
|
| 866 |
+
# serialization support
|
| 867 |
+
|
| 868 |
+
@contextlib.contextmanager
|
| 869 |
+
def _get_writer(file_or_filename, encoding):
|
| 870 |
+
# Copied from Python 3.12
|
| 871 |
+
# returns text write method and release all resources after using
|
| 872 |
+
try:
|
| 873 |
+
write = file_or_filename.write
|
| 874 |
+
except AttributeError:
|
| 875 |
+
# file_or_filename is a file name
|
| 876 |
+
if encoding.lower() == "unicode":
|
| 877 |
+
encoding = "utf-8"
|
| 878 |
+
with open(file_or_filename, "w", encoding=encoding,
|
| 879 |
+
errors="xmlcharrefreplace") as file:
|
| 880 |
+
yield file.write, encoding
|
| 881 |
+
else:
|
| 882 |
+
# file_or_filename is a file-like object
|
| 883 |
+
# encoding determines if it is a text or binary writer
|
| 884 |
+
if encoding.lower() == "unicode":
|
| 885 |
+
# use a text writer as is
|
| 886 |
+
yield write, getattr(file_or_filename, "encoding", None) or "utf-8"
|
| 887 |
+
else:
|
| 888 |
+
# wrap a binary writer with TextIOWrapper
|
| 889 |
+
with contextlib.ExitStack() as stack:
|
| 890 |
+
if isinstance(file_or_filename, io.BufferedIOBase):
|
| 891 |
+
file = file_or_filename
|
| 892 |
+
elif isinstance(file_or_filename, io.RawIOBase):
|
| 893 |
+
file = io.BufferedWriter(file_or_filename)
|
| 894 |
+
# Keep the original file open when the BufferedWriter is
|
| 895 |
+
# destroyed
|
| 896 |
+
stack.callback(file.detach)
|
| 897 |
+
else:
|
| 898 |
+
# This is to handle passed objects that aren't in the
|
| 899 |
+
# IOBase hierarchy, but just have a write method
|
| 900 |
+
file = io.BufferedIOBase()
|
| 901 |
+
file.writable = lambda: True
|
| 902 |
+
file.write = write
|
| 903 |
+
try:
|
| 904 |
+
# TextIOWrapper uses this methods to determine
|
| 905 |
+
# if BOM (for UTF-16, etc) should be added
|
| 906 |
+
file.seekable = file_or_filename.seekable
|
| 907 |
+
file.tell = file_or_filename.tell
|
| 908 |
+
except AttributeError:
|
| 909 |
+
pass
|
| 910 |
+
file = io.TextIOWrapper(file,
|
| 911 |
+
encoding=encoding,
|
| 912 |
+
errors="xmlcharrefreplace",
|
| 913 |
+
newline="\n")
|
| 914 |
+
# Keep the original file open when the TextIOWrapper is
|
| 915 |
+
# destroyed
|
| 916 |
+
stack.callback(file.detach)
|
| 917 |
+
yield file.write, encoding
|
vllm/lib/python3.10/site-packages/et_xmlfile/xmlfile.py
ADDED
|
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import absolute_import
|
| 2 |
+
# Copyright (c) 2010-2015 openpyxl
|
| 3 |
+
|
| 4 |
+
"""Implements the lxml.etree.xmlfile API using the standard library xml.etree"""
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
from contextlib import contextmanager
|
| 8 |
+
|
| 9 |
+
from xml.etree.ElementTree import (
|
| 10 |
+
Element,
|
| 11 |
+
_escape_cdata,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from . import incremental_tree
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class LxmlSyntaxError(Exception):
|
| 18 |
+
pass
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class _IncrementalFileWriter(object):
|
| 22 |
+
"""Replacement for _IncrementalFileWriter of lxml"""
|
| 23 |
+
def __init__(self, output_file):
|
| 24 |
+
self._element_stack = []
|
| 25 |
+
self._file = output_file
|
| 26 |
+
self._have_root = False
|
| 27 |
+
self.global_nsmap = incremental_tree.current_global_nsmap()
|
| 28 |
+
self.is_html = False
|
| 29 |
+
|
| 30 |
+
@contextmanager
|
| 31 |
+
def element(self, tag, attrib=None, nsmap=None, **_extra):
|
| 32 |
+
"""Create a new xml element using a context manager."""
|
| 33 |
+
if nsmap and None in nsmap:
|
| 34 |
+
# Normalise None prefix (lxml's default namespace prefix) -> "", as
|
| 35 |
+
# required for incremental_tree
|
| 36 |
+
if "" in nsmap and nsmap[""] != nsmap[None]:
|
| 37 |
+
raise ValueError(
|
| 38 |
+
'Found None and "" as default nsmap prefixes with different URIs'
|
| 39 |
+
)
|
| 40 |
+
nsmap = nsmap.copy()
|
| 41 |
+
nsmap[""] = nsmap.pop(None)
|
| 42 |
+
|
| 43 |
+
# __enter__ part
|
| 44 |
+
self._have_root = True
|
| 45 |
+
if attrib is None:
|
| 46 |
+
attrib = {}
|
| 47 |
+
elem = Element(tag, attrib=attrib, **_extra)
|
| 48 |
+
elem.text = ''
|
| 49 |
+
elem.tail = ''
|
| 50 |
+
if self._element_stack:
|
| 51 |
+
is_root = False
|
| 52 |
+
(
|
| 53 |
+
nsmap_scope,
|
| 54 |
+
default_ns_attr_prefix,
|
| 55 |
+
uri_to_prefix,
|
| 56 |
+
) = self._element_stack[-1]
|
| 57 |
+
else:
|
| 58 |
+
is_root = True
|
| 59 |
+
nsmap_scope = {}
|
| 60 |
+
default_ns_attr_prefix = None
|
| 61 |
+
uri_to_prefix = {}
|
| 62 |
+
(
|
| 63 |
+
tag,
|
| 64 |
+
nsmap_scope,
|
| 65 |
+
default_ns_attr_prefix,
|
| 66 |
+
uri_to_prefix,
|
| 67 |
+
next_remains_root,
|
| 68 |
+
) = incremental_tree.write_elem_start(
|
| 69 |
+
self._file,
|
| 70 |
+
elem,
|
| 71 |
+
nsmap_scope=nsmap_scope,
|
| 72 |
+
global_nsmap=self.global_nsmap,
|
| 73 |
+
short_empty_elements=False,
|
| 74 |
+
is_html=self.is_html,
|
| 75 |
+
is_root=is_root,
|
| 76 |
+
uri_to_prefix=uri_to_prefix,
|
| 77 |
+
default_ns_attr_prefix=default_ns_attr_prefix,
|
| 78 |
+
new_nsmap=nsmap,
|
| 79 |
+
)
|
| 80 |
+
self._element_stack.append(
|
| 81 |
+
(
|
| 82 |
+
nsmap_scope,
|
| 83 |
+
default_ns_attr_prefix,
|
| 84 |
+
uri_to_prefix,
|
| 85 |
+
)
|
| 86 |
+
)
|
| 87 |
+
yield
|
| 88 |
+
|
| 89 |
+
# __exit__ part
|
| 90 |
+
self._element_stack.pop()
|
| 91 |
+
self._file(f"</{tag}>")
|
| 92 |
+
if elem.tail:
|
| 93 |
+
self._file(_escape_cdata(elem.tail))
|
| 94 |
+
|
| 95 |
+
def write(self, arg):
|
| 96 |
+
"""Write a string or subelement."""
|
| 97 |
+
|
| 98 |
+
if isinstance(arg, str):
|
| 99 |
+
# it is not allowed to write a string outside of an element
|
| 100 |
+
if not self._element_stack:
|
| 101 |
+
raise LxmlSyntaxError()
|
| 102 |
+
self._file(_escape_cdata(arg))
|
| 103 |
+
|
| 104 |
+
else:
|
| 105 |
+
if not self._element_stack and self._have_root:
|
| 106 |
+
raise LxmlSyntaxError()
|
| 107 |
+
|
| 108 |
+
if self._element_stack:
|
| 109 |
+
is_root = False
|
| 110 |
+
(
|
| 111 |
+
nsmap_scope,
|
| 112 |
+
default_ns_attr_prefix,
|
| 113 |
+
uri_to_prefix,
|
| 114 |
+
) = self._element_stack[-1]
|
| 115 |
+
else:
|
| 116 |
+
is_root = True
|
| 117 |
+
nsmap_scope = {}
|
| 118 |
+
default_ns_attr_prefix = None
|
| 119 |
+
uri_to_prefix = {}
|
| 120 |
+
incremental_tree._serialize_ns_xml(
|
| 121 |
+
self._file,
|
| 122 |
+
arg,
|
| 123 |
+
nsmap_scope=nsmap_scope,
|
| 124 |
+
global_nsmap=self.global_nsmap,
|
| 125 |
+
short_empty_elements=True,
|
| 126 |
+
is_html=self.is_html,
|
| 127 |
+
is_root=is_root,
|
| 128 |
+
uri_to_prefix=uri_to_prefix,
|
| 129 |
+
default_ns_attr_prefix=default_ns_attr_prefix,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
def __enter__(self):
|
| 133 |
+
pass
|
| 134 |
+
|
| 135 |
+
def __exit__(self, type, value, traceback):
|
| 136 |
+
# without root the xml document is incomplete
|
| 137 |
+
if not self._have_root:
|
| 138 |
+
raise LxmlSyntaxError()
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
class xmlfile(object):
|
| 142 |
+
"""Context manager that can replace lxml.etree.xmlfile."""
|
| 143 |
+
def __init__(self, output_file, buffered=False, encoding="utf-8", close=False):
|
| 144 |
+
self._file = output_file
|
| 145 |
+
self._close = close
|
| 146 |
+
self.encoding = encoding
|
| 147 |
+
self.writer_cm = None
|
| 148 |
+
|
| 149 |
+
def __enter__(self):
|
| 150 |
+
self.writer_cm = incremental_tree._get_writer(self._file, encoding=self.encoding)
|
| 151 |
+
writer, declared_encoding = self.writer_cm.__enter__()
|
| 152 |
+
return _IncrementalFileWriter(writer)
|
| 153 |
+
|
| 154 |
+
def __exit__(self, type, value, traceback):
|
| 155 |
+
if self.writer_cm:
|
| 156 |
+
self.writer_cm.__exit__(type, value, traceback)
|
| 157 |
+
if self._close:
|
| 158 |
+
self._file.close()
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2017 scoder
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/METADATA
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Metadata-Version: 2.1
|
| 2 |
+
Name: fastrlock
|
| 3 |
+
Version: 0.8.3
|
| 4 |
+
Summary: Fast, re-entrant optimistic lock implemented in Cython
|
| 5 |
+
Home-page: https://github.com/scoder/fastrlock
|
| 6 |
+
Author: Stefan Behnel
|
| 7 |
+
Author-email: stefan_ml@behnel.de
|
| 8 |
+
License: MIT style
|
| 9 |
+
Classifier: Development Status :: 5 - Production/Stable
|
| 10 |
+
Classifier: Intended Audience :: Developers
|
| 11 |
+
Classifier: Intended Audience :: Information Technology
|
| 12 |
+
Classifier: License :: OSI Approved :: MIT License
|
| 13 |
+
Classifier: Programming Language :: Cython
|
| 14 |
+
Classifier: Programming Language :: Python :: 3
|
| 15 |
+
Classifier: Operating System :: OS Independent
|
| 16 |
+
Classifier: Topic :: Software Development
|
| 17 |
+
License-File: LICENSE
|
| 18 |
+
|
| 19 |
+
FastRLock
|
| 20 |
+
---------
|
| 21 |
+
|
| 22 |
+
This is a C-level implementation of a fast, re-entrant, optimistic lock for CPython.
|
| 23 |
+
It is a drop-in replacement for
|
| 24 |
+
`threading.RLock <https://docs.python.org/3/library/threading.html#threading.RLock>`_.
|
| 25 |
+
FastRLock is implemented in `Cython <https://cython.org>`_ and also provides a C-API
|
| 26 |
+
for direct use from Cython code via ``from fastrlock cimport rlock`` or
|
| 27 |
+
``from cython.cimports.fastrlock import rlock``.
|
| 28 |
+
|
| 29 |
+
Under normal conditions, it is about 10x faster than ``threading.RLock`` in Python 2.7
|
| 30 |
+
because it avoids all locking unless two or more threads try to acquire it at the
|
| 31 |
+
same time. Under congestion, it is still about 10% faster than RLock due to being
|
| 32 |
+
implemented in Cython.
|
| 33 |
+
|
| 34 |
+
This is mostly equivalent to the revised RLock implementation in Python 3.2,
|
| 35 |
+
but still faster due to being implemented in Cython. However, in Python 3.4 and
|
| 36 |
+
later, the ``threading.RLock`` implementation in the stdlib tends to be as fast
|
| 37 |
+
or even faster than the lock provided by this package, when called through the
|
| 38 |
+
Python API. ``FastRLock`` is still faster also on these systems when called
|
| 39 |
+
through its Cython API from other Cython modules.
|
| 40 |
+
|
| 41 |
+
It was initially published as a code recipe here:
|
| 42 |
+
https://code.activestate.com/recipes/577336-fast-re-entrant-optimistic-lock-implemented-in-cyt/
|
| 43 |
+
|
| 44 |
+
FastRLock has been used and tested in `Lupa <https://github.com/scoder/lupa>`_ for several years.
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
How does it work?
|
| 48 |
+
-----------------
|
| 49 |
+
|
| 50 |
+
The FastRLock implementation optimises for the non-congested case. It works by
|
| 51 |
+
exploiting the availability of the GIL. Since it knows that it holds the GIL when
|
| 52 |
+
the acquire()/release() methods are called, it can safely check the lock for being
|
| 53 |
+
held by other threads and just count any re-entries as long as it is always the
|
| 54 |
+
same thread that acquires it. This is a lot faster than actually acquiring the
|
| 55 |
+
underlying lock.
|
| 56 |
+
|
| 57 |
+
When a second thread wants to acquire the lock as well, it first checks the lock
|
| 58 |
+
count and finds out that the lock is already owned. If the underlying lock is also
|
| 59 |
+
held by another thread already, it then just frees the GIL and asks for acquiring
|
| 60 |
+
the lock, just like RLock does. If the underlying lock is not held, however, it
|
| 61 |
+
acquires it immediately and basically hands over the ownership by telling the
|
| 62 |
+
current owner to free it when it's done. Then, it falls back to the normal
|
| 63 |
+
non-owner behaviour that asks for the lock and will eventually acquire it when it
|
| 64 |
+
gets released. This makes sure that the real lock is only acquired when at least
|
| 65 |
+
two threads want it.
|
| 66 |
+
|
| 67 |
+
All of these operations are basically atomic because any thread that modifies the
|
| 68 |
+
lock state always holds the GIL. Note that the implementation must not call any
|
| 69 |
+
Python code while handling the lock, as calling into Python may lead to a context
|
| 70 |
+
switch which hands over the GIL to another thread and thus breaks atomicity.
|
| 71 |
+
Therefore, the code misuses Cython's 'nogil' annotation to make sure that no Python
|
| 72 |
+
code slips in accidentally.
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
How fast is it?
|
| 76 |
+
---------------
|
| 77 |
+
|
| 78 |
+
Here are some timings for the following scenarios:
|
| 79 |
+
|
| 80 |
+
1) five acquire-release cycles ('lock_unlock')
|
| 81 |
+
2) five acquire calls followed by five release calls (nested locking, 'reentrant_lock_unlock')
|
| 82 |
+
3) a mixed and partly nested sequence of acquire and release calls ('mixed_lock_unlock')
|
| 83 |
+
4) five acquire-release cycles that do not block ('lock_unlock_nonblocking')
|
| 84 |
+
|
| 85 |
+
All four are benchmarked for the single threaded case and the multi threaded case
|
| 86 |
+
with 10 threads. I also tested it with 20 threads only to see that it then takes
|
| 87 |
+
about twice the time for both versions. Note also that the congested case is
|
| 88 |
+
substantially slower for both locks and the benchmark includes the thread
|
| 89 |
+
creation time, so I only looped 1000x here to get useful
|
| 90 |
+
timings instead of 100000x for the single threaded case.
|
| 91 |
+
|
| 92 |
+
The results here are mixed. Depending on the optimisation of the CPython
|
| 93 |
+
installation, it can be faster, about the same speed, or somewhat slower.
|
| 94 |
+
In any case, the direct Cython interface is always faster than going through
|
| 95 |
+
the Python API, because it avoids the Python call overhead and executes
|
| 96 |
+
a C call instead.
|
| 97 |
+
|
| 98 |
+
::
|
| 99 |
+
|
| 100 |
+
Testing RLock (3.10.1)
|
| 101 |
+
|
| 102 |
+
sequential (x100000):
|
| 103 |
+
lock_unlock : 138.36 msec
|
| 104 |
+
reentrant_lock_unlock : 95.35 msec
|
| 105 |
+
mixed_lock_unlock : 102.05 msec
|
| 106 |
+
lock_unlock_nonblocking : 131.44 msec
|
| 107 |
+
context_manager : 616.83 msec
|
| 108 |
+
|
| 109 |
+
threaded 10T (x1000):
|
| 110 |
+
lock_unlock : 1386.60 msec
|
| 111 |
+
reentrant_lock_unlock : 1207.75 msec
|
| 112 |
+
mixed_lock_unlock : 1319.62 msec
|
| 113 |
+
lock_unlock_nonblocking : 1325.07 msec
|
| 114 |
+
context_manager : 1357.93 msec
|
| 115 |
+
|
| 116 |
+
Testing FastRLock (0.8.1)
|
| 117 |
+
|
| 118 |
+
sequential (x100000):
|
| 119 |
+
lock_unlock : 77.47 msec
|
| 120 |
+
reentrant_lock_unlock : 64.14 msec
|
| 121 |
+
mixed_lock_unlock : 73.51 msec
|
| 122 |
+
lock_unlock_nonblocking : 70.31 msec
|
| 123 |
+
context_manager : 393.34 msec
|
| 124 |
+
|
| 125 |
+
threaded 10T (x1000):
|
| 126 |
+
lock_unlock : 1214.13 msec
|
| 127 |
+
reentrant_lock_unlock : 1171.75 msec
|
| 128 |
+
mixed_lock_unlock : 1184.33 msec
|
| 129 |
+
lock_unlock_nonblocking : 1207.42 msec
|
| 130 |
+
context_manager : 1232.20 msec
|
| 131 |
+
|
| 132 |
+
Testing Cython interface of FastRLock (0.8.1)
|
| 133 |
+
|
| 134 |
+
sequential (x100000):
|
| 135 |
+
lock_unlock : 18.70 msec
|
| 136 |
+
reentrant_lock_unlock : 15.88 msec
|
| 137 |
+
mixed_lock_unlock : 14.96 msec
|
| 138 |
+
lock_unlock_nonblocking : 13.47 msec
|
| 139 |
+
|
| 140 |
+
threaded 10T (x1000):
|
| 141 |
+
lock_unlock : 1236.21 msec
|
| 142 |
+
reentrant_lock_unlock : 1245.77 msec
|
| 143 |
+
mixed_lock_unlock : 1194.25 msec
|
| 144 |
+
lock_unlock_nonblocking : 1206.96 msec
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
===================
|
| 148 |
+
fastrlock changelog
|
| 149 |
+
===================
|
| 150 |
+
|
| 151 |
+
0.8.3 (2024-12-17)
|
| 152 |
+
==================
|
| 153 |
+
|
| 154 |
+
* Rebuilt with Cython 3.0.11 to add Python 3.13 support.
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
0.8.2 (2023-08-27)
|
| 158 |
+
==================
|
| 159 |
+
|
| 160 |
+
* Rebuilt with Cython 3.0.2 to add Python 3.12 support.
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
0.8.1 (2022-11-02)
|
| 164 |
+
==================
|
| 165 |
+
|
| 166 |
+
* Rebuilt with Cython 3.0.0a11 to add Python 3.11 support.
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
0.8 (2021-10-22)
|
| 170 |
+
================
|
| 171 |
+
|
| 172 |
+
* Rebuilt with Cython 3.0.0a9 to improve the performance in recent
|
| 173 |
+
Python 3.x versions.
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
0.7 (2021-10-21)
|
| 177 |
+
================
|
| 178 |
+
|
| 179 |
+
* Adapted for unsigned thread IDs, as used by Py3.7+.
|
| 180 |
+
(original patch by Guilherme Dantas)
|
| 181 |
+
|
| 182 |
+
* Build with Cython 0.29.24 to support Py3.10 and later.
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
0.6 (2021-03-21)
|
| 186 |
+
================
|
| 187 |
+
|
| 188 |
+
* Rebuild with Cython 0.29.22 to support Py3.9 and later.
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
0.5 (2020-06-05)
|
| 192 |
+
================
|
| 193 |
+
|
| 194 |
+
* Rebuild with Cython 0.29.20 to support Py3.8 and later.
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
0.4 (2018-08-24)
|
| 198 |
+
================
|
| 199 |
+
|
| 200 |
+
* Rebuild with Cython 0.28.5.
|
| 201 |
+
|
| 202 |
+
* Linux wheels are faster through profile guided optimisation.
|
| 203 |
+
|
| 204 |
+
* Add missing file to sdist.
|
| 205 |
+
(patch by Mark Harfouche, Github issue #5)
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
0.3 (2017-08-10)
|
| 209 |
+
================
|
| 210 |
+
|
| 211 |
+
* improve cimport support of C-API
|
| 212 |
+
(patch by Naotoshi Seo, Github issue #3)
|
| 213 |
+
|
| 214 |
+
* provide ``fastrlock.__version__``
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
0.2 (2017-08-09)
|
| 218 |
+
================
|
| 219 |
+
|
| 220 |
+
* add missing readme file to sdist
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
0.1 (2017-06-04)
|
| 224 |
+
================
|
| 225 |
+
|
| 226 |
+
* initial release
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/RECORD
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastrlock-0.8.3.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
|
| 2 |
+
fastrlock-0.8.3.dist-info/LICENSE,sha256=edWWCQqdGaUaEXXL0SQGCy8j1Pa-vqeYIkHSMRdRljA,1063
|
| 3 |
+
fastrlock-0.8.3.dist-info/METADATA,sha256=CSkdXG1Tg_Nn1ar1AXfaqMPqOzGI3Er9xl1ed3brFQo,7664
|
| 4 |
+
fastrlock-0.8.3.dist-info/RECORD,,
|
| 5 |
+
fastrlock-0.8.3.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 6 |
+
fastrlock-0.8.3.dist-info/WHEEL,sha256=Rk4grMJLqb8wSCjEpvXBqchuGLCY2i_LHup4dkE_8Eo,186
|
| 7 |
+
fastrlock-0.8.3.dist-info/top_level.txt,sha256=QMLNNCjoisR1NTxtzPxl2Zyih9n6sFxd8VCUQzIJHOA,10
|
| 8 |
+
fastrlock/__init__.pxd,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
| 9 |
+
fastrlock/__init__.py,sha256=lYDBBV0R1dtMBmWKorNXKhEma8Fo0OswJJW6zCSGmtU,169
|
| 10 |
+
fastrlock/__pycache__/__init__.cpython-310.pyc,,
|
| 11 |
+
fastrlock/_lock.pxi,sha256=tPIg2qyMZbCZDEXQsp_tb_Em2J0podo3iU3-XEBdnTQ,2608
|
| 12 |
+
fastrlock/rlock.cpython-310-x86_64-linux-gnu.so,sha256=r9XOGqP28vc9-BbAWmWQwb8S04o9hVHuJ9LIgRdymvA,120120
|
| 13 |
+
fastrlock/rlock.pxd,sha256=slrtTC9yStpzsL9FUgoyU69D_YsJAe036GEfH6Z9a0c,313
|
| 14 |
+
fastrlock/rlock.pyx,sha256=YZfaVup-Tkqb42IcNlunf4Vtt2vXVQfZPG4l9BmQlAY,3599
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/REQUESTED
ADDED
|
File without changes
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/WHEEL
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Wheel-Version: 1.0
|
| 2 |
+
Generator: setuptools (75.6.0)
|
| 3 |
+
Root-Is-Purelib: false
|
| 4 |
+
Tag: cp310-cp310-manylinux_2_5_x86_64
|
| 5 |
+
Tag: cp310-cp310-manylinux1_x86_64
|
| 6 |
+
Tag: cp310-cp310-manylinux_2_28_x86_64
|
| 7 |
+
|
vllm/lib/python3.10/site-packages/fastrlock-0.8.3.dist-info/top_level.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
fastrlock
|
vllm/lib/python3.10/site-packages/llvmlite/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (241 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/__pycache__/_version.cpython-310.pyc
ADDED
|
Binary file (405 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/__pycache__/utils.cpython-310.pyc
ADDED
|
Binary file (785 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
This subpackage implements the LLVM IR classes in pure python
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from .types import *
|
| 6 |
+
from .values import *
|
| 7 |
+
from .module import *
|
| 8 |
+
from .builder import *
|
| 9 |
+
from .instructions import *
|
| 10 |
+
from .transforms import *
|
| 11 |
+
from .context import Context, global_context
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (428 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/_utils.cpython-310.pyc
ADDED
|
Binary file (3.23 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/builder.cpython-310.pyc
ADDED
|
Binary file (34.5 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/context.cpython-310.pyc
ADDED
|
Binary file (859 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/instructions.cpython-310.pyc
ADDED
|
Binary file (32.8 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/module.cpython-310.pyc
ADDED
|
Binary file (8.39 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/transforms.cpython-310.pyc
ADDED
|
Binary file (2.72 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/types.cpython-310.pyc
ADDED
|
Binary file (21.9 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/__pycache__/values.cpython-310.pyc
ADDED
|
Binary file (38.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/ir/_utils.py
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections import defaultdict
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class DuplicatedNameError(NameError):
|
| 5 |
+
pass
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class NameScope(object):
|
| 9 |
+
def __init__(self):
|
| 10 |
+
self._useset = set([''])
|
| 11 |
+
self._basenamemap = defaultdict(int)
|
| 12 |
+
|
| 13 |
+
def is_used(self, name):
|
| 14 |
+
return name in self._useset
|
| 15 |
+
|
| 16 |
+
def register(self, name, deduplicate=False):
|
| 17 |
+
if deduplicate:
|
| 18 |
+
name = self.deduplicate(name)
|
| 19 |
+
elif self.is_used(name):
|
| 20 |
+
raise DuplicatedNameError(name)
|
| 21 |
+
self._useset.add(name)
|
| 22 |
+
return name
|
| 23 |
+
|
| 24 |
+
def deduplicate(self, name):
|
| 25 |
+
basename = name
|
| 26 |
+
while self.is_used(name):
|
| 27 |
+
ident = self._basenamemap[basename] + 1
|
| 28 |
+
self._basenamemap[basename] = ident
|
| 29 |
+
name = "{0}.{1}".format(basename, ident)
|
| 30 |
+
return name
|
| 31 |
+
|
| 32 |
+
def get_child(self):
|
| 33 |
+
return type(self)(parent=self)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class _StrCaching(object):
|
| 37 |
+
|
| 38 |
+
def _clear_string_cache(self):
|
| 39 |
+
try:
|
| 40 |
+
del self.__cached_str
|
| 41 |
+
except AttributeError:
|
| 42 |
+
pass
|
| 43 |
+
|
| 44 |
+
def __str__(self):
|
| 45 |
+
try:
|
| 46 |
+
return self.__cached_str
|
| 47 |
+
except AttributeError:
|
| 48 |
+
s = self.__cached_str = self._to_string()
|
| 49 |
+
return s
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
class _StringReferenceCaching(object):
|
| 53 |
+
|
| 54 |
+
def get_reference(self):
|
| 55 |
+
try:
|
| 56 |
+
return self.__cached_refstr
|
| 57 |
+
except AttributeError:
|
| 58 |
+
s = self.__cached_refstr = self._get_reference()
|
| 59 |
+
return s
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class _HasMetadata(object):
|
| 63 |
+
|
| 64 |
+
def set_metadata(self, name, node):
|
| 65 |
+
"""
|
| 66 |
+
Attach unnamed metadata *node* to the metadata slot *name* of this
|
| 67 |
+
value.
|
| 68 |
+
"""
|
| 69 |
+
self.metadata[name] = node
|
| 70 |
+
|
| 71 |
+
def _stringify_metadata(self, leading_comma=False):
|
| 72 |
+
if self.metadata:
|
| 73 |
+
buf = []
|
| 74 |
+
if leading_comma:
|
| 75 |
+
buf.append("")
|
| 76 |
+
buf += ["!{0} {1}".format(k, v.get_reference())
|
| 77 |
+
for k, v in self.metadata.items()]
|
| 78 |
+
return ', '.join(buf)
|
| 79 |
+
else:
|
| 80 |
+
return ''
|
vllm/lib/python3.10/site-packages/llvmlite/ir/builder.py
ADDED
|
@@ -0,0 +1,1119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ite.ir import instructions, types, values
|
| 5 |
+
|
| 6 |
+
_CMP_MAP = {
|
| 7 |
+
'>': 'gt',
|
| 8 |
+
'<': 'lt',
|
| 9 |
+
'==': 'eq',
|
| 10 |
+
'!=': 'ne',
|
| 11 |
+
'>=': 'ge',
|
| 12 |
+
'<=': 'le',
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _unop(opname, cls=instructions.Instruction):
|
| 17 |
+
def wrap(fn):
|
| 18 |
+
@functools.wraps(fn)
|
| 19 |
+
def wrapped(self, arg, name='', flags=()):
|
| 20 |
+
instr = cls(self.block, arg.type, opname, [arg], name, flags)
|
| 21 |
+
self._insert(instr)
|
| 22 |
+
return instr
|
| 23 |
+
|
| 24 |
+
return wrapped
|
| 25 |
+
|
| 26 |
+
return wrap
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _binop(opname, cls=instructions.Instruction):
|
| 30 |
+
def wrap(fn):
|
| 31 |
+
@functools.wraps(fn)
|
| 32 |
+
def wrapped(self, lhs, rhs, name='', flags=()):
|
| 33 |
+
if lhs.type != rhs.type:
|
| 34 |
+
raise ValueError("Operands must be the same type, got (%s, %s)"
|
| 35 |
+
% (lhs.type, rhs.type))
|
| 36 |
+
instr = cls(self.block, lhs.type, opname, (lhs, rhs), name, flags)
|
| 37 |
+
self._insert(instr)
|
| 38 |
+
return instr
|
| 39 |
+
|
| 40 |
+
return wrapped
|
| 41 |
+
|
| 42 |
+
return wrap
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _binop_with_overflow(opname, cls=instructions.Instruction):
|
| 46 |
+
def wrap(fn):
|
| 47 |
+
@functools.wraps(fn)
|
| 48 |
+
def wrapped(self, lhs, rhs, name=''):
|
| 49 |
+
if lhs.type != rhs.type:
|
| 50 |
+
raise ValueError("Operands must be the same type, got (%s, %s)"
|
| 51 |
+
% (lhs.type, rhs.type))
|
| 52 |
+
ty = lhs.type
|
| 53 |
+
if not isinstance(ty, types.IntType):
|
| 54 |
+
raise TypeError("expected an integer type, got %s" % (ty,))
|
| 55 |
+
bool_ty = types.IntType(1)
|
| 56 |
+
|
| 57 |
+
mod = self.module
|
| 58 |
+
fnty = types.FunctionType(types.LiteralStructType([ty, bool_ty]),
|
| 59 |
+
[ty, ty])
|
| 60 |
+
fn = mod.declare_intrinsic("llvm.%s.with.overflow" % (opname,),
|
| 61 |
+
[ty], fnty)
|
| 62 |
+
ret = self.call(fn, [lhs, rhs], name=name)
|
| 63 |
+
return ret
|
| 64 |
+
|
| 65 |
+
return wrapped
|
| 66 |
+
|
| 67 |
+
return wrap
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _uniop(opname, cls=instructions.Instruction):
|
| 71 |
+
def wrap(fn):
|
| 72 |
+
@functools.wraps(fn)
|
| 73 |
+
def wrapped(self, operand, name=''):
|
| 74 |
+
instr = cls(self.block, operand.type, opname, [operand], name)
|
| 75 |
+
self._insert(instr)
|
| 76 |
+
return instr
|
| 77 |
+
|
| 78 |
+
return wrapped
|
| 79 |
+
|
| 80 |
+
return wrap
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def _uniop_intrinsic_int(opname):
|
| 84 |
+
def wrap(fn):
|
| 85 |
+
@functools.wraps(fn)
|
| 86 |
+
def wrapped(self, operand, name=''):
|
| 87 |
+
if not isinstance(operand.type, types.IntType):
|
| 88 |
+
raise TypeError(
|
| 89 |
+
"expected an integer type, got %s" %
|
| 90 |
+
operand.type)
|
| 91 |
+
fn = self.module.declare_intrinsic(opname, [operand.type])
|
| 92 |
+
return self.call(fn, [operand], name)
|
| 93 |
+
|
| 94 |
+
return wrapped
|
| 95 |
+
|
| 96 |
+
return wrap
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def _uniop_intrinsic_float(opname):
|
| 100 |
+
def wrap(fn):
|
| 101 |
+
@functools.wraps(fn)
|
| 102 |
+
def wrapped(self, operand, name=''):
|
| 103 |
+
if not isinstance(
|
| 104 |
+
operand.type, (types.FloatType, types.DoubleType)):
|
| 105 |
+
raise TypeError("expected a float type, got %s" % operand.type)
|
| 106 |
+
fn = self.module.declare_intrinsic(opname, [operand.type])
|
| 107 |
+
return self.call(fn, [operand], name)
|
| 108 |
+
|
| 109 |
+
return wrapped
|
| 110 |
+
|
| 111 |
+
return wrap
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _uniop_intrinsic_with_flag(opname):
|
| 115 |
+
def wrap(fn):
|
| 116 |
+
@functools.wraps(fn)
|
| 117 |
+
def wrapped(self, operand, flag, name=''):
|
| 118 |
+
if not isinstance(operand.type, types.IntType):
|
| 119 |
+
raise TypeError(
|
| 120 |
+
"expected an integer type, got %s" %
|
| 121 |
+
operand.type)
|
| 122 |
+
if not (isinstance(flag.type, types.IntType) and
|
| 123 |
+
flag.type.width == 1):
|
| 124 |
+
raise TypeError("expected an i1 type, got %s" % flag.type)
|
| 125 |
+
fn = self.module.declare_intrinsic(
|
| 126 |
+
opname, [operand.type, flag.type])
|
| 127 |
+
return self.call(fn, [operand, flag], name)
|
| 128 |
+
|
| 129 |
+
return wrapped
|
| 130 |
+
|
| 131 |
+
return wrap
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _triop_intrinsic(opname):
|
| 135 |
+
def wrap(fn):
|
| 136 |
+
@functools.wraps(fn)
|
| 137 |
+
def wrapped(self, a, b, c, name=''):
|
| 138 |
+
if a.type != b.type or b.type != c.type:
|
| 139 |
+
raise TypeError(
|
| 140 |
+
"expected types to be the same, got %s, %s, %s" % (
|
| 141 |
+
a.type,
|
| 142 |
+
b.type,
|
| 143 |
+
c.type))
|
| 144 |
+
elif not isinstance(
|
| 145 |
+
a.type,
|
| 146 |
+
(types.HalfType, types.FloatType, types.DoubleType)):
|
| 147 |
+
raise TypeError(
|
| 148 |
+
"expected an floating point type, got %s" %
|
| 149 |
+
a.type)
|
| 150 |
+
fn = self.module.declare_intrinsic(opname, [a.type, b.type, c.type])
|
| 151 |
+
return self.call(fn, [a, b, c], name)
|
| 152 |
+
|
| 153 |
+
return wrapped
|
| 154 |
+
|
| 155 |
+
return wrap
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _castop(opname, cls=instructions.CastInstr):
|
| 159 |
+
def wrap(fn):
|
| 160 |
+
@functools.wraps(fn)
|
| 161 |
+
def wrapped(self, val, typ, name=''):
|
| 162 |
+
if val.type == typ:
|
| 163 |
+
return val
|
| 164 |
+
instr = cls(self.block, opname, val, typ, name)
|
| 165 |
+
self._insert(instr)
|
| 166 |
+
return instr
|
| 167 |
+
|
| 168 |
+
return wrapped
|
| 169 |
+
|
| 170 |
+
return wrap
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _label_suffix(label, suffix):
|
| 174 |
+
"""Returns (label + suffix) or a truncated version if it's too long.
|
| 175 |
+
Parameters
|
| 176 |
+
----------
|
| 177 |
+
label : str
|
| 178 |
+
Label name
|
| 179 |
+
suffix : str
|
| 180 |
+
Label suffix
|
| 181 |
+
"""
|
| 182 |
+
if len(label) > 50:
|
| 183 |
+
nhead = 25
|
| 184 |
+
return ''.join([label[:nhead], '..', suffix])
|
| 185 |
+
else:
|
| 186 |
+
return label + suffix
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class IRBuilder(object):
|
| 190 |
+
def __init__(self, block=None):
|
| 191 |
+
self._block = block
|
| 192 |
+
self._anchor = len(block.instructions) if block else 0
|
| 193 |
+
self.debug_metadata = None
|
| 194 |
+
|
| 195 |
+
@property
|
| 196 |
+
def block(self):
|
| 197 |
+
"""
|
| 198 |
+
The current basic block.
|
| 199 |
+
"""
|
| 200 |
+
return self._block
|
| 201 |
+
|
| 202 |
+
basic_block = block
|
| 203 |
+
|
| 204 |
+
@property
|
| 205 |
+
def function(self):
|
| 206 |
+
"""
|
| 207 |
+
The current function.
|
| 208 |
+
"""
|
| 209 |
+
return self.block.parent
|
| 210 |
+
|
| 211 |
+
@property
|
| 212 |
+
def module(self):
|
| 213 |
+
"""
|
| 214 |
+
The current module.
|
| 215 |
+
"""
|
| 216 |
+
return self.block.parent.module
|
| 217 |
+
|
| 218 |
+
def position_before(self, instr):
|
| 219 |
+
"""
|
| 220 |
+
Position immediately before the given instruction. The current block
|
| 221 |
+
is also changed to the instruction's basic block.
|
| 222 |
+
"""
|
| 223 |
+
self._block = instr.parent
|
| 224 |
+
self._anchor = self._block.instructions.index(instr)
|
| 225 |
+
|
| 226 |
+
def position_after(self, instr):
|
| 227 |
+
"""
|
| 228 |
+
Position immediately after the given instruction. The current block
|
| 229 |
+
is also changed to the instruction's basic block.
|
| 230 |
+
"""
|
| 231 |
+
self._block = instr.parent
|
| 232 |
+
self._anchor = self._block.instructions.index(instr) + 1
|
| 233 |
+
|
| 234 |
+
def position_at_start(self, block):
|
| 235 |
+
"""
|
| 236 |
+
Position at the start of the basic *block*.
|
| 237 |
+
"""
|
| 238 |
+
self._block = block
|
| 239 |
+
self._anchor = 0
|
| 240 |
+
|
| 241 |
+
def position_at_end(self, block):
|
| 242 |
+
"""
|
| 243 |
+
Position at the end of the basic *block*.
|
| 244 |
+
"""
|
| 245 |
+
self._block = block
|
| 246 |
+
self._anchor = len(block.instructions)
|
| 247 |
+
|
| 248 |
+
def append_basic_block(self, name=''):
|
| 249 |
+
"""
|
| 250 |
+
Append a basic block, with the given optional *name*, to the current
|
| 251 |
+
function. The current block is not changed. The new block is returned.
|
| 252 |
+
"""
|
| 253 |
+
return self.function.append_basic_block(name)
|
| 254 |
+
|
| 255 |
+
def remove(self, instr):
|
| 256 |
+
"""Remove the given instruction."""
|
| 257 |
+
idx = self._block.instructions.index(instr)
|
| 258 |
+
del self._block.instructions[idx]
|
| 259 |
+
if self._block.terminator == instr:
|
| 260 |
+
self._block.terminator = None
|
| 261 |
+
if self._anchor > idx:
|
| 262 |
+
self._anchor -= 1
|
| 263 |
+
|
| 264 |
+
@contextlib.contextmanager
|
| 265 |
+
def goto_block(self, block):
|
| 266 |
+
"""
|
| 267 |
+
A context manager which temporarily positions the builder at the end
|
| 268 |
+
of basic block *bb* (but before any terminator).
|
| 269 |
+
"""
|
| 270 |
+
old_block = self.basic_block
|
| 271 |
+
term = block.terminator
|
| 272 |
+
if term is not None:
|
| 273 |
+
self.position_before(term)
|
| 274 |
+
else:
|
| 275 |
+
self.position_at_end(block)
|
| 276 |
+
try:
|
| 277 |
+
yield
|
| 278 |
+
finally:
|
| 279 |
+
self.position_at_end(old_block)
|
| 280 |
+
|
| 281 |
+
@contextlib.contextmanager
|
| 282 |
+
def goto_entry_block(self):
|
| 283 |
+
"""
|
| 284 |
+
A context manager which temporarily positions the builder at the
|
| 285 |
+
end of the function's entry block.
|
| 286 |
+
"""
|
| 287 |
+
with self.goto_block(self.function.entry_basic_block):
|
| 288 |
+
yield
|
| 289 |
+
|
| 290 |
+
@contextlib.contextmanager
|
| 291 |
+
def _branch_helper(self, bbenter, bbexit):
|
| 292 |
+
self.position_at_end(bbenter)
|
| 293 |
+
yield bbexit
|
| 294 |
+
if self.basic_block.terminator is None:
|
| 295 |
+
self.branch(bbexit)
|
| 296 |
+
|
| 297 |
+
@contextlib.contextmanager
|
| 298 |
+
def if_then(self, pred, likely=None):
|
| 299 |
+
"""
|
| 300 |
+
A context manager which sets up a conditional basic block based
|
| 301 |
+
on the given predicate (a i1 value). If the conditional block
|
| 302 |
+
is not explicitly terminated, a branch will be added to the next
|
| 303 |
+
block.
|
| 304 |
+
If *likely* is given, its boolean value indicates whether the
|
| 305 |
+
predicate is likely to be true or not, and metadata is issued
|
| 306 |
+
for LLVM's optimizers to account for that.
|
| 307 |
+
"""
|
| 308 |
+
bb = self.basic_block
|
| 309 |
+
bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if'))
|
| 310 |
+
bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif'))
|
| 311 |
+
br = self.cbranch(pred, bbif, bbend)
|
| 312 |
+
if likely is not None:
|
| 313 |
+
br.set_weights([99, 1] if likely else [1, 99])
|
| 314 |
+
|
| 315 |
+
with self._branch_helper(bbif, bbend):
|
| 316 |
+
yield bbend
|
| 317 |
+
|
| 318 |
+
self.position_at_end(bbend)
|
| 319 |
+
|
| 320 |
+
@contextlib.contextmanager
|
| 321 |
+
def if_else(self, pred, likely=None):
|
| 322 |
+
"""
|
| 323 |
+
A context manager which sets up two conditional basic blocks based
|
| 324 |
+
on the given predicate (a i1 value).
|
| 325 |
+
A tuple of context managers is yield'ed. Each context manager
|
| 326 |
+
acts as a if_then() block.
|
| 327 |
+
*likely* has the same meaning as in if_then().
|
| 328 |
+
|
| 329 |
+
Typical use::
|
| 330 |
+
with builder.if_else(pred) as (then, otherwise):
|
| 331 |
+
with then:
|
| 332 |
+
# emit instructions for when the predicate is true
|
| 333 |
+
with otherwise:
|
| 334 |
+
# emit instructions for when the predicate is false
|
| 335 |
+
"""
|
| 336 |
+
bb = self.basic_block
|
| 337 |
+
bbif = self.append_basic_block(name=_label_suffix(bb.name, '.if'))
|
| 338 |
+
bbelse = self.append_basic_block(name=_label_suffix(bb.name, '.else'))
|
| 339 |
+
bbend = self.append_basic_block(name=_label_suffix(bb.name, '.endif'))
|
| 340 |
+
br = self.cbranch(pred, bbif, bbelse)
|
| 341 |
+
if likely is not None:
|
| 342 |
+
br.set_weights([99, 1] if likely else [1, 99])
|
| 343 |
+
|
| 344 |
+
then = self._branch_helper(bbif, bbend)
|
| 345 |
+
otherwise = self._branch_helper(bbelse, bbend)
|
| 346 |
+
|
| 347 |
+
yield then, otherwise
|
| 348 |
+
|
| 349 |
+
self.position_at_end(bbend)
|
| 350 |
+
|
| 351 |
+
def _insert(self, instr):
|
| 352 |
+
if self.debug_metadata is not None and 'dbg' not in instr.metadata:
|
| 353 |
+
instr.metadata['dbg'] = self.debug_metadata
|
| 354 |
+
self._block.instructions.insert(self._anchor, instr)
|
| 355 |
+
self._anchor += 1
|
| 356 |
+
|
| 357 |
+
def _set_terminator(self, term):
|
| 358 |
+
assert not self.block.is_terminated
|
| 359 |
+
self._insert(term)
|
| 360 |
+
self.block.terminator = term
|
| 361 |
+
return term
|
| 362 |
+
|
| 363 |
+
#
|
| 364 |
+
# Arithmetic APIs
|
| 365 |
+
#
|
| 366 |
+
|
| 367 |
+
@_binop('shl')
|
| 368 |
+
def shl(self, lhs, rhs, name=''):
|
| 369 |
+
"""
|
| 370 |
+
Left integer shift:
|
| 371 |
+
name = lhs << rhs
|
| 372 |
+
"""
|
| 373 |
+
|
| 374 |
+
@_binop('lshr')
|
| 375 |
+
def lshr(self, lhs, rhs, name=''):
|
| 376 |
+
"""
|
| 377 |
+
Logical (unsigned) right integer shift:
|
| 378 |
+
name = lhs >> rhs
|
| 379 |
+
"""
|
| 380 |
+
|
| 381 |
+
@_binop('ashr')
|
| 382 |
+
def ashr(self, lhs, rhs, name=''):
|
| 383 |
+
"""
|
| 384 |
+
Arithmetic (signed) right integer shift:
|
| 385 |
+
name = lhs >> rhs
|
| 386 |
+
"""
|
| 387 |
+
|
| 388 |
+
@_binop('add')
|
| 389 |
+
def add(self, lhs, rhs, name=''):
|
| 390 |
+
"""
|
| 391 |
+
Integer addition:
|
| 392 |
+
name = lhs + rhs
|
| 393 |
+
"""
|
| 394 |
+
|
| 395 |
+
@_binop('fadd')
|
| 396 |
+
def fadd(self, lhs, rhs, name=''):
|
| 397 |
+
"""
|
| 398 |
+
Floating-point addition:
|
| 399 |
+
name = lhs + rhs
|
| 400 |
+
"""
|
| 401 |
+
|
| 402 |
+
@_binop('sub')
|
| 403 |
+
def sub(self, lhs, rhs, name=''):
|
| 404 |
+
"""
|
| 405 |
+
Integer subtraction:
|
| 406 |
+
name = lhs - rhs
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
@_binop('fsub')
|
| 410 |
+
def fsub(self, lhs, rhs, name=''):
|
| 411 |
+
"""
|
| 412 |
+
Floating-point subtraction:
|
| 413 |
+
name = lhs - rhs
|
| 414 |
+
"""
|
| 415 |
+
|
| 416 |
+
@_binop('mul')
|
| 417 |
+
def mul(self, lhs, rhs, name=''):
|
| 418 |
+
"""
|
| 419 |
+
Integer multiplication:
|
| 420 |
+
name = lhs * rhs
|
| 421 |
+
"""
|
| 422 |
+
|
| 423 |
+
@_binop('fmul')
|
| 424 |
+
def fmul(self, lhs, rhs, name=''):
|
| 425 |
+
"""
|
| 426 |
+
Floating-point multiplication:
|
| 427 |
+
name = lhs * rhs
|
| 428 |
+
"""
|
| 429 |
+
|
| 430 |
+
@_binop('udiv')
|
| 431 |
+
def udiv(self, lhs, rhs, name=''):
|
| 432 |
+
"""
|
| 433 |
+
Unsigned integer division:
|
| 434 |
+
name = lhs / rhs
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
@_binop('sdiv')
|
| 438 |
+
def sdiv(self, lhs, rhs, name=''):
|
| 439 |
+
"""
|
| 440 |
+
Signed integer division:
|
| 441 |
+
name = lhs / rhs
|
| 442 |
+
"""
|
| 443 |
+
|
| 444 |
+
@_binop('fdiv')
|
| 445 |
+
def fdiv(self, lhs, rhs, name=''):
|
| 446 |
+
"""
|
| 447 |
+
Floating-point division:
|
| 448 |
+
name = lhs / rhs
|
| 449 |
+
"""
|
| 450 |
+
|
| 451 |
+
@_binop('urem')
|
| 452 |
+
def urem(self, lhs, rhs, name=''):
|
| 453 |
+
"""
|
| 454 |
+
Unsigned integer remainder:
|
| 455 |
+
name = lhs % rhs
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
@_binop('srem')
|
| 459 |
+
def srem(self, lhs, rhs, name=''):
|
| 460 |
+
"""
|
| 461 |
+
Signed integer remainder:
|
| 462 |
+
name = lhs % rhs
|
| 463 |
+
"""
|
| 464 |
+
|
| 465 |
+
@_binop('frem')
|
| 466 |
+
def frem(self, lhs, rhs, name=''):
|
| 467 |
+
"""
|
| 468 |
+
Floating-point remainder:
|
| 469 |
+
name = lhs % rhs
|
| 470 |
+
"""
|
| 471 |
+
|
| 472 |
+
@_binop('or')
|
| 473 |
+
def or_(self, lhs, rhs, name=''):
|
| 474 |
+
"""
|
| 475 |
+
Bitwise integer OR:
|
| 476 |
+
name = lhs | rhs
|
| 477 |
+
"""
|
| 478 |
+
|
| 479 |
+
@_binop('and')
|
| 480 |
+
def and_(self, lhs, rhs, name=''):
|
| 481 |
+
"""
|
| 482 |
+
Bitwise integer AND:
|
| 483 |
+
name = lhs & rhs
|
| 484 |
+
"""
|
| 485 |
+
|
| 486 |
+
@_binop('xor')
|
| 487 |
+
def xor(self, lhs, rhs, name=''):
|
| 488 |
+
"""
|
| 489 |
+
Bitwise integer XOR:
|
| 490 |
+
name = lhs ^ rhs
|
| 491 |
+
"""
|
| 492 |
+
|
| 493 |
+
@_binop_with_overflow('sadd')
|
| 494 |
+
def sadd_with_overflow(self, lhs, rhs, name=''):
|
| 495 |
+
"""
|
| 496 |
+
Signed integer addition with overflow:
|
| 497 |
+
name = {result, overflow bit} = lhs + rhs
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
@_binop_with_overflow('smul')
|
| 501 |
+
def smul_with_overflow(self, lhs, rhs, name=''):
|
| 502 |
+
"""
|
| 503 |
+
Signed integer multiplication with overflow:
|
| 504 |
+
name = {result, overflow bit} = lhs * rhs
|
| 505 |
+
"""
|
| 506 |
+
|
| 507 |
+
@_binop_with_overflow('ssub')
|
| 508 |
+
def ssub_with_overflow(self, lhs, rhs, name=''):
|
| 509 |
+
"""
|
| 510 |
+
Signed integer subtraction with overflow:
|
| 511 |
+
name = {result, overflow bit} = lhs - rhs
|
| 512 |
+
"""
|
| 513 |
+
|
| 514 |
+
@_binop_with_overflow('uadd')
|
| 515 |
+
def uadd_with_overflow(self, lhs, rhs, name=''):
|
| 516 |
+
"""
|
| 517 |
+
Unsigned integer addition with overflow:
|
| 518 |
+
name = {result, overflow bit} = lhs + rhs
|
| 519 |
+
"""
|
| 520 |
+
|
| 521 |
+
@_binop_with_overflow('umul')
|
| 522 |
+
def umul_with_overflow(self, lhs, rhs, name=''):
|
| 523 |
+
"""
|
| 524 |
+
Unsigned integer multiplication with overflow:
|
| 525 |
+
name = {result, overflow bit} = lhs * rhs
|
| 526 |
+
"""
|
| 527 |
+
|
| 528 |
+
@_binop_with_overflow('usub')
|
| 529 |
+
def usub_with_overflow(self, lhs, rhs, name=''):
|
| 530 |
+
"""
|
| 531 |
+
Unsigned integer subtraction with overflow:
|
| 532 |
+
name = {result, overflow bit} = lhs - rhs
|
| 533 |
+
"""
|
| 534 |
+
|
| 535 |
+
#
|
| 536 |
+
# Unary APIs
|
| 537 |
+
#
|
| 538 |
+
|
| 539 |
+
def not_(self, value, name=''):
|
| 540 |
+
"""
|
| 541 |
+
Bitwise integer complement:
|
| 542 |
+
name = ~value
|
| 543 |
+
"""
|
| 544 |
+
if isinstance(value.type, types.VectorType):
|
| 545 |
+
rhs = values.Constant(value.type, (-1,) * value.type.count)
|
| 546 |
+
else:
|
| 547 |
+
rhs = values.Constant(value.type, -1)
|
| 548 |
+
return self.xor(value, rhs, name=name)
|
| 549 |
+
|
| 550 |
+
def neg(self, value, name=''):
|
| 551 |
+
"""
|
| 552 |
+
Integer negative:
|
| 553 |
+
name = -value
|
| 554 |
+
"""
|
| 555 |
+
return self.sub(values.Constant(value.type, 0), value, name=name)
|
| 556 |
+
|
| 557 |
+
@_unop('fneg')
|
| 558 |
+
def fneg(self, arg, name='', flags=()):
|
| 559 |
+
"""
|
| 560 |
+
Floating-point negative:
|
| 561 |
+
name = -arg
|
| 562 |
+
"""
|
| 563 |
+
|
| 564 |
+
#
|
| 565 |
+
# Comparison APIs
|
| 566 |
+
#
|
| 567 |
+
|
| 568 |
+
def _icmp(self, prefix, cmpop, lhs, rhs, name):
|
| 569 |
+
try:
|
| 570 |
+
op = _CMP_MAP[cmpop]
|
| 571 |
+
except KeyError:
|
| 572 |
+
raise ValueError("invalid comparison %r for icmp" % (cmpop,))
|
| 573 |
+
if cmpop not in ('==', '!='):
|
| 574 |
+
op = prefix + op
|
| 575 |
+
instr = instructions.ICMPInstr(self.block, op, lhs, rhs, name=name)
|
| 576 |
+
self._insert(instr)
|
| 577 |
+
return instr
|
| 578 |
+
|
| 579 |
+
def icmp_signed(self, cmpop, lhs, rhs, name=''):
|
| 580 |
+
"""
|
| 581 |
+
Signed integer comparison:
|
| 582 |
+
name = lhs <cmpop> rhs
|
| 583 |
+
|
| 584 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>='
|
| 585 |
+
"""
|
| 586 |
+
return self._icmp('s', cmpop, lhs, rhs, name)
|
| 587 |
+
|
| 588 |
+
def icmp_unsigned(self, cmpop, lhs, rhs, name=''):
|
| 589 |
+
"""
|
| 590 |
+
Unsigned integer (or pointer) comparison:
|
| 591 |
+
name = lhs <cmpop> rhs
|
| 592 |
+
|
| 593 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>='
|
| 594 |
+
"""
|
| 595 |
+
return self._icmp('u', cmpop, lhs, rhs, name)
|
| 596 |
+
|
| 597 |
+
def fcmp_ordered(self, cmpop, lhs, rhs, name='', flags=()):
|
| 598 |
+
"""
|
| 599 |
+
Floating-point ordered comparison:
|
| 600 |
+
name = lhs <cmpop> rhs
|
| 601 |
+
|
| 602 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
|
| 603 |
+
"""
|
| 604 |
+
if cmpop in _CMP_MAP:
|
| 605 |
+
op = 'o' + _CMP_MAP[cmpop]
|
| 606 |
+
else:
|
| 607 |
+
op = cmpop
|
| 608 |
+
instr = instructions.FCMPInstr(
|
| 609 |
+
self.block, op, lhs, rhs, name=name, flags=flags)
|
| 610 |
+
self._insert(instr)
|
| 611 |
+
return instr
|
| 612 |
+
|
| 613 |
+
def fcmp_unordered(self, cmpop, lhs, rhs, name='', flags=()):
|
| 614 |
+
"""
|
| 615 |
+
Floating-point unordered comparison:
|
| 616 |
+
name = lhs <cmpop> rhs
|
| 617 |
+
|
| 618 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
|
| 619 |
+
"""
|
| 620 |
+
if cmpop in _CMP_MAP:
|
| 621 |
+
op = 'u' + _CMP_MAP[cmpop]
|
| 622 |
+
else:
|
| 623 |
+
op = cmpop
|
| 624 |
+
instr = instructions.FCMPInstr(
|
| 625 |
+
self.block, op, lhs, rhs, name=name, flags=flags)
|
| 626 |
+
self._insert(instr)
|
| 627 |
+
return instr
|
| 628 |
+
|
| 629 |
+
def select(self, cond, lhs, rhs, name='', flags=()):
|
| 630 |
+
"""
|
| 631 |
+
Ternary select operator:
|
| 632 |
+
name = cond ? lhs : rhs
|
| 633 |
+
"""
|
| 634 |
+
instr = instructions.SelectInstr(self.block, cond, lhs, rhs, name=name,
|
| 635 |
+
flags=flags)
|
| 636 |
+
self._insert(instr)
|
| 637 |
+
return instr
|
| 638 |
+
|
| 639 |
+
#
|
| 640 |
+
# Cast APIs
|
| 641 |
+
#
|
| 642 |
+
|
| 643 |
+
@_castop('trunc')
|
| 644 |
+
def trunc(self, value, typ, name=''):
|
| 645 |
+
"""
|
| 646 |
+
Truncating integer downcast to a smaller type:
|
| 647 |
+
name = (typ) value
|
| 648 |
+
"""
|
| 649 |
+
|
| 650 |
+
@_castop('zext')
|
| 651 |
+
def zext(self, value, typ, name=''):
|
| 652 |
+
"""
|
| 653 |
+
Zero-extending integer upcast to a larger type:
|
| 654 |
+
name = (typ) value
|
| 655 |
+
"""
|
| 656 |
+
|
| 657 |
+
@_castop('sext')
|
| 658 |
+
def sext(self, value, typ, name=''):
|
| 659 |
+
"""
|
| 660 |
+
Sign-extending integer upcast to a larger type:
|
| 661 |
+
name = (typ) value
|
| 662 |
+
"""
|
| 663 |
+
|
| 664 |
+
@_castop('fptrunc')
|
| 665 |
+
def fptrunc(self, value, typ, name=''):
|
| 666 |
+
"""
|
| 667 |
+
Floating-point downcast to a less precise type:
|
| 668 |
+
name = (typ) value
|
| 669 |
+
"""
|
| 670 |
+
|
| 671 |
+
@_castop('fpext')
|
| 672 |
+
def fpext(self, value, typ, name=''):
|
| 673 |
+
"""
|
| 674 |
+
Floating-point upcast to a more precise type:
|
| 675 |
+
name = (typ) value
|
| 676 |
+
"""
|
| 677 |
+
|
| 678 |
+
@_castop('bitcast')
|
| 679 |
+
def bitcast(self, value, typ, name=''):
|
| 680 |
+
"""
|
| 681 |
+
Pointer cast to a different pointer type:
|
| 682 |
+
name = (typ) value
|
| 683 |
+
"""
|
| 684 |
+
|
| 685 |
+
@_castop('addrspacecast')
|
| 686 |
+
def addrspacecast(self, value, typ, name=''):
|
| 687 |
+
"""
|
| 688 |
+
Pointer cast to a different address space:
|
| 689 |
+
name = (typ) value
|
| 690 |
+
"""
|
| 691 |
+
|
| 692 |
+
@_castop('fptoui')
|
| 693 |
+
def fptoui(self, value, typ, name=''):
|
| 694 |
+
"""
|
| 695 |
+
Convert floating-point to unsigned integer:
|
| 696 |
+
name = (typ) value
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
@_castop('uitofp')
|
| 700 |
+
def uitofp(self, value, typ, name=''):
|
| 701 |
+
"""
|
| 702 |
+
Convert unsigned integer to floating-point:
|
| 703 |
+
name = (typ) value
|
| 704 |
+
"""
|
| 705 |
+
|
| 706 |
+
@_castop('fptosi')
|
| 707 |
+
def fptosi(self, value, typ, name=''):
|
| 708 |
+
"""
|
| 709 |
+
Convert floating-point to signed integer:
|
| 710 |
+
name = (typ) value
|
| 711 |
+
"""
|
| 712 |
+
|
| 713 |
+
@_castop('sitofp')
|
| 714 |
+
def sitofp(self, value, typ, name=''):
|
| 715 |
+
"""
|
| 716 |
+
Convert signed integer to floating-point:
|
| 717 |
+
name = (typ) value
|
| 718 |
+
"""
|
| 719 |
+
|
| 720 |
+
@_castop('ptrtoint')
|
| 721 |
+
def ptrtoint(self, value, typ, name=''):
|
| 722 |
+
"""
|
| 723 |
+
Cast pointer to integer:
|
| 724 |
+
name = (typ) value
|
| 725 |
+
"""
|
| 726 |
+
|
| 727 |
+
@_castop('inttoptr')
|
| 728 |
+
def inttoptr(self, value, typ, name=''):
|
| 729 |
+
"""
|
| 730 |
+
Cast integer to pointer:
|
| 731 |
+
name = (typ) value
|
| 732 |
+
"""
|
| 733 |
+
|
| 734 |
+
#
|
| 735 |
+
# Memory APIs
|
| 736 |
+
#
|
| 737 |
+
|
| 738 |
+
def alloca(self, typ, size=None, name=''):
|
| 739 |
+
"""
|
| 740 |
+
Stack-allocate a slot for *size* elements of the given type.
|
| 741 |
+
(default one element)
|
| 742 |
+
"""
|
| 743 |
+
if size is None:
|
| 744 |
+
pass
|
| 745 |
+
elif isinstance(size, (values.Value, values.Constant)):
|
| 746 |
+
assert isinstance(size.type, types.IntType)
|
| 747 |
+
else:
|
| 748 |
+
# If it is not a Value instance,
|
| 749 |
+
# assume to be a Python integer.
|
| 750 |
+
size = values.Constant(types.IntType(32), size)
|
| 751 |
+
|
| 752 |
+
al = instructions.AllocaInstr(self.block, typ, size, name)
|
| 753 |
+
self._insert(al)
|
| 754 |
+
return al
|
| 755 |
+
|
| 756 |
+
def load(self, ptr, name='', align=None):
|
| 757 |
+
"""
|
| 758 |
+
Load value from pointer, with optional guaranteed alignment:
|
| 759 |
+
name = *ptr
|
| 760 |
+
"""
|
| 761 |
+
if not isinstance(ptr.type, types.PointerType):
|
| 762 |
+
msg = "cannot load from value of type %s (%r): not a pointer"
|
| 763 |
+
raise TypeError(msg % (ptr.type, str(ptr)))
|
| 764 |
+
ld = instructions.LoadInstr(self.block, ptr, name)
|
| 765 |
+
ld.align = align
|
| 766 |
+
self._insert(ld)
|
| 767 |
+
return ld
|
| 768 |
+
|
| 769 |
+
def store(self, value, ptr, align=None):
|
| 770 |
+
"""
|
| 771 |
+
Store value to pointer, with optional guaranteed alignment:
|
| 772 |
+
*ptr = name
|
| 773 |
+
"""
|
| 774 |
+
if not isinstance(ptr.type, types.PointerType):
|
| 775 |
+
msg = "cannot store to value of type %s (%r): not a pointer"
|
| 776 |
+
raise TypeError(msg % (ptr.type, str(ptr)))
|
| 777 |
+
if ptr.type.pointee != value.type:
|
| 778 |
+
raise TypeError("cannot store %s to %s: mismatching types"
|
| 779 |
+
% (value.type, ptr.type))
|
| 780 |
+
st = instructions.StoreInstr(self.block, value, ptr)
|
| 781 |
+
st.align = align
|
| 782 |
+
self._insert(st)
|
| 783 |
+
return st
|
| 784 |
+
|
| 785 |
+
def load_atomic(self, ptr, ordering, align, name=''):
|
| 786 |
+
"""
|
| 787 |
+
Load value from pointer, with optional guaranteed alignment:
|
| 788 |
+
name = *ptr
|
| 789 |
+
"""
|
| 790 |
+
if not isinstance(ptr.type, types.PointerType):
|
| 791 |
+
msg = "cannot load from value of type %s (%r): not a pointer"
|
| 792 |
+
raise TypeError(msg % (ptr.type, str(ptr)))
|
| 793 |
+
ld = instructions.LoadAtomicInstr(
|
| 794 |
+
self.block, ptr, ordering, align, name)
|
| 795 |
+
self._insert(ld)
|
| 796 |
+
return ld
|
| 797 |
+
|
| 798 |
+
def store_atomic(self, value, ptr, ordering, align):
|
| 799 |
+
"""
|
| 800 |
+
Store value to pointer, with optional guaranteed alignment:
|
| 801 |
+
*ptr = name
|
| 802 |
+
"""
|
| 803 |
+
if not isinstance(ptr.type, types.PointerType):
|
| 804 |
+
msg = "cannot store to value of type %s (%r): not a pointer"
|
| 805 |
+
raise TypeError(msg % (ptr.type, str(ptr)))
|
| 806 |
+
if ptr.type.pointee != value.type:
|
| 807 |
+
raise TypeError("cannot store %s to %s: mismatching types"
|
| 808 |
+
% (value.type, ptr.type))
|
| 809 |
+
st = instructions.StoreAtomicInstr(
|
| 810 |
+
self.block, value, ptr, ordering, align)
|
| 811 |
+
self._insert(st)
|
| 812 |
+
return st
|
| 813 |
+
|
| 814 |
+
#
|
| 815 |
+
# Terminators APIs
|
| 816 |
+
#
|
| 817 |
+
|
| 818 |
+
def switch(self, value, default):
|
| 819 |
+
"""
|
| 820 |
+
Create a switch-case with a single *default* target.
|
| 821 |
+
"""
|
| 822 |
+
swt = instructions.SwitchInstr(self.block, 'switch', value, default)
|
| 823 |
+
self._set_terminator(swt)
|
| 824 |
+
return swt
|
| 825 |
+
|
| 826 |
+
def branch(self, target):
|
| 827 |
+
"""
|
| 828 |
+
Unconditional branch to *target*.
|
| 829 |
+
"""
|
| 830 |
+
br = instructions.Branch(self.block, "br", [target])
|
| 831 |
+
self._set_terminator(br)
|
| 832 |
+
return br
|
| 833 |
+
|
| 834 |
+
def cbranch(self, cond, truebr, falsebr):
|
| 835 |
+
"""
|
| 836 |
+
Conditional branch to *truebr* if *cond* is true, else to *falsebr*.
|
| 837 |
+
"""
|
| 838 |
+
br = instructions.ConditionalBranch(self.block, "br",
|
| 839 |
+
[cond, truebr, falsebr])
|
| 840 |
+
self._set_terminator(br)
|
| 841 |
+
return br
|
| 842 |
+
|
| 843 |
+
def branch_indirect(self, addr):
|
| 844 |
+
"""
|
| 845 |
+
Indirect branch to target *addr*.
|
| 846 |
+
"""
|
| 847 |
+
br = instructions.IndirectBranch(self.block, "indirectbr", addr)
|
| 848 |
+
self._set_terminator(br)
|
| 849 |
+
return br
|
| 850 |
+
|
| 851 |
+
def ret_void(self):
|
| 852 |
+
"""
|
| 853 |
+
Return from function without a value.
|
| 854 |
+
"""
|
| 855 |
+
return self._set_terminator(
|
| 856 |
+
instructions.Ret(self.block, "ret void"))
|
| 857 |
+
|
| 858 |
+
def ret(self, value):
|
| 859 |
+
"""
|
| 860 |
+
Return from function with the given *value*.
|
| 861 |
+
"""
|
| 862 |
+
return self._set_terminator(
|
| 863 |
+
instructions.Ret(self.block, "ret", value))
|
| 864 |
+
|
| 865 |
+
def resume(self, landingpad):
|
| 866 |
+
"""
|
| 867 |
+
Resume an in-flight exception.
|
| 868 |
+
"""
|
| 869 |
+
br = instructions.Branch(self.block, "resume", [landingpad])
|
| 870 |
+
self._set_terminator(br)
|
| 871 |
+
return br
|
| 872 |
+
|
| 873 |
+
# Call APIs
|
| 874 |
+
|
| 875 |
+
def call(self, fn, args, name='', cconv=None, tail=False, fastmath=(),
|
| 876 |
+
attrs=(), arg_attrs=None):
|
| 877 |
+
"""
|
| 878 |
+
Call function *fn* with *args*:
|
| 879 |
+
name = fn(args...)
|
| 880 |
+
"""
|
| 881 |
+
inst = instructions.CallInstr(self.block, fn, args, name=name,
|
| 882 |
+
cconv=cconv, tail=tail, fastmath=fastmath,
|
| 883 |
+
attrs=attrs, arg_attrs=arg_attrs)
|
| 884 |
+
self._insert(inst)
|
| 885 |
+
return inst
|
| 886 |
+
|
| 887 |
+
def asm(self, ftype, asm, constraint, args, side_effect, name=''):
|
| 888 |
+
"""
|
| 889 |
+
Inline assembler.
|
| 890 |
+
"""
|
| 891 |
+
asm = instructions.InlineAsm(ftype, asm, constraint, side_effect)
|
| 892 |
+
return self.call(asm, args, name)
|
| 893 |
+
|
| 894 |
+
def load_reg(self, reg_type, reg_name, name=''):
|
| 895 |
+
"""
|
| 896 |
+
Load a register value into an LLVM value.
|
| 897 |
+
Example: v = load_reg(IntType(32), "eax")
|
| 898 |
+
"""
|
| 899 |
+
ftype = types.FunctionType(reg_type, [])
|
| 900 |
+
return self.asm(ftype, "", "={%s}" % reg_name, [], False, name)
|
| 901 |
+
|
| 902 |
+
def store_reg(self, value, reg_type, reg_name, name=''):
|
| 903 |
+
"""
|
| 904 |
+
Store an LLVM value inside a register
|
| 905 |
+
Example:
|
| 906 |
+
store_reg(Constant(IntType(32), 0xAAAAAAAA), IntType(32), "eax")
|
| 907 |
+
"""
|
| 908 |
+
ftype = types.FunctionType(types.VoidType(), [reg_type])
|
| 909 |
+
return self.asm(ftype, "", "{%s}" % reg_name, [value], True, name)
|
| 910 |
+
|
| 911 |
+
def invoke(self, fn, args, normal_to, unwind_to,
|
| 912 |
+
name='', cconv=None, fastmath=(), attrs=(), arg_attrs=None):
|
| 913 |
+
inst = instructions.InvokeInstr(self.block, fn, args, normal_to,
|
| 914 |
+
unwind_to, name=name, cconv=cconv,
|
| 915 |
+
fastmath=fastmath, attrs=attrs,
|
| 916 |
+
arg_attrs=arg_attrs)
|
| 917 |
+
self._set_terminator(inst)
|
| 918 |
+
return inst
|
| 919 |
+
|
| 920 |
+
# GEP APIs
|
| 921 |
+
|
| 922 |
+
def gep(self, ptr, indices, inbounds=False, name=''):
|
| 923 |
+
"""
|
| 924 |
+
Compute effective address (getelementptr):
|
| 925 |
+
name = getelementptr ptr, <indices...>
|
| 926 |
+
"""
|
| 927 |
+
instr = instructions.GEPInstr(self.block, ptr, indices,
|
| 928 |
+
inbounds=inbounds, name=name)
|
| 929 |
+
self._insert(instr)
|
| 930 |
+
return instr
|
| 931 |
+
|
| 932 |
+
# Vector Operations APIs
|
| 933 |
+
|
| 934 |
+
def extract_element(self, vector, idx, name=''):
|
| 935 |
+
"""
|
| 936 |
+
Returns the value at position idx.
|
| 937 |
+
"""
|
| 938 |
+
instr = instructions.ExtractElement(self.block, vector, idx, name=name)
|
| 939 |
+
self._insert(instr)
|
| 940 |
+
return instr
|
| 941 |
+
|
| 942 |
+
def insert_element(self, vector, value, idx, name=''):
|
| 943 |
+
"""
|
| 944 |
+
Returns vector with vector[idx] replaced by value.
|
| 945 |
+
The result is undefined if the idx is larger or equal the vector length.
|
| 946 |
+
"""
|
| 947 |
+
instr = instructions.InsertElement(self.block, vector, value, idx,
|
| 948 |
+
name=name)
|
| 949 |
+
self._insert(instr)
|
| 950 |
+
return instr
|
| 951 |
+
|
| 952 |
+
def shuffle_vector(self, vector1, vector2, mask, name=''):
|
| 953 |
+
"""
|
| 954 |
+
Constructs a permutation of elements from *vector1* and *vector2*.
|
| 955 |
+
Returns a new vector in the same length of *mask*.
|
| 956 |
+
|
| 957 |
+
* *vector1* and *vector2* must have the same element type.
|
| 958 |
+
* *mask* must be a constant vector of integer types.
|
| 959 |
+
"""
|
| 960 |
+
instr = instructions.ShuffleVector(self.block, vector1, vector2, mask,
|
| 961 |
+
name=name)
|
| 962 |
+
self._insert(instr)
|
| 963 |
+
return instr
|
| 964 |
+
|
| 965 |
+
# Aggregate APIs
|
| 966 |
+
|
| 967 |
+
def extract_value(self, agg, idx, name=''):
|
| 968 |
+
"""
|
| 969 |
+
Extract member number *idx* from aggregate.
|
| 970 |
+
"""
|
| 971 |
+
if not isinstance(idx, (tuple, list)):
|
| 972 |
+
idx = [idx]
|
| 973 |
+
instr = instructions.ExtractValue(self.block, agg, idx, name=name)
|
| 974 |
+
self._insert(instr)
|
| 975 |
+
return instr
|
| 976 |
+
|
| 977 |
+
def insert_value(self, agg, value, idx, name=''):
|
| 978 |
+
"""
|
| 979 |
+
Insert *value* into member number *idx* from aggregate.
|
| 980 |
+
"""
|
| 981 |
+
if not isinstance(idx, (tuple, list)):
|
| 982 |
+
idx = [idx]
|
| 983 |
+
instr = instructions.InsertValue(self.block, agg, value, idx, name=name)
|
| 984 |
+
self._insert(instr)
|
| 985 |
+
return instr
|
| 986 |
+
|
| 987 |
+
# PHI APIs
|
| 988 |
+
|
| 989 |
+
def phi(self, typ, name='', flags=()):
|
| 990 |
+
inst = instructions.PhiInstr(self.block, typ, name=name, flags=flags)
|
| 991 |
+
self._insert(inst)
|
| 992 |
+
return inst
|
| 993 |
+
|
| 994 |
+
# Special API
|
| 995 |
+
|
| 996 |
+
def unreachable(self):
|
| 997 |
+
inst = instructions.Unreachable(self.block)
|
| 998 |
+
self._set_terminator(inst)
|
| 999 |
+
return inst
|
| 1000 |
+
|
| 1001 |
+
def atomic_rmw(self, op, ptr, val, ordering, name=''):
|
| 1002 |
+
inst = instructions.AtomicRMW(
|
| 1003 |
+
self.block, op, ptr, val, ordering, name=name)
|
| 1004 |
+
self._insert(inst)
|
| 1005 |
+
return inst
|
| 1006 |
+
|
| 1007 |
+
def cmpxchg(self, ptr, cmp, val, ordering, failordering=None, name=''):
|
| 1008 |
+
"""
|
| 1009 |
+
Atomic compared-and-set:
|
| 1010 |
+
atomic {
|
| 1011 |
+
old = *ptr
|
| 1012 |
+
success = (old == cmp)
|
| 1013 |
+
if (success)
|
| 1014 |
+
*ptr = val
|
| 1015 |
+
}
|
| 1016 |
+
name = { old, success }
|
| 1017 |
+
|
| 1018 |
+
If failordering is `None`, the value of `ordering` is used.
|
| 1019 |
+
"""
|
| 1020 |
+
failordering = ordering if failordering is None else failordering
|
| 1021 |
+
inst = instructions.CmpXchg(self.block, ptr, cmp, val, ordering,
|
| 1022 |
+
failordering, name=name)
|
| 1023 |
+
self._insert(inst)
|
| 1024 |
+
return inst
|
| 1025 |
+
|
| 1026 |
+
def landingpad(self, typ, name='', cleanup=False):
|
| 1027 |
+
inst = instructions.LandingPadInstr(self.block, typ, name, cleanup)
|
| 1028 |
+
self._insert(inst)
|
| 1029 |
+
return inst
|
| 1030 |
+
|
| 1031 |
+
def assume(self, cond):
|
| 1032 |
+
"""
|
| 1033 |
+
Optimizer hint: assume *cond* is always true.
|
| 1034 |
+
"""
|
| 1035 |
+
fn = self.module.declare_intrinsic("llvm.assume")
|
| 1036 |
+
return self.call(fn, [cond])
|
| 1037 |
+
|
| 1038 |
+
def fence(self, ordering, targetscope=None, name=''):
|
| 1039 |
+
"""
|
| 1040 |
+
Add a memory barrier, preventing certain reorderings of load and/or
|
| 1041 |
+
store accesses with
|
| 1042 |
+
respect to other processors and devices.
|
| 1043 |
+
"""
|
| 1044 |
+
inst = instructions.Fence(self.block, ordering, targetscope, name=name)
|
| 1045 |
+
self._insert(inst)
|
| 1046 |
+
return inst
|
| 1047 |
+
|
| 1048 |
+
def comment(self, text):
|
| 1049 |
+
"""
|
| 1050 |
+
Puts a single-line comment into the generated IR. This will be ignored
|
| 1051 |
+
by LLVM, but can be useful for debugging the output of a compiler. Adds
|
| 1052 |
+
a comment to the source file.
|
| 1053 |
+
|
| 1054 |
+
* *text* is a string that does not contain new line characters.
|
| 1055 |
+
"""
|
| 1056 |
+
inst = instructions.Comment(self.block, text)
|
| 1057 |
+
self._insert(inst)
|
| 1058 |
+
return inst
|
| 1059 |
+
|
| 1060 |
+
@_uniop_intrinsic_int("llvm.bswap")
|
| 1061 |
+
def bswap(self, cond):
|
| 1062 |
+
"""
|
| 1063 |
+
Used to byte swap integer values with an even number of bytes (positive
|
| 1064 |
+
multiple of 16 bits)
|
| 1065 |
+
"""
|
| 1066 |
+
|
| 1067 |
+
@_uniop_intrinsic_int("llvm.bitreverse")
|
| 1068 |
+
def bitreverse(self, cond):
|
| 1069 |
+
"""
|
| 1070 |
+
Reverse the bitpattern of an integer value; for example 0b10110110
|
| 1071 |
+
becomes 0b01101101.
|
| 1072 |
+
"""
|
| 1073 |
+
|
| 1074 |
+
@_uniop_intrinsic_int("llvm.ctpop")
|
| 1075 |
+
def ctpop(self, cond):
|
| 1076 |
+
"""
|
| 1077 |
+
Counts the number of bits set in a value.
|
| 1078 |
+
"""
|
| 1079 |
+
|
| 1080 |
+
@_uniop_intrinsic_with_flag("llvm.ctlz")
|
| 1081 |
+
def ctlz(self, cond, flag):
|
| 1082 |
+
"""
|
| 1083 |
+
Counts leading zero bits in *value*. Boolean *flag* indicates whether
|
| 1084 |
+
the result is defined for ``0``.
|
| 1085 |
+
"""
|
| 1086 |
+
|
| 1087 |
+
@_uniop_intrinsic_with_flag("llvm.cttz")
|
| 1088 |
+
def cttz(self, cond, flag):
|
| 1089 |
+
"""
|
| 1090 |
+
Counts trailing zero bits in *value*. Boolean *flag* indicates whether
|
| 1091 |
+
the result is defined for ``0``.
|
| 1092 |
+
"""
|
| 1093 |
+
|
| 1094 |
+
@_triop_intrinsic("llvm.fma")
|
| 1095 |
+
def fma(self, a, b, c):
|
| 1096 |
+
"""
|
| 1097 |
+
Perform the fused multiply-add operation.
|
| 1098 |
+
"""
|
| 1099 |
+
|
| 1100 |
+
def convert_from_fp16(self, a, to=None, name=''):
|
| 1101 |
+
"""
|
| 1102 |
+
Convert from an i16 to the given FP type
|
| 1103 |
+
"""
|
| 1104 |
+
if not to:
|
| 1105 |
+
raise TypeError("expected a float return type")
|
| 1106 |
+
if not isinstance(to, (types.FloatType, types.DoubleType)):
|
| 1107 |
+
raise TypeError("expected a float type, got %s" % to)
|
| 1108 |
+
if not (isinstance(a.type, types.IntType) and a.type.width == 16):
|
| 1109 |
+
raise TypeError("expected an i16 type, got %s" % a.type)
|
| 1110 |
+
|
| 1111 |
+
opname = 'llvm.convert.from.fp16'
|
| 1112 |
+
fn = self.module.declare_intrinsic(opname, [to])
|
| 1113 |
+
return self.call(fn, [a], name)
|
| 1114 |
+
|
| 1115 |
+
@_uniop_intrinsic_float("llvm.convert.to.fp16")
|
| 1116 |
+
def convert_to_fp16(self, a):
|
| 1117 |
+
"""
|
| 1118 |
+
Convert the given FP number to an i16
|
| 1119 |
+
"""
|
vllm/lib/python3.10/site-packages/llvmlite/ir/context.py
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from llvmlite.ir import _utils
|
| 2 |
+
from llvmlite.ir import types
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
class Context(object):
|
| 6 |
+
def __init__(self):
|
| 7 |
+
self.scope = _utils.NameScope()
|
| 8 |
+
self.identified_types = {}
|
| 9 |
+
|
| 10 |
+
def get_identified_type(self, name):
|
| 11 |
+
if name not in self.identified_types:
|
| 12 |
+
self.scope.register(name)
|
| 13 |
+
ty = types.IdentifiedStructType(self, name)
|
| 14 |
+
self.identified_types[name] = ty
|
| 15 |
+
else:
|
| 16 |
+
ty = self.identified_types[name]
|
| 17 |
+
return ty
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
global_context = Context()
|
vllm/lib/python3.10/site-packages/llvmlite/ir/instructions.py
ADDED
|
@@ -0,0 +1,893 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from llvmlite.ir import types
|
| 6 |
+
from llvmlite.ir.values import (Block, Function, Value, NamedValue, Constant,
|
| 7 |
+
MetaDataArgument, MetaDataString, AttributeSet,
|
| 8 |
+
Undefined, ArgumentAttributes)
|
| 9 |
+
from llvmlite.ir._utils import _HasMetadata
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Instruction(NamedValue, _HasMetadata):
|
| 13 |
+
def __init__(self, parent, typ, opname, operands, name='', flags=()):
|
| 14 |
+
super(Instruction, self).__init__(parent, typ, name=name)
|
| 15 |
+
assert isinstance(parent, Block)
|
| 16 |
+
assert isinstance(flags, (tuple, list))
|
| 17 |
+
self.opname = opname
|
| 18 |
+
self.operands = operands
|
| 19 |
+
self.flags = list(flags)
|
| 20 |
+
self.metadata = {}
|
| 21 |
+
|
| 22 |
+
@property
|
| 23 |
+
def function(self):
|
| 24 |
+
return self.parent.function
|
| 25 |
+
|
| 26 |
+
@property
|
| 27 |
+
def module(self):
|
| 28 |
+
return self.parent.function.module
|
| 29 |
+
|
| 30 |
+
def descr(self, buf):
|
| 31 |
+
opname = self.opname
|
| 32 |
+
if self.flags:
|
| 33 |
+
opname = ' '.join([opname] + self.flags)
|
| 34 |
+
operands = ', '.join([op.get_reference() for op in self.operands])
|
| 35 |
+
typ = self.type
|
| 36 |
+
metadata = self._stringify_metadata(leading_comma=True)
|
| 37 |
+
buf.append("{0} {1} {2}{3}\n"
|
| 38 |
+
.format(opname, typ, operands, metadata))
|
| 39 |
+
|
| 40 |
+
def replace_usage(self, old, new):
|
| 41 |
+
if old in self.operands:
|
| 42 |
+
ops = []
|
| 43 |
+
for op in self.operands:
|
| 44 |
+
ops.append(new if op is old else op)
|
| 45 |
+
self.operands = tuple(ops)
|
| 46 |
+
self._clear_string_cache()
|
| 47 |
+
|
| 48 |
+
def __repr__(self):
|
| 49 |
+
return "<ir.%s %r of type '%s', opname %r, operands %r>" % (
|
| 50 |
+
self.__class__.__name__, self.name, self.type,
|
| 51 |
+
self.opname, self.operands)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class CallInstrAttributes(AttributeSet):
|
| 55 |
+
_known = frozenset(['convergent', 'noreturn', 'nounwind', 'readonly',
|
| 56 |
+
'readnone', 'noinline', 'alwaysinline'])
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
TailMarkerOptions = frozenset(['tail', 'musttail', 'notail'])
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class FastMathFlags(AttributeSet):
|
| 63 |
+
_known = frozenset(['fast', 'nnan', 'ninf', 'nsz', 'arcp', 'contract',
|
| 64 |
+
'afn', 'reassoc'])
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class CallInstr(Instruction):
|
| 68 |
+
def __init__(self, parent, func, args, name='', cconv=None, tail=None,
|
| 69 |
+
fastmath=(), attrs=(), arg_attrs=None):
|
| 70 |
+
self.cconv = (func.calling_convention
|
| 71 |
+
if cconv is None and isinstance(func, Function)
|
| 72 |
+
else cconv)
|
| 73 |
+
|
| 74 |
+
# For backwards compatibility with previous API of accepting a "truthy"
|
| 75 |
+
# value for a hint to the optimizer to potentially tail optimize.
|
| 76 |
+
if isinstance(tail, str) and tail in TailMarkerOptions:
|
| 77 |
+
pass
|
| 78 |
+
elif tail:
|
| 79 |
+
tail = "tail"
|
| 80 |
+
else:
|
| 81 |
+
tail = ""
|
| 82 |
+
|
| 83 |
+
self.tail = tail
|
| 84 |
+
self.fastmath = FastMathFlags(fastmath)
|
| 85 |
+
self.attributes = CallInstrAttributes(attrs)
|
| 86 |
+
self.arg_attributes = {}
|
| 87 |
+
if arg_attrs:
|
| 88 |
+
for idx, attrs in arg_attrs.items():
|
| 89 |
+
if not (0 <= idx < len(args)):
|
| 90 |
+
raise ValueError("Invalid argument index {}"
|
| 91 |
+
.format(idx))
|
| 92 |
+
self.arg_attributes[idx] = ArgumentAttributes(attrs)
|
| 93 |
+
|
| 94 |
+
# Fix and validate arguments
|
| 95 |
+
args = list(args)
|
| 96 |
+
for i in range(len(func.function_type.args)):
|
| 97 |
+
arg = args[i]
|
| 98 |
+
expected_type = func.function_type.args[i]
|
| 99 |
+
if (isinstance(expected_type, types.MetaDataType) and
|
| 100 |
+
arg.type != expected_type):
|
| 101 |
+
arg = MetaDataArgument(arg)
|
| 102 |
+
if arg.type != expected_type:
|
| 103 |
+
msg = ("Type of #{0} arg mismatch: {1} != {2}"
|
| 104 |
+
.format(1 + i, expected_type, arg.type))
|
| 105 |
+
raise TypeError(msg)
|
| 106 |
+
args[i] = arg
|
| 107 |
+
|
| 108 |
+
super(CallInstr, self).__init__(parent, func.function_type.return_type,
|
| 109 |
+
"call", [func] + list(args), name=name)
|
| 110 |
+
|
| 111 |
+
@property
|
| 112 |
+
def callee(self):
|
| 113 |
+
return self.operands[0]
|
| 114 |
+
|
| 115 |
+
@callee.setter
|
| 116 |
+
def callee(self, newcallee):
|
| 117 |
+
self.operands[0] = newcallee
|
| 118 |
+
|
| 119 |
+
@property
|
| 120 |
+
def args(self):
|
| 121 |
+
return self.operands[1:]
|
| 122 |
+
|
| 123 |
+
def replace_callee(self, newfunc):
|
| 124 |
+
if newfunc.function_type != self.callee.function_type:
|
| 125 |
+
raise TypeError("New function has incompatible type")
|
| 126 |
+
self.callee = newfunc
|
| 127 |
+
|
| 128 |
+
@property
|
| 129 |
+
def called_function(self):
|
| 130 |
+
"""The callee function"""
|
| 131 |
+
return self.callee
|
| 132 |
+
|
| 133 |
+
def _descr(self, buf, add_metadata):
|
| 134 |
+
def descr_arg(i, a):
|
| 135 |
+
if i in self.arg_attributes:
|
| 136 |
+
attrs = ' '.join(self.arg_attributes[i]._to_list(a.type)) + ' '
|
| 137 |
+
else:
|
| 138 |
+
attrs = ''
|
| 139 |
+
return '{0} {1}{2}'.format(a.type, attrs, a.get_reference())
|
| 140 |
+
args = ', '.join([descr_arg(i, a) for i, a in enumerate(self.args)])
|
| 141 |
+
|
| 142 |
+
fnty = self.callee.function_type
|
| 143 |
+
# Only print function type if variable-argument
|
| 144 |
+
if fnty.var_arg:
|
| 145 |
+
ty = fnty
|
| 146 |
+
# Otherwise, just print the return type.
|
| 147 |
+
else:
|
| 148 |
+
# Fastmath flag work only in this case
|
| 149 |
+
ty = fnty.return_type
|
| 150 |
+
callee_ref = "{0} {1}".format(ty, self.callee.get_reference())
|
| 151 |
+
if self.cconv:
|
| 152 |
+
callee_ref = "{0} {1}".format(self.cconv, callee_ref)
|
| 153 |
+
|
| 154 |
+
tail_marker = ""
|
| 155 |
+
if self.tail:
|
| 156 |
+
tail_marker = "{0} ".format(self.tail)
|
| 157 |
+
|
| 158 |
+
fn_attrs = ' ' + ' '.join(self.attributes._to_list(fnty.return_type))\
|
| 159 |
+
if self.attributes else ''
|
| 160 |
+
|
| 161 |
+
fm_attrs = ' ' + ' '.join(self.fastmath._to_list(fnty.return_type))\
|
| 162 |
+
if self.fastmath else ''
|
| 163 |
+
|
| 164 |
+
buf.append("{tail}{op}{fastmath} {callee}({args}){attr}{meta}\n".format(
|
| 165 |
+
tail=tail_marker,
|
| 166 |
+
op=self.opname,
|
| 167 |
+
callee=callee_ref,
|
| 168 |
+
fastmath=fm_attrs,
|
| 169 |
+
args=args,
|
| 170 |
+
attr=fn_attrs,
|
| 171 |
+
meta=(self._stringify_metadata(leading_comma=True)
|
| 172 |
+
if add_metadata else ""),
|
| 173 |
+
))
|
| 174 |
+
|
| 175 |
+
def descr(self, buf):
|
| 176 |
+
self._descr(buf, add_metadata=True)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class InvokeInstr(CallInstr):
|
| 180 |
+
def __init__(self, parent, func, args, normal_to, unwind_to, name='',
|
| 181 |
+
cconv=None, fastmath=(), attrs=(), arg_attrs=None):
|
| 182 |
+
assert isinstance(normal_to, Block)
|
| 183 |
+
assert isinstance(unwind_to, Block)
|
| 184 |
+
super(InvokeInstr, self).__init__(parent, func, args, name, cconv,
|
| 185 |
+
tail=False, fastmath=fastmath,
|
| 186 |
+
attrs=attrs, arg_attrs=arg_attrs)
|
| 187 |
+
self.opname = "invoke"
|
| 188 |
+
self.normal_to = normal_to
|
| 189 |
+
self.unwind_to = unwind_to
|
| 190 |
+
|
| 191 |
+
def descr(self, buf):
|
| 192 |
+
super(InvokeInstr, self)._descr(buf, add_metadata=False)
|
| 193 |
+
buf.append(" to label {0} unwind label {1}{metadata}\n".format(
|
| 194 |
+
self.normal_to.get_reference(),
|
| 195 |
+
self.unwind_to.get_reference(),
|
| 196 |
+
metadata=self._stringify_metadata(leading_comma=True),
|
| 197 |
+
))
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class Terminator(Instruction):
|
| 201 |
+
def __init__(self, parent, opname, operands):
|
| 202 |
+
super(Terminator, self).__init__(parent, types.VoidType(), opname,
|
| 203 |
+
operands)
|
| 204 |
+
|
| 205 |
+
def descr(self, buf):
|
| 206 |
+
opname = self.opname
|
| 207 |
+
operands = ', '.join(["{0} {1}".format(op.type, op.get_reference())
|
| 208 |
+
for op in self.operands])
|
| 209 |
+
metadata = self._stringify_metadata(leading_comma=True)
|
| 210 |
+
buf.append("{0} {1}{2}".format(opname, operands, metadata))
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
class PredictableInstr(Instruction):
|
| 214 |
+
|
| 215 |
+
def set_weights(self, weights):
|
| 216 |
+
operands = [MetaDataString(self.module, "branch_weights")]
|
| 217 |
+
for w in weights:
|
| 218 |
+
if w < 0:
|
| 219 |
+
raise ValueError("branch weight must be a positive integer")
|
| 220 |
+
operands.append(Constant(types.IntType(32), w))
|
| 221 |
+
md = self.module.add_metadata(operands)
|
| 222 |
+
self.set_metadata("prof", md)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
class Ret(Terminator):
|
| 226 |
+
def __init__(self, parent, opname, return_value=None):
|
| 227 |
+
operands = [return_value] if return_value is not None else []
|
| 228 |
+
super(Ret, self).__init__(parent, opname, operands)
|
| 229 |
+
|
| 230 |
+
@property
|
| 231 |
+
def return_value(self):
|
| 232 |
+
if self.operands:
|
| 233 |
+
return self.operands[0]
|
| 234 |
+
else:
|
| 235 |
+
return None
|
| 236 |
+
|
| 237 |
+
def descr(self, buf):
|
| 238 |
+
return_value = self.return_value
|
| 239 |
+
metadata = self._stringify_metadata(leading_comma=True)
|
| 240 |
+
if return_value is not None:
|
| 241 |
+
buf.append("{0} {1} {2}{3}\n"
|
| 242 |
+
.format(self.opname, return_value.type,
|
| 243 |
+
return_value.get_reference(),
|
| 244 |
+
metadata))
|
| 245 |
+
else:
|
| 246 |
+
buf.append("{0}{1}\n".format(self.opname, metadata))
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class Branch(Terminator):
|
| 250 |
+
pass
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
class ConditionalBranch(PredictableInstr, Terminator):
|
| 254 |
+
pass
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class IndirectBranch(PredictableInstr, Terminator):
|
| 258 |
+
def __init__(self, parent, opname, addr):
|
| 259 |
+
super(IndirectBranch, self).__init__(parent, opname, [addr])
|
| 260 |
+
self.destinations = []
|
| 261 |
+
|
| 262 |
+
@property
|
| 263 |
+
def address(self):
|
| 264 |
+
return self.operands[0]
|
| 265 |
+
|
| 266 |
+
def add_destination(self, block):
|
| 267 |
+
assert isinstance(block, Block)
|
| 268 |
+
self.destinations.append(block)
|
| 269 |
+
|
| 270 |
+
def descr(self, buf):
|
| 271 |
+
destinations = ["label {0}".format(blk.get_reference())
|
| 272 |
+
for blk in self.destinations]
|
| 273 |
+
buf.append("indirectbr {0} {1}, [{2}] {3}\n".format(
|
| 274 |
+
self.address.type,
|
| 275 |
+
self.address.get_reference(),
|
| 276 |
+
', '.join(destinations),
|
| 277 |
+
self._stringify_metadata(leading_comma=True),
|
| 278 |
+
))
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
class SwitchInstr(PredictableInstr, Terminator):
|
| 282 |
+
|
| 283 |
+
def __init__(self, parent, opname, val, default):
|
| 284 |
+
super(SwitchInstr, self).__init__(parent, opname, [val])
|
| 285 |
+
self.default = default
|
| 286 |
+
self.cases = []
|
| 287 |
+
|
| 288 |
+
@property
|
| 289 |
+
def value(self):
|
| 290 |
+
return self.operands[0]
|
| 291 |
+
|
| 292 |
+
def add_case(self, val, block):
|
| 293 |
+
assert isinstance(block, Block)
|
| 294 |
+
if not isinstance(val, Value):
|
| 295 |
+
val = Constant(self.value.type, val)
|
| 296 |
+
self.cases.append((val, block))
|
| 297 |
+
|
| 298 |
+
def descr(self, buf):
|
| 299 |
+
cases = ["{0} {1}, label {2}".format(val.type, val.get_reference(),
|
| 300 |
+
blk.get_reference())
|
| 301 |
+
for val, blk in self.cases]
|
| 302 |
+
buf.append("switch {0} {1}, label {2} [{3}] {4}\n".format(
|
| 303 |
+
self.value.type,
|
| 304 |
+
self.value.get_reference(),
|
| 305 |
+
self.default.get_reference(),
|
| 306 |
+
' '.join(cases),
|
| 307 |
+
self._stringify_metadata(leading_comma=True),
|
| 308 |
+
))
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
class Resume(Terminator):
|
| 312 |
+
pass
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
class SelectInstr(Instruction):
|
| 316 |
+
def __init__(self, parent, cond, lhs, rhs, name='', flags=()):
|
| 317 |
+
assert lhs.type == rhs.type
|
| 318 |
+
super(SelectInstr, self).__init__(parent, lhs.type, "select",
|
| 319 |
+
[cond, lhs, rhs], name=name,
|
| 320 |
+
flags=flags)
|
| 321 |
+
|
| 322 |
+
@property
|
| 323 |
+
def cond(self):
|
| 324 |
+
return self.operands[0]
|
| 325 |
+
|
| 326 |
+
@property
|
| 327 |
+
def lhs(self):
|
| 328 |
+
return self.operands[1]
|
| 329 |
+
|
| 330 |
+
@property
|
| 331 |
+
def rhs(self):
|
| 332 |
+
return self.operands[2]
|
| 333 |
+
|
| 334 |
+
def descr(self, buf):
|
| 335 |
+
buf.append("select {0} {1} {2}, {3} {4}, {5} {6} {7}\n".format(
|
| 336 |
+
' '.join(self.flags),
|
| 337 |
+
self.cond.type, self.cond.get_reference(),
|
| 338 |
+
self.lhs.type, self.lhs.get_reference(),
|
| 339 |
+
self.rhs.type, self.rhs.get_reference(),
|
| 340 |
+
self._stringify_metadata(leading_comma=True),
|
| 341 |
+
))
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
class CompareInstr(Instruction):
|
| 345 |
+
# Define the following in subclasses
|
| 346 |
+
OPNAME = 'invalid-compare'
|
| 347 |
+
VALID_OP = {}
|
| 348 |
+
|
| 349 |
+
def __init__(self, parent, op, lhs, rhs, name='', flags=[]):
|
| 350 |
+
if op not in self.VALID_OP:
|
| 351 |
+
raise ValueError("invalid comparison %r for %s" % (op, self.OPNAME))
|
| 352 |
+
for flag in flags:
|
| 353 |
+
if flag not in self.VALID_FLAG:
|
| 354 |
+
raise ValueError("invalid flag %r for %s" % (flag, self.OPNAME))
|
| 355 |
+
opname = self.OPNAME
|
| 356 |
+
if isinstance(lhs.type, types.VectorType):
|
| 357 |
+
typ = types.VectorType(types.IntType(1), lhs.type.count)
|
| 358 |
+
else:
|
| 359 |
+
typ = types.IntType(1)
|
| 360 |
+
super(CompareInstr, self).__init__(parent, typ,
|
| 361 |
+
opname, [lhs, rhs], flags=flags,
|
| 362 |
+
name=name)
|
| 363 |
+
self.op = op
|
| 364 |
+
|
| 365 |
+
def descr(self, buf):
|
| 366 |
+
buf.append("{opname}{flags} {op} {ty} {lhs}, {rhs} {meta}\n".format(
|
| 367 |
+
opname=self.opname,
|
| 368 |
+
flags=''.join(' ' + it for it in self.flags),
|
| 369 |
+
op=self.op,
|
| 370 |
+
ty=self.operands[0].type,
|
| 371 |
+
lhs=self.operands[0].get_reference(),
|
| 372 |
+
rhs=self.operands[1].get_reference(),
|
| 373 |
+
meta=self._stringify_metadata(leading_comma=True),
|
| 374 |
+
))
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
class ICMPInstr(CompareInstr):
|
| 378 |
+
OPNAME = 'icmp'
|
| 379 |
+
VALID_OP = {
|
| 380 |
+
'eq': 'equal',
|
| 381 |
+
'ne': 'not equal',
|
| 382 |
+
'ugt': 'unsigned greater than',
|
| 383 |
+
'uge': 'unsigned greater or equal',
|
| 384 |
+
'ult': 'unsigned less than',
|
| 385 |
+
'ule': 'unsigned less or equal',
|
| 386 |
+
'sgt': 'signed greater than',
|
| 387 |
+
'sge': 'signed greater or equal',
|
| 388 |
+
'slt': 'signed less than',
|
| 389 |
+
'sle': 'signed less or equal',
|
| 390 |
+
}
|
| 391 |
+
VALID_FLAG = set()
|
| 392 |
+
|
| 393 |
+
|
| 394 |
+
class FCMPInstr(CompareInstr):
|
| 395 |
+
OPNAME = 'fcmp'
|
| 396 |
+
VALID_OP = {
|
| 397 |
+
'false': 'no comparison, always returns false',
|
| 398 |
+
'oeq': 'ordered and equal',
|
| 399 |
+
'ogt': 'ordered and greater than',
|
| 400 |
+
'oge': 'ordered and greater than or equal',
|
| 401 |
+
'olt': 'ordered and less than',
|
| 402 |
+
'ole': 'ordered and less than or equal',
|
| 403 |
+
'one': 'ordered and not equal',
|
| 404 |
+
'ord': 'ordered (no nans)',
|
| 405 |
+
'ueq': 'unordered or equal',
|
| 406 |
+
'ugt': 'unordered or greater than',
|
| 407 |
+
'uge': 'unordered or greater than or equal',
|
| 408 |
+
'ult': 'unordered or less than',
|
| 409 |
+
'ule': 'unordered or less than or equal',
|
| 410 |
+
'une': 'unordered or not equal',
|
| 411 |
+
'uno': 'unordered (either nans)',
|
| 412 |
+
'true': 'no comparison, always returns true',
|
| 413 |
+
}
|
| 414 |
+
VALID_FLAG = {'nnan', 'ninf', 'nsz', 'arcp', 'contract', 'afn', 'reassoc',
|
| 415 |
+
'fast'}
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class CastInstr(Instruction):
|
| 419 |
+
def __init__(self, parent, op, val, typ, name=''):
|
| 420 |
+
super(CastInstr, self).__init__(parent, typ, op, [val], name=name)
|
| 421 |
+
|
| 422 |
+
def descr(self, buf):
|
| 423 |
+
buf.append("{0} {1} {2} to {3} {4}\n".format(
|
| 424 |
+
self.opname,
|
| 425 |
+
self.operands[0].type,
|
| 426 |
+
self.operands[0].get_reference(),
|
| 427 |
+
self.type,
|
| 428 |
+
self._stringify_metadata(leading_comma=True),
|
| 429 |
+
))
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class LoadInstr(Instruction):
|
| 433 |
+
|
| 434 |
+
def __init__(self, parent, ptr, name=''):
|
| 435 |
+
super(LoadInstr, self).__init__(parent, ptr.type.pointee, "load",
|
| 436 |
+
[ptr], name=name)
|
| 437 |
+
self.align = None
|
| 438 |
+
|
| 439 |
+
def descr(self, buf):
|
| 440 |
+
[val] = self.operands
|
| 441 |
+
if self.align is not None:
|
| 442 |
+
align = ', align %d' % (self.align)
|
| 443 |
+
else:
|
| 444 |
+
align = ''
|
| 445 |
+
buf.append("load {0}, {1} {2}{3}{4}\n".format(
|
| 446 |
+
val.type.pointee,
|
| 447 |
+
val.type,
|
| 448 |
+
val.get_reference(),
|
| 449 |
+
align,
|
| 450 |
+
self._stringify_metadata(leading_comma=True),
|
| 451 |
+
))
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
class StoreInstr(Instruction):
|
| 455 |
+
def __init__(self, parent, val, ptr):
|
| 456 |
+
super(StoreInstr, self).__init__(parent, types.VoidType(), "store",
|
| 457 |
+
[val, ptr])
|
| 458 |
+
|
| 459 |
+
def descr(self, buf):
|
| 460 |
+
val, ptr = self.operands
|
| 461 |
+
if self.align is not None:
|
| 462 |
+
align = ', align %d' % (self.align)
|
| 463 |
+
else:
|
| 464 |
+
align = ''
|
| 465 |
+
buf.append("store {0} {1}, {2} {3}{4}{5}\n".format(
|
| 466 |
+
val.type,
|
| 467 |
+
val.get_reference(),
|
| 468 |
+
ptr.type,
|
| 469 |
+
ptr.get_reference(),
|
| 470 |
+
align,
|
| 471 |
+
self._stringify_metadata(leading_comma=True),
|
| 472 |
+
))
|
| 473 |
+
|
| 474 |
+
|
| 475 |
+
class LoadAtomicInstr(Instruction):
|
| 476 |
+
def __init__(self, parent, ptr, ordering, align, name=''):
|
| 477 |
+
super(LoadAtomicInstr, self).__init__(parent, ptr.type.pointee,
|
| 478 |
+
"load atomic", [ptr], name=name)
|
| 479 |
+
self.ordering = ordering
|
| 480 |
+
self.align = align
|
| 481 |
+
|
| 482 |
+
def descr(self, buf):
|
| 483 |
+
[val] = self.operands
|
| 484 |
+
buf.append("load atomic {0}, {1} {2} {3}, align {4}{5}\n".format(
|
| 485 |
+
val.type.pointee,
|
| 486 |
+
val.type,
|
| 487 |
+
val.get_reference(),
|
| 488 |
+
self.ordering,
|
| 489 |
+
self.align,
|
| 490 |
+
self._stringify_metadata(leading_comma=True),
|
| 491 |
+
))
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
class StoreAtomicInstr(Instruction):
|
| 495 |
+
def __init__(self, parent, val, ptr, ordering, align):
|
| 496 |
+
super(StoreAtomicInstr, self).__init__(parent, types.VoidType(),
|
| 497 |
+
"store atomic", [val, ptr])
|
| 498 |
+
self.ordering = ordering
|
| 499 |
+
self.align = align
|
| 500 |
+
|
| 501 |
+
def descr(self, buf):
|
| 502 |
+
val, ptr = self.operands
|
| 503 |
+
buf.append("store atomic {0} {1}, {2} {3} {4}, align {5}{6}\n".format(
|
| 504 |
+
val.type,
|
| 505 |
+
val.get_reference(),
|
| 506 |
+
ptr.type,
|
| 507 |
+
ptr.get_reference(),
|
| 508 |
+
self.ordering,
|
| 509 |
+
self.align,
|
| 510 |
+
self._stringify_metadata(leading_comma=True),
|
| 511 |
+
))
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
class AllocaInstr(Instruction):
|
| 515 |
+
def __init__(self, parent, typ, count, name):
|
| 516 |
+
operands = [count] if count else ()
|
| 517 |
+
super(AllocaInstr, self).__init__(parent, typ.as_pointer(), "alloca",
|
| 518 |
+
operands, name)
|
| 519 |
+
self.align = None
|
| 520 |
+
|
| 521 |
+
def descr(self, buf):
|
| 522 |
+
buf.append("{0} {1}".format(self.opname, self.type.pointee))
|
| 523 |
+
if self.operands:
|
| 524 |
+
op, = self.operands
|
| 525 |
+
buf.append(", {0} {1}".format(op.type, op.get_reference()))
|
| 526 |
+
if self.align is not None:
|
| 527 |
+
buf.append(", align {0}".format(self.align))
|
| 528 |
+
if self.metadata:
|
| 529 |
+
buf.append(self._stringify_metadata(leading_comma=True))
|
| 530 |
+
|
| 531 |
+
|
| 532 |
+
class GEPInstr(Instruction):
|
| 533 |
+
def __init__(self, parent, ptr, indices, inbounds, name):
|
| 534 |
+
typ = ptr.type
|
| 535 |
+
lasttyp = None
|
| 536 |
+
lastaddrspace = 0
|
| 537 |
+
for i in indices:
|
| 538 |
+
lasttyp, typ = typ, typ.gep(i)
|
| 539 |
+
# inherit the addrspace from the last seen pointer
|
| 540 |
+
if isinstance(lasttyp, types.PointerType):
|
| 541 |
+
lastaddrspace = lasttyp.addrspace
|
| 542 |
+
|
| 543 |
+
if (not isinstance(typ, types.PointerType) and
|
| 544 |
+
isinstance(lasttyp, types.PointerType)):
|
| 545 |
+
typ = lasttyp
|
| 546 |
+
else:
|
| 547 |
+
typ = typ.as_pointer(lastaddrspace)
|
| 548 |
+
|
| 549 |
+
super(GEPInstr, self).__init__(parent, typ, "getelementptr",
|
| 550 |
+
[ptr] + list(indices), name=name)
|
| 551 |
+
self.pointer = ptr
|
| 552 |
+
self.indices = indices
|
| 553 |
+
self.inbounds = inbounds
|
| 554 |
+
|
| 555 |
+
def descr(self, buf):
|
| 556 |
+
indices = ['{0} {1}'.format(i.type, i.get_reference())
|
| 557 |
+
for i in self.indices]
|
| 558 |
+
op = "getelementptr inbounds" if self.inbounds else "getelementptr"
|
| 559 |
+
buf.append("{0} {1}, {2} {3}, {4} {5}\n".format(
|
| 560 |
+
op,
|
| 561 |
+
self.pointer.type.pointee,
|
| 562 |
+
self.pointer.type,
|
| 563 |
+
self.pointer.get_reference(),
|
| 564 |
+
', '.join(indices),
|
| 565 |
+
self._stringify_metadata(leading_comma=True),
|
| 566 |
+
))
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
class PhiInstr(Instruction):
|
| 570 |
+
def __init__(self, parent, typ, name, flags=()):
|
| 571 |
+
super(PhiInstr, self).__init__(parent, typ, "phi", (), name=name,
|
| 572 |
+
flags=flags)
|
| 573 |
+
self.incomings = []
|
| 574 |
+
|
| 575 |
+
def descr(self, buf):
|
| 576 |
+
incs = ', '.join('[{0}, {1}]'.format(v.get_reference(),
|
| 577 |
+
b.get_reference())
|
| 578 |
+
for v, b in self.incomings)
|
| 579 |
+
buf.append("phi {0} {1} {2} {3}\n".format(
|
| 580 |
+
' '.join(self.flags),
|
| 581 |
+
self.type,
|
| 582 |
+
incs,
|
| 583 |
+
self._stringify_metadata(leading_comma=True),
|
| 584 |
+
))
|
| 585 |
+
|
| 586 |
+
def add_incoming(self, value, block):
|
| 587 |
+
assert isinstance(block, Block)
|
| 588 |
+
self.incomings.append((value, block))
|
| 589 |
+
|
| 590 |
+
def replace_usage(self, old, new):
|
| 591 |
+
self.incomings = [((new if val is old else val), blk)
|
| 592 |
+
for (val, blk) in self.incomings]
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class ExtractElement(Instruction):
|
| 596 |
+
def __init__(self, parent, vector, index, name=''):
|
| 597 |
+
if not isinstance(vector.type, types.VectorType):
|
| 598 |
+
raise TypeError("vector needs to be of VectorType.")
|
| 599 |
+
if not isinstance(index.type, types.IntType):
|
| 600 |
+
raise TypeError("index needs to be of IntType.")
|
| 601 |
+
typ = vector.type.element
|
| 602 |
+
super(ExtractElement, self).__init__(parent, typ, "extractelement",
|
| 603 |
+
[vector, index], name=name)
|
| 604 |
+
|
| 605 |
+
def descr(self, buf):
|
| 606 |
+
operands = ", ".join("{0} {1}".format(
|
| 607 |
+
op.type, op.get_reference()) for op in self.operands)
|
| 608 |
+
buf.append("{opname} {operands}\n".format(
|
| 609 |
+
opname=self.opname, operands=operands))
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
class InsertElement(Instruction):
|
| 613 |
+
def __init__(self, parent, vector, value, index, name=''):
|
| 614 |
+
if not isinstance(vector.type, types.VectorType):
|
| 615 |
+
raise TypeError("vector needs to be of VectorType.")
|
| 616 |
+
if not value.type == vector.type.element:
|
| 617 |
+
raise TypeError(
|
| 618 |
+
"value needs to be of type {} not {}.".format(
|
| 619 |
+
vector.type.element, value.type))
|
| 620 |
+
if not isinstance(index.type, types.IntType):
|
| 621 |
+
raise TypeError("index needs to be of IntType.")
|
| 622 |
+
typ = vector.type
|
| 623 |
+
super(InsertElement, self).__init__(parent, typ, "insertelement",
|
| 624 |
+
[vector, value, index], name=name)
|
| 625 |
+
|
| 626 |
+
def descr(self, buf):
|
| 627 |
+
operands = ", ".join("{0} {1}".format(
|
| 628 |
+
op.type, op.get_reference()) for op in self.operands)
|
| 629 |
+
buf.append("{opname} {operands}\n".format(
|
| 630 |
+
opname=self.opname, operands=operands))
|
| 631 |
+
|
| 632 |
+
|
| 633 |
+
class ShuffleVector(Instruction):
|
| 634 |
+
def __init__(self, parent, vector1, vector2, mask, name=''):
|
| 635 |
+
if not isinstance(vector1.type, types.VectorType):
|
| 636 |
+
raise TypeError("vector1 needs to be of VectorType.")
|
| 637 |
+
if vector2 != Undefined:
|
| 638 |
+
if vector2.type != vector1.type:
|
| 639 |
+
raise TypeError("vector2 needs to be " +
|
| 640 |
+
"Undefined or of the same type as vector1.")
|
| 641 |
+
if (not isinstance(mask, Constant) or
|
| 642 |
+
not isinstance(mask.type, types.VectorType) or
|
| 643 |
+
not (isinstance(mask.type.element, types.IntType) and
|
| 644 |
+
mask.type.element.width == 32)):
|
| 645 |
+
raise TypeError("mask needs to be a constant i32 vector.")
|
| 646 |
+
typ = types.VectorType(vector1.type.element, mask.type.count)
|
| 647 |
+
index_range = range(vector1.type.count
|
| 648 |
+
if vector2 == Undefined
|
| 649 |
+
else 2 * vector1.type.count)
|
| 650 |
+
if not all(ii.constant in index_range for ii in mask.constant):
|
| 651 |
+
raise IndexError(
|
| 652 |
+
"mask values need to be in {0}".format(index_range),
|
| 653 |
+
)
|
| 654 |
+
super(ShuffleVector, self).__init__(parent, typ, "shufflevector",
|
| 655 |
+
[vector1, vector2, mask], name=name)
|
| 656 |
+
|
| 657 |
+
def descr(self, buf):
|
| 658 |
+
buf.append("shufflevector {0} {1}\n".format(
|
| 659 |
+
", ".join("{0} {1}".format(op.type, op.get_reference())
|
| 660 |
+
for op in self.operands),
|
| 661 |
+
self._stringify_metadata(leading_comma=True),
|
| 662 |
+
))
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
class ExtractValue(Instruction):
|
| 666 |
+
def __init__(self, parent, agg, indices, name=''):
|
| 667 |
+
typ = agg.type
|
| 668 |
+
try:
|
| 669 |
+
for i in indices:
|
| 670 |
+
typ = typ.elements[i]
|
| 671 |
+
except (AttributeError, IndexError):
|
| 672 |
+
raise TypeError("Can't index at %r in %s"
|
| 673 |
+
% (list(indices), agg.type))
|
| 674 |
+
|
| 675 |
+
super(ExtractValue, self).__init__(parent, typ, "extractvalue",
|
| 676 |
+
[agg], name=name)
|
| 677 |
+
|
| 678 |
+
self.aggregate = agg
|
| 679 |
+
self.indices = indices
|
| 680 |
+
|
| 681 |
+
def descr(self, buf):
|
| 682 |
+
indices = [str(i) for i in self.indices]
|
| 683 |
+
|
| 684 |
+
buf.append("extractvalue {0} {1}, {2} {3}\n".format(
|
| 685 |
+
self.aggregate.type,
|
| 686 |
+
self.aggregate.get_reference(),
|
| 687 |
+
', '.join(indices),
|
| 688 |
+
self._stringify_metadata(leading_comma=True),
|
| 689 |
+
))
|
| 690 |
+
|
| 691 |
+
|
| 692 |
+
class InsertValue(Instruction):
|
| 693 |
+
def __init__(self, parent, agg, elem, indices, name=''):
|
| 694 |
+
typ = agg.type
|
| 695 |
+
try:
|
| 696 |
+
for i in indices:
|
| 697 |
+
typ = typ.elements[i]
|
| 698 |
+
except (AttributeError, IndexError):
|
| 699 |
+
raise TypeError("Can't index at %r in %s"
|
| 700 |
+
% (list(indices), agg.type))
|
| 701 |
+
if elem.type != typ:
|
| 702 |
+
raise TypeError("Can only insert %s at %r in %s: got %s"
|
| 703 |
+
% (typ, list(indices), agg.type, elem.type))
|
| 704 |
+
super(InsertValue, self).__init__(parent, agg.type, "insertvalue",
|
| 705 |
+
[agg, elem], name=name)
|
| 706 |
+
|
| 707 |
+
self.aggregate = agg
|
| 708 |
+
self.value = elem
|
| 709 |
+
self.indices = indices
|
| 710 |
+
|
| 711 |
+
def descr(self, buf):
|
| 712 |
+
indices = [str(i) for i in self.indices]
|
| 713 |
+
|
| 714 |
+
buf.append("insertvalue {0} {1}, {2} {3}, {4} {5}\n".format(
|
| 715 |
+
self.aggregate.type, self.aggregate.get_reference(),
|
| 716 |
+
self.value.type, self.value.get_reference(),
|
| 717 |
+
', '.join(indices),
|
| 718 |
+
self._stringify_metadata(leading_comma=True),
|
| 719 |
+
))
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
class Unreachable(Instruction):
|
| 723 |
+
def __init__(self, parent):
|
| 724 |
+
super(Unreachable, self).__init__(parent, types.VoidType(),
|
| 725 |
+
"unreachable", (), name='')
|
| 726 |
+
|
| 727 |
+
def descr(self, buf):
|
| 728 |
+
buf += (self.opname, "\n")
|
| 729 |
+
|
| 730 |
+
|
| 731 |
+
class InlineAsm(object):
|
| 732 |
+
def __init__(self, ftype, asm, constraint, side_effect=False):
|
| 733 |
+
self.type = ftype.return_type
|
| 734 |
+
self.function_type = ftype
|
| 735 |
+
self.asm = asm
|
| 736 |
+
self.constraint = constraint
|
| 737 |
+
self.side_effect = side_effect
|
| 738 |
+
|
| 739 |
+
def descr(self, buf):
|
| 740 |
+
sideeffect = 'sideeffect' if self.side_effect else ''
|
| 741 |
+
fmt = 'asm {sideeffect} "{asm}", "{constraint}"\n'
|
| 742 |
+
buf.append(fmt.format(sideeffect=sideeffect, asm=self.asm,
|
| 743 |
+
constraint=self.constraint))
|
| 744 |
+
|
| 745 |
+
def get_reference(self):
|
| 746 |
+
buf = []
|
| 747 |
+
self.descr(buf)
|
| 748 |
+
return "".join(buf)
|
| 749 |
+
|
| 750 |
+
def __str__(self):
|
| 751 |
+
return "{0} {1}".format(self.type, self.get_reference())
|
| 752 |
+
|
| 753 |
+
|
| 754 |
+
class AtomicRMW(Instruction):
|
| 755 |
+
def __init__(self, parent, op, ptr, val, ordering, name):
|
| 756 |
+
super(AtomicRMW, self).__init__(parent, val.type, "atomicrmw",
|
| 757 |
+
(ptr, val), name=name)
|
| 758 |
+
self.operation = op
|
| 759 |
+
self.ordering = ordering
|
| 760 |
+
|
| 761 |
+
def descr(self, buf):
|
| 762 |
+
ptr, val = self.operands
|
| 763 |
+
fmt = ("atomicrmw {op} {ptrty} {ptr}, {valty} {val} {ordering} "
|
| 764 |
+
"{metadata}\n")
|
| 765 |
+
buf.append(fmt.format(op=self.operation,
|
| 766 |
+
ptrty=ptr.type,
|
| 767 |
+
ptr=ptr.get_reference(),
|
| 768 |
+
valty=val.type,
|
| 769 |
+
val=val.get_reference(),
|
| 770 |
+
ordering=self.ordering,
|
| 771 |
+
metadata=self._stringify_metadata(
|
| 772 |
+
leading_comma=True),
|
| 773 |
+
))
|
| 774 |
+
|
| 775 |
+
|
| 776 |
+
class CmpXchg(Instruction):
|
| 777 |
+
"""This instruction has changed since llvm3.5. It is not compatible with
|
| 778 |
+
older llvm versions.
|
| 779 |
+
"""
|
| 780 |
+
|
| 781 |
+
def __init__(self, parent, ptr, cmp, val, ordering, failordering, name):
|
| 782 |
+
outtype = types.LiteralStructType([val.type, types.IntType(1)])
|
| 783 |
+
super(CmpXchg, self).__init__(parent, outtype, "cmpxchg",
|
| 784 |
+
(ptr, cmp, val), name=name)
|
| 785 |
+
self.ordering = ordering
|
| 786 |
+
self.failordering = failordering
|
| 787 |
+
|
| 788 |
+
def descr(self, buf):
|
| 789 |
+
ptr, cmpval, val = self.operands
|
| 790 |
+
fmt = "cmpxchg {ptrty} {ptr}, {ty} {cmp}, {ty} {val} {ordering} " \
|
| 791 |
+
"{failordering} {metadata}\n"
|
| 792 |
+
buf.append(fmt.format(ptrty=ptr.type,
|
| 793 |
+
ptr=ptr.get_reference(),
|
| 794 |
+
ty=cmpval.type,
|
| 795 |
+
cmp=cmpval.get_reference(),
|
| 796 |
+
val=val.get_reference(),
|
| 797 |
+
ordering=self.ordering,
|
| 798 |
+
failordering=self.failordering,
|
| 799 |
+
metadata=self._stringify_metadata(
|
| 800 |
+
leading_comma=True),
|
| 801 |
+
))
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
class _LandingPadClause(object):
|
| 805 |
+
def __init__(self, value):
|
| 806 |
+
self.value = value
|
| 807 |
+
|
| 808 |
+
def __str__(self):
|
| 809 |
+
return "{kind} {type} {value}".format(
|
| 810 |
+
kind=self.kind,
|
| 811 |
+
type=self.value.type,
|
| 812 |
+
value=self.value.get_reference())
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
class CatchClause(_LandingPadClause):
|
| 816 |
+
kind = 'catch'
|
| 817 |
+
|
| 818 |
+
|
| 819 |
+
class FilterClause(_LandingPadClause):
|
| 820 |
+
kind = 'filter'
|
| 821 |
+
|
| 822 |
+
def __init__(self, value):
|
| 823 |
+
assert isinstance(value, Constant)
|
| 824 |
+
assert isinstance(value.type, types.ArrayType)
|
| 825 |
+
super(FilterClause, self).__init__(value)
|
| 826 |
+
|
| 827 |
+
|
| 828 |
+
class LandingPadInstr(Instruction):
|
| 829 |
+
def __init__(self, parent, typ, name='', cleanup=False):
|
| 830 |
+
super(LandingPadInstr, self).__init__(parent, typ, "landingpad", [],
|
| 831 |
+
name=name)
|
| 832 |
+
self.cleanup = cleanup
|
| 833 |
+
self.clauses = []
|
| 834 |
+
|
| 835 |
+
def add_clause(self, clause):
|
| 836 |
+
assert isinstance(clause, _LandingPadClause)
|
| 837 |
+
self.clauses.append(clause)
|
| 838 |
+
|
| 839 |
+
def descr(self, buf):
|
| 840 |
+
fmt = "landingpad {type}{cleanup}{clauses}\n"
|
| 841 |
+
buf.append(fmt.format(type=self.type,
|
| 842 |
+
cleanup=' cleanup' if self.cleanup else '',
|
| 843 |
+
clauses=''.join(["\n {0}".format(clause)
|
| 844 |
+
for clause in self.clauses]),
|
| 845 |
+
))
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
class Fence(Instruction):
|
| 849 |
+
"""
|
| 850 |
+
The `fence` instruction.
|
| 851 |
+
|
| 852 |
+
As of LLVM 5.0.1:
|
| 853 |
+
|
| 854 |
+
fence [syncscope("<target-scope>")] <ordering> ; yields void
|
| 855 |
+
"""
|
| 856 |
+
|
| 857 |
+
VALID_FENCE_ORDERINGS = {"acquire", "release", "acq_rel", "seq_cst"}
|
| 858 |
+
|
| 859 |
+
def __init__(self, parent, ordering, targetscope=None, name=''):
|
| 860 |
+
super(Fence, self).__init__(parent, types.VoidType(), "fence", (),
|
| 861 |
+
name=name)
|
| 862 |
+
if ordering not in self.VALID_FENCE_ORDERINGS:
|
| 863 |
+
msg = "Invalid fence ordering \"{0}\"! Should be one of {1}."
|
| 864 |
+
raise ValueError(msg .format(ordering,
|
| 865 |
+
", ".join(self.VALID_FENCE_ORDERINGS)))
|
| 866 |
+
self.ordering = ordering
|
| 867 |
+
self.targetscope = targetscope
|
| 868 |
+
|
| 869 |
+
def descr(self, buf):
|
| 870 |
+
if self.targetscope is None:
|
| 871 |
+
syncscope = ""
|
| 872 |
+
else:
|
| 873 |
+
syncscope = 'syncscope("{0}") '.format(self.targetscope)
|
| 874 |
+
|
| 875 |
+
fmt = "fence {syncscope}{ordering}\n"
|
| 876 |
+
buf.append(fmt.format(syncscope=syncscope,
|
| 877 |
+
ordering=self.ordering,
|
| 878 |
+
))
|
| 879 |
+
|
| 880 |
+
|
| 881 |
+
class Comment(Instruction):
|
| 882 |
+
"""
|
| 883 |
+
A line comment.
|
| 884 |
+
"""
|
| 885 |
+
|
| 886 |
+
def __init__(self, parent, text):
|
| 887 |
+
super(Comment, self).__init__(parent, types.VoidType(), ";", (),
|
| 888 |
+
name='')
|
| 889 |
+
assert "\n" not in text, "Comment cannot contain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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import collections
|
| 2 |
+
|
| 3 |
+
from llvmlite.ir import context, values, types, _utils
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class Module(object):
|
| 7 |
+
def __init__(self, name='', context=context.global_context):
|
| 8 |
+
self.context = context
|
| 9 |
+
self.name = name # name is for debugging/informational
|
| 10 |
+
self.data_layout = ""
|
| 11 |
+
self.scope = _utils.NameScope()
|
| 12 |
+
self.triple = 'unknown-unknown-unknown'
|
| 13 |
+
self.globals = collections.OrderedDict()
|
| 14 |
+
# Innamed metadata nodes.
|
| 15 |
+
self.metadata = []
|
| 16 |
+
# Named metadata nodes
|
| 17 |
+
self.namedmetadata = {}
|
| 18 |
+
# Cache for metadata node deduplication
|
| 19 |
+
self._metadatacache = {}
|
| 20 |
+
|
| 21 |
+
def _fix_metadata_operands(self, operands):
|
| 22 |
+
fixed_ops = []
|
| 23 |
+
for op in operands:
|
| 24 |
+
if op is None:
|
| 25 |
+
# A literal None creates a null metadata value
|
| 26 |
+
op = types.MetaDataType()(None)
|
| 27 |
+
elif isinstance(op, str):
|
| 28 |
+
# A literal string creates a metadata string value
|
| 29 |
+
op = values.MetaDataString(self, op)
|
| 30 |
+
elif isinstance(op, (list, tuple)):
|
| 31 |
+
# A sequence creates a metadata node reference
|
| 32 |
+
op = self.add_metadata(op)
|
| 33 |
+
fixed_ops.append(op)
|
| 34 |
+
return fixed_ops
|
| 35 |
+
|
| 36 |
+
def _fix_di_operands(self, operands):
|
| 37 |
+
fixed_ops = []
|
| 38 |
+
for name, op in operands:
|
| 39 |
+
if isinstance(op, (list, tuple)):
|
| 40 |
+
# A sequence creates a metadata node reference
|
| 41 |
+
op = self.add_metadata(op)
|
| 42 |
+
fixed_ops.append((name, op))
|
| 43 |
+
return fixed_ops
|
| 44 |
+
|
| 45 |
+
def add_metadata(self, operands):
|
| 46 |
+
"""
|
| 47 |
+
Add an unnamed metadata to the module with the given *operands*
|
| 48 |
+
(a sequence of values) or return a previous equivalent metadata.
|
| 49 |
+
A MDValue instance is returned, it can then be associated to
|
| 50 |
+
e.g. an instruction.
|
| 51 |
+
"""
|
| 52 |
+
if not isinstance(operands, (list, tuple)):
|
| 53 |
+
raise TypeError("expected a list or tuple of metadata values, "
|
| 54 |
+
"got %r" % (operands,))
|
| 55 |
+
operands = self._fix_metadata_operands(operands)
|
| 56 |
+
key = tuple(operands)
|
| 57 |
+
if key not in self._metadatacache:
|
| 58 |
+
n = len(self.metadata)
|
| 59 |
+
md = values.MDValue(self, operands, name=str(n))
|
| 60 |
+
self._metadatacache[key] = md
|
| 61 |
+
else:
|
| 62 |
+
md = self._metadatacache[key]
|
| 63 |
+
return md
|
| 64 |
+
|
| 65 |
+
def add_debug_info(self, kind, operands, is_distinct=False):
|
| 66 |
+
"""
|
| 67 |
+
Add debug information metadata to the module with the given
|
| 68 |
+
*operands* (a dict of values with string keys) or return
|
| 69 |
+
a previous equivalent metadata. *kind* is a string of the
|
| 70 |
+
debug information kind (e.g. "DICompileUnit").
|
| 71 |
+
|
| 72 |
+
A DIValue instance is returned, it can then be associated to e.g.
|
| 73 |
+
an instruction.
|
| 74 |
+
"""
|
| 75 |
+
operands = tuple(sorted(self._fix_di_operands(operands.items())))
|
| 76 |
+
key = (kind, operands, is_distinct)
|
| 77 |
+
if key not in self._metadatacache:
|
| 78 |
+
n = len(self.metadata)
|
| 79 |
+
di = values.DIValue(self, is_distinct, kind, operands, name=str(n))
|
| 80 |
+
self._metadatacache[key] = di
|
| 81 |
+
else:
|
| 82 |
+
di = self._metadatacache[key]
|
| 83 |
+
return di
|
| 84 |
+
|
| 85 |
+
def add_named_metadata(self, name, element=None):
|
| 86 |
+
"""
|
| 87 |
+
Add a named metadata node to the module, if it doesn't exist,
|
| 88 |
+
or return the existing node.
|
| 89 |
+
If *element* is given, it will append a new element to
|
| 90 |
+
the named metadata node. If *element* is a sequence of values
|
| 91 |
+
(rather than a metadata value), a new unnamed node will first be
|
| 92 |
+
created.
|
| 93 |
+
|
| 94 |
+
Example::
|
| 95 |
+
module.add_named_metadata("llvm.ident", ["llvmlite/1.0"])
|
| 96 |
+
"""
|
| 97 |
+
if name in self.namedmetadata:
|
| 98 |
+
nmd = self.namedmetadata[name]
|
| 99 |
+
else:
|
| 100 |
+
nmd = self.namedmetadata[name] = values.NamedMetaData(self)
|
| 101 |
+
if element is not None:
|
| 102 |
+
if not isinstance(element, values.Value):
|
| 103 |
+
element = self.add_metadata(element)
|
| 104 |
+
if not isinstance(element.type, types.MetaDataType):
|
| 105 |
+
raise TypeError("wrong type for metadata element: got %r"
|
| 106 |
+
% (element,))
|
| 107 |
+
nmd.add(element)
|
| 108 |
+
return nmd
|
| 109 |
+
|
| 110 |
+
def get_named_metadata(self, name):
|
| 111 |
+
"""
|
| 112 |
+
Return the metadata node with the given *name*. KeyError is raised
|
| 113 |
+
if no such node exists (contrast with add_named_metadata()).
|
| 114 |
+
"""
|
| 115 |
+
return self.namedmetadata[name]
|
| 116 |
+
|
| 117 |
+
@property
|
| 118 |
+
def functions(self):
|
| 119 |
+
"""
|
| 120 |
+
A list of functions declared or defined in this module.
|
| 121 |
+
"""
|
| 122 |
+
return [v for v in self.globals.values()
|
| 123 |
+
if isinstance(v, values.Function)]
|
| 124 |
+
|
| 125 |
+
@property
|
| 126 |
+
def global_values(self):
|
| 127 |
+
"""
|
| 128 |
+
An iterable of global values in this module.
|
| 129 |
+
"""
|
| 130 |
+
return self.globals.values()
|
| 131 |
+
|
| 132 |
+
def get_global(self, name):
|
| 133 |
+
"""
|
| 134 |
+
Get a global value by name.
|
| 135 |
+
"""
|
| 136 |
+
return self.globals[name]
|
| 137 |
+
|
| 138 |
+
def add_global(self, globalvalue):
|
| 139 |
+
"""
|
| 140 |
+
Add a new global value.
|
| 141 |
+
"""
|
| 142 |
+
assert globalvalue.name not in self.globals
|
| 143 |
+
self.globals[globalvalue.name] = globalvalue
|
| 144 |
+
|
| 145 |
+
def get_unique_name(self, name=''):
|
| 146 |
+
"""
|
| 147 |
+
Get a unique global name with the following *name* hint.
|
| 148 |
+
"""
|
| 149 |
+
return self.scope.deduplicate(name)
|
| 150 |
+
|
| 151 |
+
def declare_intrinsic(self, intrinsic, tys=(), fnty=None):
|
| 152 |
+
def _error():
|
| 153 |
+
raise NotImplementedError("unknown intrinsic %r with %d types"
|
| 154 |
+
% (intrinsic, len(tys)))
|
| 155 |
+
|
| 156 |
+
if intrinsic in {'llvm.cttz', 'llvm.ctlz', 'llvm.fma'}:
|
| 157 |
+
suffixes = [tys[0].intrinsic_name]
|
| 158 |
+
else:
|
| 159 |
+
suffixes = [t.intrinsic_name for t in tys]
|
| 160 |
+
name = '.'.join([intrinsic] + suffixes)
|
| 161 |
+
if name in self.globals:
|
| 162 |
+
return self.globals[name]
|
| 163 |
+
|
| 164 |
+
if fnty is not None:
|
| 165 |
+
# General case: function type is given
|
| 166 |
+
pass
|
| 167 |
+
# Compute function type if omitted for common cases
|
| 168 |
+
elif len(tys) == 0 and intrinsic == 'llvm.assume':
|
| 169 |
+
fnty = types.FunctionType(types.VoidType(), [types.IntType(1)])
|
| 170 |
+
elif len(tys) == 1:
|
| 171 |
+
if intrinsic == 'llvm.powi':
|
| 172 |
+
fnty = types.FunctionType(tys[0], [tys[0], types.IntType(32)])
|
| 173 |
+
elif intrinsic == 'llvm.pow':
|
| 174 |
+
fnty = types.FunctionType(tys[0], tys * 2)
|
| 175 |
+
elif intrinsic == 'llvm.convert.from.fp16':
|
| 176 |
+
fnty = types.FunctionType(tys[0], [types.IntType(16)])
|
| 177 |
+
elif intrinsic == 'llvm.convert.to.fp16':
|
| 178 |
+
fnty = types.FunctionType(types.IntType(16), tys)
|
| 179 |
+
else:
|
| 180 |
+
fnty = types.FunctionType(tys[0], tys)
|
| 181 |
+
elif len(tys) == 2:
|
| 182 |
+
if intrinsic == 'llvm.memset':
|
| 183 |
+
tys = [tys[0], types.IntType(8), tys[1],
|
| 184 |
+
types.IntType(1)]
|
| 185 |
+
fnty = types.FunctionType(types.VoidType(), tys)
|
| 186 |
+
elif intrinsic in {'llvm.cttz', 'llvm.ctlz'}:
|
| 187 |
+
tys = [tys[0], types.IntType(1)]
|
| 188 |
+
fnty = types.FunctionType(tys[0], tys)
|
| 189 |
+
else:
|
| 190 |
+
_error()
|
| 191 |
+
elif len(tys) == 3:
|
| 192 |
+
if intrinsic in ('llvm.memcpy', 'llvm.memmove'):
|
| 193 |
+
tys = tys + [types.IntType(1)]
|
| 194 |
+
fnty = types.FunctionType(types.VoidType(), tys)
|
| 195 |
+
elif intrinsic == 'llvm.fma':
|
| 196 |
+
tys = [tys[0]] * 3
|
| 197 |
+
fnty = types.FunctionType(tys[0], tys)
|
| 198 |
+
else:
|
| 199 |
+
_error()
|
| 200 |
+
else:
|
| 201 |
+
_error()
|
| 202 |
+
return values.Function(self, fnty, name=name)
|
| 203 |
+
|
| 204 |
+
def get_identified_types(self):
|
| 205 |
+
return self.context.identified_types
|
| 206 |
+
|
| 207 |
+
def _get_body_lines(self):
|
| 208 |
+
# Type declarations
|
| 209 |
+
lines = [it.get_declaration()
|
| 210 |
+
for it in self.get_identified_types().values()]
|
| 211 |
+
# Global values (including function definitions)
|
| 212 |
+
lines += [str(v) for v in self.globals.values()]
|
| 213 |
+
return lines
|
| 214 |
+
|
| 215 |
+
def _get_metadata_lines(self):
|
| 216 |
+
mdbuf = []
|
| 217 |
+
for k, v in self.namedmetadata.items():
|
| 218 |
+
mdbuf.append("!{name} = !{{ {operands} }}".format(
|
| 219 |
+
name=k, operands=', '.join(i.get_reference()
|
| 220 |
+
for i in v.operands)))
|
| 221 |
+
for md in self.metadata:
|
| 222 |
+
mdbuf.append(str(md))
|
| 223 |
+
return mdbuf
|
| 224 |
+
|
| 225 |
+
def _stringify_body(self):
|
| 226 |
+
# For testing
|
| 227 |
+
return "\n".join(self._get_body_lines())
|
| 228 |
+
|
| 229 |
+
def _stringify_metadata(self):
|
| 230 |
+
# For testing
|
| 231 |
+
return "\n".join(self._get_metadata_lines())
|
| 232 |
+
|
| 233 |
+
def __repr__(self):
|
| 234 |
+
lines = []
|
| 235 |
+
# Header
|
| 236 |
+
lines += [
|
| 237 |
+
'; ModuleID = "%s"' % (self.name,),
|
| 238 |
+
'target triple = "%s"' % (self.triple,),
|
| 239 |
+
'target datalayout = "%s"' % (self.data_layout,),
|
| 240 |
+
'']
|
| 241 |
+
# Body
|
| 242 |
+
lines += self._get_body_lines()
|
| 243 |
+
# Metadata
|
| 244 |
+
lines += self._get_metadata_lines()
|
| 245 |
+
|
| 246 |
+
return "\n".join(lines)
|
vllm/lib/python3.10/site-packages/llvmlite/ir/transforms.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from llvmlite.ir import CallInstr
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class Visitor(object):
|
| 5 |
+
def visit(self, module):
|
| 6 |
+
self._module = module
|
| 7 |
+
for func in module.functions:
|
| 8 |
+
self.visit_Function(func)
|
| 9 |
+
|
| 10 |
+
def visit_Function(self, func):
|
| 11 |
+
self._function = func
|
| 12 |
+
for bb in func.blocks:
|
| 13 |
+
self.visit_BasicBlock(bb)
|
| 14 |
+
|
| 15 |
+
def visit_BasicBlock(self, bb):
|
| 16 |
+
self._basic_block = bb
|
| 17 |
+
for instr in bb.instructions:
|
| 18 |
+
self.visit_Instruction(instr)
|
| 19 |
+
|
| 20 |
+
def visit_Instruction(self, instr):
|
| 21 |
+
raise NotImplementedError
|
| 22 |
+
|
| 23 |
+
@property
|
| 24 |
+
def module(self):
|
| 25 |
+
return self._module
|
| 26 |
+
|
| 27 |
+
@property
|
| 28 |
+
def function(self):
|
| 29 |
+
return self._function
|
| 30 |
+
|
| 31 |
+
@property
|
| 32 |
+
def basic_block(self):
|
| 33 |
+
return self._basic_block
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CallVisitor(Visitor):
|
| 37 |
+
def visit_Instruction(self, instr):
|
| 38 |
+
if isinstance(instr, CallInstr):
|
| 39 |
+
self.visit_Call(instr)
|
| 40 |
+
|
| 41 |
+
def visit_Call(self, instr):
|
| 42 |
+
raise NotImplementedError
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ReplaceCalls(CallVisitor):
|
| 46 |
+
def __init__(self, orig, repl):
|
| 47 |
+
super(ReplaceCalls, self).__init__()
|
| 48 |
+
self.orig = orig
|
| 49 |
+
self.repl = repl
|
| 50 |
+
self.calls = []
|
| 51 |
+
|
| 52 |
+
def visit_Call(self, instr):
|
| 53 |
+
if instr.callee == self.orig:
|
| 54 |
+
instr.replace_callee(self.repl)
|
| 55 |
+
self.calls.append(instr)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def replace_all_calls(mod, orig, repl):
|
| 59 |
+
"""Replace all calls to `orig` to `repl` in module `mod`.
|
| 60 |
+
Returns the references to the returned calls
|
| 61 |
+
"""
|
| 62 |
+
rc = ReplaceCalls(orig, repl)
|
| 63 |
+
rc.visit(mod)
|
| 64 |
+
return rc.calls
|
vllm/lib/python3.10/site-packages/llvmlite/ir/types.py
ADDED
|
@@ -0,0 +1,614 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes that are LLVM types
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import struct
|
| 6 |
+
|
| 7 |
+
from llvmlite.ir._utils import _StrCaching
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def _wrapname(x):
|
| 11 |
+
return '"{0}"'.format(x.replace('\\', '\\5c').replace('"', '\\22'))
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class Type(_StrCaching):
|
| 15 |
+
"""
|
| 16 |
+
The base class for all LLVM types.
|
| 17 |
+
"""
|
| 18 |
+
is_pointer = False
|
| 19 |
+
null = 'zeroinitializer'
|
| 20 |
+
|
| 21 |
+
def __repr__(self):
|
| 22 |
+
return "<%s %s>" % (type(self), str(self))
|
| 23 |
+
|
| 24 |
+
def _to_string(self):
|
| 25 |
+
raise NotImplementedError
|
| 26 |
+
|
| 27 |
+
def as_pointer(self, addrspace=0):
|
| 28 |
+
return PointerType(self, addrspace)
|
| 29 |
+
|
| 30 |
+
def __ne__(self, other):
|
| 31 |
+
return not (self == other)
|
| 32 |
+
|
| 33 |
+
def _get_ll_pointer_type(self, target_data, context=None):
|
| 34 |
+
"""
|
| 35 |
+
Convert this type object to an LLVM type.
|
| 36 |
+
"""
|
| 37 |
+
from llvmlite.ir import Module, GlobalVariable
|
| 38 |
+
from llvmlite.binding import parse_assembly
|
| 39 |
+
|
| 40 |
+
if context is None:
|
| 41 |
+
m = Module()
|
| 42 |
+
else:
|
| 43 |
+
m = Module(context=context)
|
| 44 |
+
foo = GlobalVariable(m, self, name="foo")
|
| 45 |
+
with parse_assembly(str(m)) as llmod:
|
| 46 |
+
return llmod.get_global_variable(foo.name).type
|
| 47 |
+
|
| 48 |
+
def get_abi_size(self, target_data, context=None):
|
| 49 |
+
"""
|
| 50 |
+
Get the ABI size of this type according to data layout *target_data*.
|
| 51 |
+
"""
|
| 52 |
+
llty = self._get_ll_pointer_type(target_data, context)
|
| 53 |
+
return target_data.get_pointee_abi_size(llty)
|
| 54 |
+
|
| 55 |
+
def get_abi_alignment(self, target_data, context=None):
|
| 56 |
+
"""
|
| 57 |
+
Get the minimum ABI alignment of this type according to data layout
|
| 58 |
+
*target_data*.
|
| 59 |
+
"""
|
| 60 |
+
llty = self._get_ll_pointer_type(target_data, context)
|
| 61 |
+
return target_data.get_pointee_abi_alignment(llty)
|
| 62 |
+
|
| 63 |
+
def format_constant(self, value):
|
| 64 |
+
"""
|
| 65 |
+
Format constant *value* of this type. This method may be overriden
|
| 66 |
+
by subclasses.
|
| 67 |
+
"""
|
| 68 |
+
return str(value)
|
| 69 |
+
|
| 70 |
+
def wrap_constant_value(self, value):
|
| 71 |
+
"""
|
| 72 |
+
Wrap constant *value* if necessary. This method may be overriden
|
| 73 |
+
by subclasses (especially aggregate types).
|
| 74 |
+
"""
|
| 75 |
+
return value
|
| 76 |
+
|
| 77 |
+
def __call__(self, value):
|
| 78 |
+
"""
|
| 79 |
+
Create a LLVM constant of this type with the given Python value.
|
| 80 |
+
"""
|
| 81 |
+
from llvmlite.ir import Constant
|
| 82 |
+
return Constant(self, value)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class MetaDataType(Type):
|
| 86 |
+
|
| 87 |
+
def _to_string(self):
|
| 88 |
+
return "metadata"
|
| 89 |
+
|
| 90 |
+
def as_pointer(self):
|
| 91 |
+
raise TypeError
|
| 92 |
+
|
| 93 |
+
def __eq__(self, other):
|
| 94 |
+
return isinstance(other, MetaDataType)
|
| 95 |
+
|
| 96 |
+
def __hash__(self):
|
| 97 |
+
return hash(MetaDataType)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
class LabelType(Type):
|
| 101 |
+
"""
|
| 102 |
+
The label type is the type of e.g. basic blocks.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
def _to_string(self):
|
| 106 |
+
return "label"
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
class PointerType(Type):
|
| 110 |
+
"""
|
| 111 |
+
The type of all pointer values.
|
| 112 |
+
"""
|
| 113 |
+
is_pointer = True
|
| 114 |
+
null = 'null'
|
| 115 |
+
|
| 116 |
+
def __init__(self, pointee, addrspace=0):
|
| 117 |
+
assert not isinstance(pointee, VoidType)
|
| 118 |
+
self.pointee = pointee
|
| 119 |
+
self.addrspace = addrspace
|
| 120 |
+
|
| 121 |
+
def _to_string(self):
|
| 122 |
+
if self.addrspace != 0:
|
| 123 |
+
return "{0} addrspace({1})*".format(self.pointee, self.addrspace)
|
| 124 |
+
else:
|
| 125 |
+
return "{0}*".format(self.pointee)
|
| 126 |
+
|
| 127 |
+
def __eq__(self, other):
|
| 128 |
+
if isinstance(other, PointerType):
|
| 129 |
+
return (self.pointee, self.addrspace) == (other.pointee,
|
| 130 |
+
other.addrspace)
|
| 131 |
+
else:
|
| 132 |
+
return False
|
| 133 |
+
|
| 134 |
+
def __hash__(self):
|
| 135 |
+
return hash(PointerType)
|
| 136 |
+
|
| 137 |
+
def gep(self, i):
|
| 138 |
+
"""
|
| 139 |
+
Resolve the type of the i-th element (for getelementptr lookups).
|
| 140 |
+
"""
|
| 141 |
+
if not isinstance(i.type, IntType):
|
| 142 |
+
raise TypeError(i.type)
|
| 143 |
+
return self.pointee
|
| 144 |
+
|
| 145 |
+
@property
|
| 146 |
+
def intrinsic_name(self):
|
| 147 |
+
return 'p%d%s' % (self.addrspace, self.pointee.intrinsic_name)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class VoidType(Type):
|
| 151 |
+
"""
|
| 152 |
+
The type for empty values (e.g. a function returning no value).
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def _to_string(self):
|
| 156 |
+
return 'void'
|
| 157 |
+
|
| 158 |
+
def __eq__(self, other):
|
| 159 |
+
return isinstance(other, VoidType)
|
| 160 |
+
|
| 161 |
+
def __hash__(self):
|
| 162 |
+
return hash(VoidType)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class FunctionType(Type):
|
| 166 |
+
"""
|
| 167 |
+
The type for functions.
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
def __init__(self, return_type, args, var_arg=False):
|
| 171 |
+
self.return_type = return_type
|
| 172 |
+
self.args = tuple(args)
|
| 173 |
+
self.var_arg = var_arg
|
| 174 |
+
|
| 175 |
+
def _to_string(self):
|
| 176 |
+
if self.args:
|
| 177 |
+
strargs = ', '.join([str(a) for a in self.args])
|
| 178 |
+
if self.var_arg:
|
| 179 |
+
return '{0} ({1}, ...)'.format(self.return_type, strargs)
|
| 180 |
+
else:
|
| 181 |
+
return '{0} ({1})'.format(self.return_type, strargs)
|
| 182 |
+
elif self.var_arg:
|
| 183 |
+
return '{0} (...)'.format(self.return_type)
|
| 184 |
+
else:
|
| 185 |
+
return '{0} ()'.format(self.return_type)
|
| 186 |
+
|
| 187 |
+
def __eq__(self, other):
|
| 188 |
+
if isinstance(other, FunctionType):
|
| 189 |
+
return (self.return_type == other.return_type and
|
| 190 |
+
self.args == other.args and self.var_arg == other.var_arg)
|
| 191 |
+
else:
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
def __hash__(self):
|
| 195 |
+
return hash(FunctionType)
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class IntType(Type):
|
| 199 |
+
"""
|
| 200 |
+
The type for integers.
|
| 201 |
+
"""
|
| 202 |
+
null = '0'
|
| 203 |
+
_instance_cache = {}
|
| 204 |
+
width: int
|
| 205 |
+
|
| 206 |
+
def __new__(cls, bits):
|
| 207 |
+
# Cache all common integer types
|
| 208 |
+
if 0 <= bits <= 128:
|
| 209 |
+
try:
|
| 210 |
+
return cls._instance_cache[bits]
|
| 211 |
+
except KeyError:
|
| 212 |
+
inst = cls._instance_cache[bits] = cls.__new(bits)
|
| 213 |
+
return inst
|
| 214 |
+
return cls.__new(bits)
|
| 215 |
+
|
| 216 |
+
@classmethod
|
| 217 |
+
def __new(cls, bits):
|
| 218 |
+
assert isinstance(bits, int) and bits >= 0
|
| 219 |
+
self = super(IntType, cls).__new__(cls)
|
| 220 |
+
self.width = bits
|
| 221 |
+
return self
|
| 222 |
+
|
| 223 |
+
def __getnewargs__(self):
|
| 224 |
+
return self.width,
|
| 225 |
+
|
| 226 |
+
def __copy__(self):
|
| 227 |
+
return self
|
| 228 |
+
|
| 229 |
+
def _to_string(self):
|
| 230 |
+
return 'i%u' % (self.width,)
|
| 231 |
+
|
| 232 |
+
def __eq__(self, other):
|
| 233 |
+
if isinstance(other, IntType):
|
| 234 |
+
return self.width == other.width
|
| 235 |
+
else:
|
| 236 |
+
return False
|
| 237 |
+
|
| 238 |
+
def __hash__(self):
|
| 239 |
+
return hash(IntType)
|
| 240 |
+
|
| 241 |
+
def format_constant(self, val):
|
| 242 |
+
if isinstance(val, bool):
|
| 243 |
+
return str(val).lower()
|
| 244 |
+
else:
|
| 245 |
+
return str(val)
|
| 246 |
+
|
| 247 |
+
def wrap_constant_value(self, val):
|
| 248 |
+
if val is None:
|
| 249 |
+
return 0
|
| 250 |
+
return val
|
| 251 |
+
|
| 252 |
+
@property
|
| 253 |
+
def intrinsic_name(self):
|
| 254 |
+
return str(self)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _as_float(value):
|
| 258 |
+
"""
|
| 259 |
+
Truncate to single-precision float.
|
| 260 |
+
"""
|
| 261 |
+
return struct.unpack('f', struct.pack('f', value))[0]
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def _as_half(value):
|
| 265 |
+
"""
|
| 266 |
+
Truncate to half-precision float.
|
| 267 |
+
"""
|
| 268 |
+
try:
|
| 269 |
+
return struct.unpack('e', struct.pack('e', value))[0]
|
| 270 |
+
except struct.error:
|
| 271 |
+
# 'e' only added in Python 3.6+
|
| 272 |
+
return _as_float(value)
|
| 273 |
+
|
| 274 |
+
|
| 275 |
+
def _format_float_as_hex(value, packfmt, unpackfmt, numdigits):
|
| 276 |
+
raw = struct.pack(packfmt, float(value))
|
| 277 |
+
intrep = struct.unpack(unpackfmt, raw)[0]
|
| 278 |
+
out = '{{0:#{0}x}}'.format(numdigits).format(intrep)
|
| 279 |
+
return out
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _format_double(value):
|
| 283 |
+
"""
|
| 284 |
+
Format *value* as a hexadecimal string of its IEEE double precision
|
| 285 |
+
representation.
|
| 286 |
+
"""
|
| 287 |
+
return _format_float_as_hex(value, 'd', 'Q', 16)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class _BaseFloatType(Type):
|
| 291 |
+
|
| 292 |
+
def __new__(cls):
|
| 293 |
+
return cls._instance_cache
|
| 294 |
+
|
| 295 |
+
def __eq__(self, other):
|
| 296 |
+
return isinstance(other, type(self))
|
| 297 |
+
|
| 298 |
+
def __hash__(self):
|
| 299 |
+
return hash(type(self))
|
| 300 |
+
|
| 301 |
+
@classmethod
|
| 302 |
+
def _create_instance(cls):
|
| 303 |
+
cls._instance_cache = super(_BaseFloatType, cls).__new__(cls)
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class HalfType(_BaseFloatType):
|
| 307 |
+
"""
|
| 308 |
+
The type for single-precision floats.
|
| 309 |
+
"""
|
| 310 |
+
null = '0.0'
|
| 311 |
+
intrinsic_name = 'f16'
|
| 312 |
+
|
| 313 |
+
def __str__(self):
|
| 314 |
+
return 'half'
|
| 315 |
+
|
| 316 |
+
def format_constant(self, value):
|
| 317 |
+
return _format_double(_as_half(value))
|
| 318 |
+
|
| 319 |
+
|
| 320 |
+
class FloatType(_BaseFloatType):
|
| 321 |
+
"""
|
| 322 |
+
The type for single-precision floats.
|
| 323 |
+
"""
|
| 324 |
+
null = '0.0'
|
| 325 |
+
intrinsic_name = 'f32'
|
| 326 |
+
|
| 327 |
+
def __str__(self):
|
| 328 |
+
return 'float'
|
| 329 |
+
|
| 330 |
+
def format_constant(self, value):
|
| 331 |
+
return _format_double(_as_float(value))
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
class DoubleType(_BaseFloatType):
|
| 335 |
+
"""
|
| 336 |
+
The type for double-precision floats.
|
| 337 |
+
"""
|
| 338 |
+
null = '0.0'
|
| 339 |
+
intrinsic_name = 'f64'
|
| 340 |
+
|
| 341 |
+
def __str__(self):
|
| 342 |
+
return 'double'
|
| 343 |
+
|
| 344 |
+
def format_constant(self, value):
|
| 345 |
+
return _format_double(value)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
for _cls in (HalfType, FloatType, DoubleType):
|
| 349 |
+
_cls._create_instance()
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
class _Repeat(object):
|
| 353 |
+
def __init__(self, value, size):
|
| 354 |
+
self.value = value
|
| 355 |
+
self.size = size
|
| 356 |
+
|
| 357 |
+
def __len__(self):
|
| 358 |
+
return self.size
|
| 359 |
+
|
| 360 |
+
def __getitem__(self, item):
|
| 361 |
+
if 0 <= item < self.size:
|
| 362 |
+
return self.value
|
| 363 |
+
else:
|
| 364 |
+
raise IndexError(item)
|
| 365 |
+
|
| 366 |
+
|
| 367 |
+
class VectorType(Type):
|
| 368 |
+
"""
|
| 369 |
+
The type for vectors of primitive data items (e.g. "<f32 x 4>").
|
| 370 |
+
"""
|
| 371 |
+
|
| 372 |
+
def __init__(self, element, count):
|
| 373 |
+
self.element = element
|
| 374 |
+
self.count = count
|
| 375 |
+
|
| 376 |
+
@property
|
| 377 |
+
def elements(self):
|
| 378 |
+
return _Repeat(self.element, self.count)
|
| 379 |
+
|
| 380 |
+
def __len__(self):
|
| 381 |
+
return self.count
|
| 382 |
+
|
| 383 |
+
def _to_string(self):
|
| 384 |
+
return "<%d x %s>" % (self.count, self.element)
|
| 385 |
+
|
| 386 |
+
def __eq__(self, other):
|
| 387 |
+
if isinstance(other, VectorType):
|
| 388 |
+
return self.element == other.element and self.count == other.count
|
| 389 |
+
|
| 390 |
+
def __hash__(self):
|
| 391 |
+
# TODO: why does this not take self.element/self.count into account?
|
| 392 |
+
return hash(VectorType)
|
| 393 |
+
|
| 394 |
+
def __copy__(self):
|
| 395 |
+
return self
|
| 396 |
+
|
| 397 |
+
def format_constant(self, value):
|
| 398 |
+
itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference())
|
| 399 |
+
for x in value])
|
| 400 |
+
return "<{0}>".format(itemstring)
|
| 401 |
+
|
| 402 |
+
def wrap_constant_value(self, values):
|
| 403 |
+
from . import Value, Constant
|
| 404 |
+
if not isinstance(values, (list, tuple)):
|
| 405 |
+
if isinstance(values, Constant):
|
| 406 |
+
if values.type != self.element:
|
| 407 |
+
raise TypeError("expected {} for {}".format(
|
| 408 |
+
self.element, values.type))
|
| 409 |
+
return (values, ) * self.count
|
| 410 |
+
return (Constant(self.element, values), ) * self.count
|
| 411 |
+
if len(values) != len(self):
|
| 412 |
+
raise ValueError("wrong constant size for %s: got %d elements"
|
| 413 |
+
% (self, len(values)))
|
| 414 |
+
return [Constant(ty, val) if not isinstance(val, Value) else val
|
| 415 |
+
for ty, val in zip(self.elements, values)]
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
class Aggregate(Type):
|
| 419 |
+
"""
|
| 420 |
+
Base class for aggregate types.
|
| 421 |
+
See http://llvm.org/docs/LangRef.html#t-aggregate
|
| 422 |
+
"""
|
| 423 |
+
|
| 424 |
+
def wrap_constant_value(self, values):
|
| 425 |
+
from . import Value, Constant
|
| 426 |
+
|
| 427 |
+
if not isinstance(values, (list, tuple)):
|
| 428 |
+
return values
|
| 429 |
+
if len(values) != len(self):
|
| 430 |
+
raise ValueError("wrong constant size for %s: got %d elements"
|
| 431 |
+
% (self, len(values)))
|
| 432 |
+
return [Constant(ty, val) if not isinstance(val, Value) else val
|
| 433 |
+
for ty, val in zip(self.elements, values)]
|
| 434 |
+
|
| 435 |
+
|
| 436 |
+
class ArrayType(Aggregate):
|
| 437 |
+
"""
|
| 438 |
+
The type for fixed-size homogenous arrays (e.g. "[f32 x 3]").
|
| 439 |
+
"""
|
| 440 |
+
|
| 441 |
+
def __init__(self, element, count):
|
| 442 |
+
self.element = element
|
| 443 |
+
self.count = count
|
| 444 |
+
|
| 445 |
+
@property
|
| 446 |
+
def elements(self):
|
| 447 |
+
return _Repeat(self.element, self.count)
|
| 448 |
+
|
| 449 |
+
def __len__(self):
|
| 450 |
+
return self.count
|
| 451 |
+
|
| 452 |
+
def _to_string(self):
|
| 453 |
+
return "[%d x %s]" % (self.count, self.element)
|
| 454 |
+
|
| 455 |
+
def __eq__(self, other):
|
| 456 |
+
if isinstance(other, ArrayType):
|
| 457 |
+
return self.element == other.element and self.count == other.count
|
| 458 |
+
|
| 459 |
+
def __hash__(self):
|
| 460 |
+
return hash(ArrayType)
|
| 461 |
+
|
| 462 |
+
def gep(self, i):
|
| 463 |
+
"""
|
| 464 |
+
Resolve the type of the i-th element (for getelementptr lookups).
|
| 465 |
+
"""
|
| 466 |
+
if not isinstance(i.type, IntType):
|
| 467 |
+
raise TypeError(i.type)
|
| 468 |
+
return self.element
|
| 469 |
+
|
| 470 |
+
def format_constant(self, value):
|
| 471 |
+
itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference())
|
| 472 |
+
for x in value])
|
| 473 |
+
return "[{0}]".format(itemstring)
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
class BaseStructType(Aggregate):
|
| 477 |
+
"""
|
| 478 |
+
The base type for heterogenous struct types.
|
| 479 |
+
"""
|
| 480 |
+
_packed = False
|
| 481 |
+
|
| 482 |
+
@property
|
| 483 |
+
def packed(self):
|
| 484 |
+
"""
|
| 485 |
+
A boolean attribute that indicates whether the structure uses
|
| 486 |
+
packed layout.
|
| 487 |
+
"""
|
| 488 |
+
return self._packed
|
| 489 |
+
|
| 490 |
+
@packed.setter
|
| 491 |
+
def packed(self, val):
|
| 492 |
+
self._packed = bool(val)
|
| 493 |
+
|
| 494 |
+
def __len__(self):
|
| 495 |
+
assert self.elements is not None
|
| 496 |
+
return len(self.elements)
|
| 497 |
+
|
| 498 |
+
def __iter__(self):
|
| 499 |
+
assert self.elements is not None
|
| 500 |
+
return iter(self.elements)
|
| 501 |
+
|
| 502 |
+
@property
|
| 503 |
+
def is_opaque(self):
|
| 504 |
+
return self.elements is None
|
| 505 |
+
|
| 506 |
+
def structure_repr(self):
|
| 507 |
+
"""
|
| 508 |
+
Return the LLVM IR for the structure representation
|
| 509 |
+
"""
|
| 510 |
+
ret = '{%s}' % ', '.join([str(x) for x in self.elements])
|
| 511 |
+
return self._wrap_packed(ret)
|
| 512 |
+
|
| 513 |
+
def format_constant(self, value):
|
| 514 |
+
itemstring = ", " .join(["{0} {1}".format(x.type, x.get_reference())
|
| 515 |
+
for x in value])
|
| 516 |
+
ret = "{{{0}}}".format(itemstring)
|
| 517 |
+
return self._wrap_packed(ret)
|
| 518 |
+
|
| 519 |
+
def gep(self, i):
|
| 520 |
+
"""
|
| 521 |
+
Resolve the type of the i-th element (for getelementptr lookups).
|
| 522 |
+
|
| 523 |
+
*i* needs to be a LLVM constant, so that the type can be determined
|
| 524 |
+
at compile-time.
|
| 525 |
+
"""
|
| 526 |
+
if not isinstance(i.type, IntType):
|
| 527 |
+
raise TypeError(i.type)
|
| 528 |
+
return self.elements[i.constant]
|
| 529 |
+
|
| 530 |
+
def _wrap_packed(self, textrepr):
|
| 531 |
+
"""
|
| 532 |
+
Internal helper to wrap textual repr of struct type into packed struct
|
| 533 |
+
"""
|
| 534 |
+
if self.packed:
|
| 535 |
+
return '<{}>'.format(textrepr)
|
| 536 |
+
else:
|
| 537 |
+
return textrepr
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
class LiteralStructType(BaseStructType):
|
| 541 |
+
"""
|
| 542 |
+
The type of "literal" structs, i.e. structs with a literally-defined
|
| 543 |
+
type (by contrast with IdentifiedStructType).
|
| 544 |
+
"""
|
| 545 |
+
|
| 546 |
+
null = 'zeroinitializer'
|
| 547 |
+
|
| 548 |
+
def __init__(self, elems, packed=False):
|
| 549 |
+
"""
|
| 550 |
+
*elems* is a sequence of types to be used as members.
|
| 551 |
+
*packed* controls the use of packed layout.
|
| 552 |
+
"""
|
| 553 |
+
self.elements = tuple(elems)
|
| 554 |
+
self.packed = packed
|
| 555 |
+
|
| 556 |
+
def _to_string(self):
|
| 557 |
+
return self.structure_repr()
|
| 558 |
+
|
| 559 |
+
def __eq__(self, other):
|
| 560 |
+
if isinstance(other, LiteralStructType):
|
| 561 |
+
return self.elements == other.elements
|
| 562 |
+
|
| 563 |
+
def __hash__(self):
|
| 564 |
+
return hash(LiteralStructType)
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class IdentifiedStructType(BaseStructType):
|
| 568 |
+
"""
|
| 569 |
+
A type which is a named alias for another struct type, akin to a typedef.
|
| 570 |
+
While literal struct types can be structurally equal (see
|
| 571 |
+
LiteralStructType), identified struct types are compared by name.
|
| 572 |
+
|
| 573 |
+
Do not use this directly.
|
| 574 |
+
"""
|
| 575 |
+
null = 'zeroinitializer'
|
| 576 |
+
|
| 577 |
+
def __init__(self, context, name, packed=False):
|
| 578 |
+
"""
|
| 579 |
+
*context* is a llvmlite.ir.Context.
|
| 580 |
+
*name* is the identifier for the new struct type.
|
| 581 |
+
*packed* controls the use of packed layout.
|
| 582 |
+
"""
|
| 583 |
+
assert name
|
| 584 |
+
self.context = context
|
| 585 |
+
self.name = name
|
| 586 |
+
self.elements = None
|
| 587 |
+
self.packed = packed
|
| 588 |
+
|
| 589 |
+
def _to_string(self):
|
| 590 |
+
return "%{name}".format(name=_wrapname(self.name))
|
| 591 |
+
|
| 592 |
+
def get_declaration(self):
|
| 593 |
+
"""
|
| 594 |
+
Returns the string for the declaration of the type
|
| 595 |
+
"""
|
| 596 |
+
if self.is_opaque:
|
| 597 |
+
out = "{strrep} = type opaque".format(strrep=str(self))
|
| 598 |
+
else:
|
| 599 |
+
out = "{strrep} = type {struct}".format(
|
| 600 |
+
strrep=str(self), struct=self.structure_repr())
|
| 601 |
+
return out
|
| 602 |
+
|
| 603 |
+
def __eq__(self, other):
|
| 604 |
+
if isinstance(other, IdentifiedStructType):
|
| 605 |
+
return self.name == other.name
|
| 606 |
+
|
| 607 |
+
def __hash__(self):
|
| 608 |
+
return hash(IdentifiedStructType)
|
| 609 |
+
|
| 610 |
+
def set_body(self, *elems):
|
| 611 |
+
if not self.is_opaque:
|
| 612 |
+
raise RuntimeError("{name} is already defined".format(
|
| 613 |
+
name=self.name))
|
| 614 |
+
self.elements = tuple(elems)
|
vllm/lib/python3.10/site-packages/llvmlite/ir/values.py
ADDED
|
@@ -0,0 +1,1217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Classes that are LLVM values: Value, Constant...
|
| 3 |
+
Instructions are in the instructions module.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import functools
|
| 7 |
+
import string
|
| 8 |
+
import re
|
| 9 |
+
from types import MappingProxyType
|
| 10 |
+
|
| 11 |
+
from llvmlite.ir import values, types, _utils
|
| 12 |
+
from llvmlite.ir._utils import (_StrCaching, _StringReferenceCaching,
|
| 13 |
+
_HasMetadata)
|
| 14 |
+
|
| 15 |
+
_VALID_CHARS = (frozenset(map(ord, string.ascii_letters)) |
|
| 16 |
+
frozenset(map(ord, string.digits)) |
|
| 17 |
+
frozenset(map(ord, ' !#$%&\'()*+,-./:;<=>?@[]^_`{|}~')))
|
| 18 |
+
|
| 19 |
+
_SIMPLE_IDENTIFIER_RE = re.compile(r"[-a-zA-Z$._][-a-zA-Z$._0-9]*$")
|
| 20 |
+
|
| 21 |
+
_CMP_MAP = {
|
| 22 |
+
'>': 'gt',
|
| 23 |
+
'<': 'lt',
|
| 24 |
+
'==': 'eq',
|
| 25 |
+
'!=': 'ne',
|
| 26 |
+
'>=': 'ge',
|
| 27 |
+
'<=': 'le',
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _escape_string(text, _map={}):
|
| 32 |
+
"""
|
| 33 |
+
Escape the given bytestring for safe use as a LLVM array constant.
|
| 34 |
+
Any unicode string input is first encoded with utf8 into bytes.
|
| 35 |
+
"""
|
| 36 |
+
if isinstance(text, str):
|
| 37 |
+
text = text.encode()
|
| 38 |
+
assert isinstance(text, (bytes, bytearray))
|
| 39 |
+
|
| 40 |
+
if not _map:
|
| 41 |
+
for ch in range(256):
|
| 42 |
+
if ch in _VALID_CHARS:
|
| 43 |
+
_map[ch] = chr(ch)
|
| 44 |
+
else:
|
| 45 |
+
_map[ch] = '\\%02x' % ch
|
| 46 |
+
|
| 47 |
+
buf = [_map[ch] for ch in text]
|
| 48 |
+
return ''.join(buf)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _binop(opname):
|
| 52 |
+
def wrap(fn):
|
| 53 |
+
@functools.wraps(fn)
|
| 54 |
+
def wrapped(lhs, rhs):
|
| 55 |
+
if lhs.type != rhs.type:
|
| 56 |
+
raise ValueError("Operands must be the same type, got (%s, %s)"
|
| 57 |
+
% (lhs.type, rhs.type))
|
| 58 |
+
|
| 59 |
+
fmt = "{0} ({1} {2}, {3} {4})".format(opname,
|
| 60 |
+
lhs.type, lhs.get_reference(),
|
| 61 |
+
rhs.type, rhs.get_reference())
|
| 62 |
+
return FormattedConstant(lhs.type, fmt)
|
| 63 |
+
|
| 64 |
+
return wrapped
|
| 65 |
+
return wrap
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _castop(opname):
|
| 69 |
+
def wrap(fn):
|
| 70 |
+
@functools.wraps(fn)
|
| 71 |
+
def wrapped(self, typ):
|
| 72 |
+
fn(self, typ)
|
| 73 |
+
if typ == self.type:
|
| 74 |
+
return self
|
| 75 |
+
|
| 76 |
+
op = "{0} ({1} {2} to {3})".format(opname, self.type,
|
| 77 |
+
self.get_reference(), typ)
|
| 78 |
+
return FormattedConstant(typ, op)
|
| 79 |
+
|
| 80 |
+
return wrapped
|
| 81 |
+
return wrap
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
class _ConstOpMixin(object):
|
| 85 |
+
"""
|
| 86 |
+
A mixin defining constant operations, for use in constant-like classes.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
#
|
| 90 |
+
# Arithmetic APIs
|
| 91 |
+
#
|
| 92 |
+
|
| 93 |
+
@_binop('shl')
|
| 94 |
+
def shl(self, other):
|
| 95 |
+
"""
|
| 96 |
+
Left integer shift:
|
| 97 |
+
lhs << rhs
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
@_binop('lshr')
|
| 101 |
+
def lshr(self, other):
|
| 102 |
+
"""
|
| 103 |
+
Logical (unsigned) right integer shift:
|
| 104 |
+
lhs >> rhs
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
@_binop('ashr')
|
| 108 |
+
def ashr(self, other):
|
| 109 |
+
"""
|
| 110 |
+
Arithmetic (signed) right integer shift:
|
| 111 |
+
lhs >> rhs
|
| 112 |
+
"""
|
| 113 |
+
|
| 114 |
+
@_binop('add')
|
| 115 |
+
def add(self, other):
|
| 116 |
+
"""
|
| 117 |
+
Integer addition:
|
| 118 |
+
lhs + rhs
|
| 119 |
+
"""
|
| 120 |
+
|
| 121 |
+
@_binop('fadd')
|
| 122 |
+
def fadd(self, other):
|
| 123 |
+
"""
|
| 124 |
+
Floating-point addition:
|
| 125 |
+
lhs + rhs
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
@_binop('sub')
|
| 129 |
+
def sub(self, other):
|
| 130 |
+
"""
|
| 131 |
+
Integer subtraction:
|
| 132 |
+
lhs - rhs
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
@_binop('fsub')
|
| 136 |
+
def fsub(self, other):
|
| 137 |
+
"""
|
| 138 |
+
Floating-point subtraction:
|
| 139 |
+
lhs - rhs
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
@_binop('mul')
|
| 143 |
+
def mul(self, other):
|
| 144 |
+
"""
|
| 145 |
+
Integer multiplication:
|
| 146 |
+
lhs * rhs
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
@_binop('fmul')
|
| 150 |
+
def fmul(self, other):
|
| 151 |
+
"""
|
| 152 |
+
Floating-point multiplication:
|
| 153 |
+
lhs * rhs
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
@_binop('udiv')
|
| 157 |
+
def udiv(self, other):
|
| 158 |
+
"""
|
| 159 |
+
Unsigned integer division:
|
| 160 |
+
lhs / rhs
|
| 161 |
+
"""
|
| 162 |
+
|
| 163 |
+
@_binop('sdiv')
|
| 164 |
+
def sdiv(self, other):
|
| 165 |
+
"""
|
| 166 |
+
Signed integer division:
|
| 167 |
+
lhs / rhs
|
| 168 |
+
"""
|
| 169 |
+
|
| 170 |
+
@_binop('fdiv')
|
| 171 |
+
def fdiv(self, other):
|
| 172 |
+
"""
|
| 173 |
+
Floating-point division:
|
| 174 |
+
lhs / rhs
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
@_binop('urem')
|
| 178 |
+
def urem(self, other):
|
| 179 |
+
"""
|
| 180 |
+
Unsigned integer remainder:
|
| 181 |
+
lhs % rhs
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
@_binop('srem')
|
| 185 |
+
def srem(self, other):
|
| 186 |
+
"""
|
| 187 |
+
Signed integer remainder:
|
| 188 |
+
lhs % rhs
|
| 189 |
+
"""
|
| 190 |
+
|
| 191 |
+
@_binop('frem')
|
| 192 |
+
def frem(self, other):
|
| 193 |
+
"""
|
| 194 |
+
Floating-point remainder:
|
| 195 |
+
lhs % rhs
|
| 196 |
+
"""
|
| 197 |
+
|
| 198 |
+
@_binop('or')
|
| 199 |
+
def or_(self, other):
|
| 200 |
+
"""
|
| 201 |
+
Bitwise integer OR:
|
| 202 |
+
lhs | rhs
|
| 203 |
+
"""
|
| 204 |
+
|
| 205 |
+
@_binop('and')
|
| 206 |
+
def and_(self, other):
|
| 207 |
+
"""
|
| 208 |
+
Bitwise integer AND:
|
| 209 |
+
lhs & rhs
|
| 210 |
+
"""
|
| 211 |
+
|
| 212 |
+
@_binop('xor')
|
| 213 |
+
def xor(self, other):
|
| 214 |
+
"""
|
| 215 |
+
Bitwise integer XOR:
|
| 216 |
+
lhs ^ rhs
|
| 217 |
+
"""
|
| 218 |
+
|
| 219 |
+
def _cmp(self, prefix, sign, cmpop, other):
|
| 220 |
+
ins = prefix + 'cmp'
|
| 221 |
+
try:
|
| 222 |
+
op = _CMP_MAP[cmpop]
|
| 223 |
+
except KeyError:
|
| 224 |
+
raise ValueError("invalid comparison %r for %s" % (cmpop, ins))
|
| 225 |
+
|
| 226 |
+
if not (prefix == 'i' and cmpop in ('==', '!=')):
|
| 227 |
+
op = sign + op
|
| 228 |
+
|
| 229 |
+
if self.type != other.type:
|
| 230 |
+
raise ValueError("Operands must be the same type, got (%s, %s)"
|
| 231 |
+
% (self.type, other.type))
|
| 232 |
+
|
| 233 |
+
fmt = "{0} {1} ({2} {3}, {4} {5})".format(
|
| 234 |
+
ins, op,
|
| 235 |
+
self.type, self.get_reference(),
|
| 236 |
+
other.type, other.get_reference())
|
| 237 |
+
|
| 238 |
+
return FormattedConstant(types.IntType(1), fmt)
|
| 239 |
+
|
| 240 |
+
def icmp_signed(self, cmpop, other):
|
| 241 |
+
"""
|
| 242 |
+
Signed integer comparison:
|
| 243 |
+
lhs <cmpop> rhs
|
| 244 |
+
|
| 245 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>='
|
| 246 |
+
"""
|
| 247 |
+
return self._cmp('i', 's', cmpop, other)
|
| 248 |
+
|
| 249 |
+
def icmp_unsigned(self, cmpop, other):
|
| 250 |
+
"""
|
| 251 |
+
Unsigned integer (or pointer) comparison:
|
| 252 |
+
lhs <cmpop> rhs
|
| 253 |
+
|
| 254 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>='
|
| 255 |
+
"""
|
| 256 |
+
return self._cmp('i', 'u', cmpop, other)
|
| 257 |
+
|
| 258 |
+
def fcmp_ordered(self, cmpop, other):
|
| 259 |
+
"""
|
| 260 |
+
Floating-point ordered comparison:
|
| 261 |
+
lhs <cmpop> rhs
|
| 262 |
+
|
| 263 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
|
| 264 |
+
"""
|
| 265 |
+
return self._cmp('f', 'o', cmpop, other)
|
| 266 |
+
|
| 267 |
+
def fcmp_unordered(self, cmpop, other):
|
| 268 |
+
"""
|
| 269 |
+
Floating-point unordered comparison:
|
| 270 |
+
lhs <cmpop> rhs
|
| 271 |
+
|
| 272 |
+
where cmpop can be '==', '!=', '<', '<=', '>', '>=', 'ord', 'uno'
|
| 273 |
+
"""
|
| 274 |
+
return self._cmp('f', 'u', cmpop, other)
|
| 275 |
+
|
| 276 |
+
#
|
| 277 |
+
# Unary APIs
|
| 278 |
+
#
|
| 279 |
+
|
| 280 |
+
def not_(self):
|
| 281 |
+
"""
|
| 282 |
+
Bitwise integer complement:
|
| 283 |
+
~value
|
| 284 |
+
"""
|
| 285 |
+
if isinstance(self.type, types.VectorType):
|
| 286 |
+
rhs = values.Constant(self.type, (-1,) * self.type.count)
|
| 287 |
+
else:
|
| 288 |
+
rhs = values.Constant(self.type, -1)
|
| 289 |
+
|
| 290 |
+
return self.xor(rhs)
|
| 291 |
+
|
| 292 |
+
def neg(self):
|
| 293 |
+
"""
|
| 294 |
+
Integer negative:
|
| 295 |
+
-value
|
| 296 |
+
"""
|
| 297 |
+
zero = values.Constant(self.type, 0)
|
| 298 |
+
return zero.sub(self)
|
| 299 |
+
|
| 300 |
+
def fneg(self):
|
| 301 |
+
"""
|
| 302 |
+
Floating-point negative:
|
| 303 |
+
-value
|
| 304 |
+
"""
|
| 305 |
+
fmt = "fneg ({0} {1})".format(self.type, self.get_reference())
|
| 306 |
+
return FormattedConstant(self.type, fmt)
|
| 307 |
+
|
| 308 |
+
#
|
| 309 |
+
# Cast APIs
|
| 310 |
+
#
|
| 311 |
+
|
| 312 |
+
@_castop('trunc')
|
| 313 |
+
def trunc(self, typ):
|
| 314 |
+
"""
|
| 315 |
+
Truncating integer downcast to a smaller type.
|
| 316 |
+
"""
|
| 317 |
+
|
| 318 |
+
@_castop('zext')
|
| 319 |
+
def zext(self, typ):
|
| 320 |
+
"""
|
| 321 |
+
Zero-extending integer upcast to a larger type
|
| 322 |
+
"""
|
| 323 |
+
|
| 324 |
+
@_castop('sext')
|
| 325 |
+
def sext(self, typ):
|
| 326 |
+
"""
|
| 327 |
+
Sign-extending integer upcast to a larger type.
|
| 328 |
+
"""
|
| 329 |
+
|
| 330 |
+
@_castop('fptrunc')
|
| 331 |
+
def fptrunc(self, typ):
|
| 332 |
+
"""
|
| 333 |
+
Floating-point downcast to a less precise type.
|
| 334 |
+
"""
|
| 335 |
+
|
| 336 |
+
@_castop('fpext')
|
| 337 |
+
def fpext(self, typ):
|
| 338 |
+
"""
|
| 339 |
+
Floating-point upcast to a more precise type.
|
| 340 |
+
"""
|
| 341 |
+
|
| 342 |
+
@_castop('bitcast')
|
| 343 |
+
def bitcast(self, typ):
|
| 344 |
+
"""
|
| 345 |
+
Pointer cast to a different pointer type.
|
| 346 |
+
"""
|
| 347 |
+
|
| 348 |
+
@_castop('fptoui')
|
| 349 |
+
def fptoui(self, typ):
|
| 350 |
+
"""
|
| 351 |
+
Convert floating-point to unsigned integer.
|
| 352 |
+
"""
|
| 353 |
+
|
| 354 |
+
@_castop('uitofp')
|
| 355 |
+
def uitofp(self, typ):
|
| 356 |
+
"""
|
| 357 |
+
Convert unsigned integer to floating-point.
|
| 358 |
+
"""
|
| 359 |
+
|
| 360 |
+
@_castop('fptosi')
|
| 361 |
+
def fptosi(self, typ):
|
| 362 |
+
"""
|
| 363 |
+
Convert floating-point to signed integer.
|
| 364 |
+
"""
|
| 365 |
+
|
| 366 |
+
@_castop('sitofp')
|
| 367 |
+
def sitofp(self, typ):
|
| 368 |
+
"""
|
| 369 |
+
Convert signed integer to floating-point.
|
| 370 |
+
"""
|
| 371 |
+
|
| 372 |
+
@_castop('ptrtoint')
|
| 373 |
+
def ptrtoint(self, typ):
|
| 374 |
+
"""
|
| 375 |
+
Cast pointer to integer.
|
| 376 |
+
"""
|
| 377 |
+
if not isinstance(self.type, types.PointerType):
|
| 378 |
+
msg = "can only call ptrtoint() on pointer type, not '%s'"
|
| 379 |
+
raise TypeError(msg % (self.type,))
|
| 380 |
+
if not isinstance(typ, types.IntType):
|
| 381 |
+
raise TypeError("can only ptrtoint() to integer type, not '%s'"
|
| 382 |
+
% (typ,))
|
| 383 |
+
|
| 384 |
+
@_castop('inttoptr')
|
| 385 |
+
def inttoptr(self, typ):
|
| 386 |
+
"""
|
| 387 |
+
Cast integer to pointer.
|
| 388 |
+
"""
|
| 389 |
+
if not isinstance(self.type, types.IntType):
|
| 390 |
+
msg = "can only call inttoptr() on integer constants, not '%s'"
|
| 391 |
+
raise TypeError(msg % (self.type,))
|
| 392 |
+
if not isinstance(typ, types.PointerType):
|
| 393 |
+
raise TypeError("can only inttoptr() to pointer type, not '%s'"
|
| 394 |
+
% (typ,))
|
| 395 |
+
|
| 396 |
+
def gep(self, indices):
|
| 397 |
+
"""
|
| 398 |
+
Call getelementptr on this pointer constant.
|
| 399 |
+
"""
|
| 400 |
+
if not isinstance(self.type, types.PointerType):
|
| 401 |
+
raise TypeError("can only call gep() on pointer constants, not '%s'"
|
| 402 |
+
% (self.type,))
|
| 403 |
+
|
| 404 |
+
outtype = self.type
|
| 405 |
+
for i in indices:
|
| 406 |
+
outtype = outtype.gep(i)
|
| 407 |
+
|
| 408 |
+
strindices = ["{0} {1}".format(idx.type, idx.get_reference())
|
| 409 |
+
for idx in indices]
|
| 410 |
+
|
| 411 |
+
op = "getelementptr ({0}, {1} {2}, {3})".format(
|
| 412 |
+
self.type.pointee, self.type,
|
| 413 |
+
self.get_reference(), ', '.join(strindices))
|
| 414 |
+
return FormattedConstant(outtype.as_pointer(self.addrspace), op)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
class Value(object):
|
| 418 |
+
"""
|
| 419 |
+
The base class for all values.
|
| 420 |
+
"""
|
| 421 |
+
|
| 422 |
+
def __repr__(self):
|
| 423 |
+
return "<ir.%s type='%s' ...>" % (self.__class__.__name__, self.type,)
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
class _Undefined(object):
|
| 427 |
+
"""
|
| 428 |
+
'undef': a value for undefined values.
|
| 429 |
+
"""
|
| 430 |
+
def __new__(cls):
|
| 431 |
+
try:
|
| 432 |
+
return Undefined
|
| 433 |
+
except NameError:
|
| 434 |
+
return object.__new__(_Undefined)
|
| 435 |
+
|
| 436 |
+
|
| 437 |
+
Undefined = _Undefined()
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
class Constant(_StrCaching, _StringReferenceCaching, _ConstOpMixin, Value):
|
| 441 |
+
"""
|
| 442 |
+
A constant LLVM value.
|
| 443 |
+
"""
|
| 444 |
+
|
| 445 |
+
def __init__(self, typ, constant):
|
| 446 |
+
assert isinstance(typ, types.Type)
|
| 447 |
+
assert not isinstance(typ, types.VoidType)
|
| 448 |
+
self.type = typ
|
| 449 |
+
constant = typ.wrap_constant_value(constant)
|
| 450 |
+
self.constant = constant
|
| 451 |
+
|
| 452 |
+
def _to_string(self):
|
| 453 |
+
return '{0} {1}'.format(self.type, self.get_reference())
|
| 454 |
+
|
| 455 |
+
def _get_reference(self):
|
| 456 |
+
if self.constant is None:
|
| 457 |
+
val = self.type.null
|
| 458 |
+
|
| 459 |
+
elif self.constant is Undefined:
|
| 460 |
+
val = "undef"
|
| 461 |
+
|
| 462 |
+
elif isinstance(self.constant, bytearray):
|
| 463 |
+
val = 'c"{0}"'.format(_escape_string(self.constant))
|
| 464 |
+
|
| 465 |
+
else:
|
| 466 |
+
val = self.type.format_constant(self.constant)
|
| 467 |
+
|
| 468 |
+
return val
|
| 469 |
+
|
| 470 |
+
@classmethod
|
| 471 |
+
def literal_array(cls, elems):
|
| 472 |
+
"""
|
| 473 |
+
Construct a literal array constant made of the given members.
|
| 474 |
+
"""
|
| 475 |
+
tys = [el.type for el in elems]
|
| 476 |
+
if len(tys) == 0:
|
| 477 |
+
raise ValueError("need at least one element")
|
| 478 |
+
ty = tys[0]
|
| 479 |
+
for other in tys:
|
| 480 |
+
if ty != other:
|
| 481 |
+
raise TypeError("all elements must have the same type")
|
| 482 |
+
return cls(types.ArrayType(ty, len(elems)), elems)
|
| 483 |
+
|
| 484 |
+
@classmethod
|
| 485 |
+
def literal_struct(cls, elems):
|
| 486 |
+
"""
|
| 487 |
+
Construct a literal structure constant made of the given members.
|
| 488 |
+
"""
|
| 489 |
+
tys = [el.type for el in elems]
|
| 490 |
+
return cls(types.LiteralStructType(tys), elems)
|
| 491 |
+
|
| 492 |
+
@property
|
| 493 |
+
def addrspace(self):
|
| 494 |
+
if not isinstance(self.type, types.PointerType):
|
| 495 |
+
raise TypeError("Only pointer constant have address spaces")
|
| 496 |
+
return self.type.addrspace
|
| 497 |
+
|
| 498 |
+
def __eq__(self, other):
|
| 499 |
+
if isinstance(other, Constant):
|
| 500 |
+
return str(self) == str(other)
|
| 501 |
+
else:
|
| 502 |
+
return False
|
| 503 |
+
|
| 504 |
+
def __ne__(self, other):
|
| 505 |
+
return not self.__eq__(other)
|
| 506 |
+
|
| 507 |
+
def __hash__(self):
|
| 508 |
+
return hash(str(self))
|
| 509 |
+
|
| 510 |
+
def __repr__(self):
|
| 511 |
+
return "<ir.Constant type='%s' value=%r>" % (self.type, self.constant)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
class FormattedConstant(Constant):
|
| 515 |
+
"""
|
| 516 |
+
A constant with an already formatted IR representation.
|
| 517 |
+
"""
|
| 518 |
+
|
| 519 |
+
def __init__(self, typ, constant):
|
| 520 |
+
assert isinstance(constant, str)
|
| 521 |
+
Constant.__init__(self, typ, constant)
|
| 522 |
+
|
| 523 |
+
def _to_string(self):
|
| 524 |
+
return self.constant
|
| 525 |
+
|
| 526 |
+
def _get_reference(self):
|
| 527 |
+
return self.constant
|
| 528 |
+
|
| 529 |
+
|
| 530 |
+
class NamedValue(_StrCaching, _StringReferenceCaching, Value):
|
| 531 |
+
"""
|
| 532 |
+
The base class for named values.
|
| 533 |
+
"""
|
| 534 |
+
name_prefix = '%'
|
| 535 |
+
deduplicate_name = True
|
| 536 |
+
|
| 537 |
+
def __init__(self, parent, type, name):
|
| 538 |
+
assert parent is not None
|
| 539 |
+
assert isinstance(type, types.Type)
|
| 540 |
+
self.parent = parent
|
| 541 |
+
self.type = type
|
| 542 |
+
self._set_name(name)
|
| 543 |
+
|
| 544 |
+
def _to_string(self):
|
| 545 |
+
buf = []
|
| 546 |
+
if not isinstance(self.type, types.VoidType):
|
| 547 |
+
buf.append("{0} = ".format(self.get_reference()))
|
| 548 |
+
self.descr(buf)
|
| 549 |
+
return "".join(buf).rstrip()
|
| 550 |
+
|
| 551 |
+
def descr(self, buf):
|
| 552 |
+
raise NotImplementedError
|
| 553 |
+
|
| 554 |
+
def _get_name(self):
|
| 555 |
+
return self._name
|
| 556 |
+
|
| 557 |
+
def _set_name(self, name):
|
| 558 |
+
name = self.parent.scope.register(name,
|
| 559 |
+
deduplicate=self.deduplicate_name)
|
| 560 |
+
self._name = name
|
| 561 |
+
|
| 562 |
+
name = property(_get_name, _set_name)
|
| 563 |
+
|
| 564 |
+
def _get_reference(self):
|
| 565 |
+
name = self.name
|
| 566 |
+
# Quote and escape value name
|
| 567 |
+
if '\\' in name or '"' in name:
|
| 568 |
+
name = name.replace('\\', '\\5c').replace('"', '\\22')
|
| 569 |
+
return '{0}"{1}"'.format(self.name_prefix, name)
|
| 570 |
+
|
| 571 |
+
def __repr__(self):
|
| 572 |
+
return "<ir.%s %r of type '%s'>" % (
|
| 573 |
+
self.__class__.__name__, self.name, self.type)
|
| 574 |
+
|
| 575 |
+
@property
|
| 576 |
+
def function_type(self):
|
| 577 |
+
ty = self.type
|
| 578 |
+
if isinstance(ty, types.PointerType):
|
| 579 |
+
ty = self.type.pointee
|
| 580 |
+
if isinstance(ty, types.FunctionType):
|
| 581 |
+
return ty
|
| 582 |
+
else:
|
| 583 |
+
raise TypeError("Not a function: {0}".format(self.type))
|
| 584 |
+
|
| 585 |
+
|
| 586 |
+
class MetaDataString(NamedValue):
|
| 587 |
+
"""
|
| 588 |
+
A metadata string, i.e. a constant string used as a value in a metadata
|
| 589 |
+
node.
|
| 590 |
+
"""
|
| 591 |
+
|
| 592 |
+
def __init__(self, parent, string):
|
| 593 |
+
super(MetaDataString, self).__init__(parent,
|
| 594 |
+
types.MetaDataType(),
|
| 595 |
+
name="")
|
| 596 |
+
self.string = string
|
| 597 |
+
|
| 598 |
+
def descr(self, buf):
|
| 599 |
+
buf += (self.get_reference(), "\n")
|
| 600 |
+
|
| 601 |
+
def _get_reference(self):
|
| 602 |
+
return '!"{0}"'.format(_escape_string(self.string))
|
| 603 |
+
|
| 604 |
+
_to_string = _get_reference
|
| 605 |
+
|
| 606 |
+
def __eq__(self, other):
|
| 607 |
+
if isinstance(other, MetaDataString):
|
| 608 |
+
return self.string == other.string
|
| 609 |
+
else:
|
| 610 |
+
return False
|
| 611 |
+
|
| 612 |
+
def __ne__(self, other):
|
| 613 |
+
return not self.__eq__(other)
|
| 614 |
+
|
| 615 |
+
def __hash__(self):
|
| 616 |
+
return hash(self.string)
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
class MetaDataArgument(_StrCaching, _StringReferenceCaching, Value):
|
| 620 |
+
"""
|
| 621 |
+
An argument value to a function taking metadata arguments.
|
| 622 |
+
This can wrap any other kind of LLVM value.
|
| 623 |
+
|
| 624 |
+
Do not instantiate directly, Builder.call() will create these
|
| 625 |
+
automatically.
|
| 626 |
+
"""
|
| 627 |
+
|
| 628 |
+
def __init__(self, value):
|
| 629 |
+
assert isinstance(value, Value)
|
| 630 |
+
assert not isinstance(value.type, types.MetaDataType)
|
| 631 |
+
self.type = types.MetaDataType()
|
| 632 |
+
self.wrapped_value = value
|
| 633 |
+
|
| 634 |
+
def _get_reference(self):
|
| 635 |
+
# e.g. "i32* %2"
|
| 636 |
+
return "{0} {1}".format(self.wrapped_value.type,
|
| 637 |
+
self.wrapped_value.get_reference())
|
| 638 |
+
|
| 639 |
+
_to_string = _get_reference
|
| 640 |
+
|
| 641 |
+
|
| 642 |
+
class NamedMetaData(object):
|
| 643 |
+
"""
|
| 644 |
+
A named metadata node.
|
| 645 |
+
|
| 646 |
+
Do not instantiate directly, use Module.add_named_metadata() instead.
|
| 647 |
+
"""
|
| 648 |
+
|
| 649 |
+
def __init__(self, parent):
|
| 650 |
+
self.parent = parent
|
| 651 |
+
self.operands = []
|
| 652 |
+
|
| 653 |
+
def add(self, md):
|
| 654 |
+
self.operands.append(md)
|
| 655 |
+
|
| 656 |
+
|
| 657 |
+
class MDValue(NamedValue):
|
| 658 |
+
"""
|
| 659 |
+
A metadata node's value, consisting of a sequence of elements ("operands").
|
| 660 |
+
|
| 661 |
+
Do not instantiate directly, use Module.add_metadata() instead.
|
| 662 |
+
"""
|
| 663 |
+
name_prefix = '!'
|
| 664 |
+
|
| 665 |
+
def __init__(self, parent, values, name):
|
| 666 |
+
super(MDValue, self).__init__(parent,
|
| 667 |
+
types.MetaDataType(),
|
| 668 |
+
name=name)
|
| 669 |
+
self.operands = tuple(values)
|
| 670 |
+
parent.metadata.append(self)
|
| 671 |
+
|
| 672 |
+
def descr(self, buf):
|
| 673 |
+
operands = []
|
| 674 |
+
for op in self.operands:
|
| 675 |
+
if isinstance(op.type, types.MetaDataType):
|
| 676 |
+
if isinstance(op, Constant) and op.constant is None:
|
| 677 |
+
operands.append("null")
|
| 678 |
+
else:
|
| 679 |
+
operands.append(op.get_reference())
|
| 680 |
+
else:
|
| 681 |
+
operands.append("{0} {1}".format(op.type, op.get_reference()))
|
| 682 |
+
operands = ', '.join(operands)
|
| 683 |
+
buf += ("!{{ {0} }}".format(operands), "\n")
|
| 684 |
+
|
| 685 |
+
def _get_reference(self):
|
| 686 |
+
return self.name_prefix + str(self.name)
|
| 687 |
+
|
| 688 |
+
def __eq__(self, other):
|
| 689 |
+
if isinstance(other, MDValue):
|
| 690 |
+
return self.operands == other.operands
|
| 691 |
+
else:
|
| 692 |
+
return False
|
| 693 |
+
|
| 694 |
+
def __ne__(self, other):
|
| 695 |
+
return not self.__eq__(other)
|
| 696 |
+
|
| 697 |
+
def __hash__(self):
|
| 698 |
+
return hash(self.operands)
|
| 699 |
+
|
| 700 |
+
|
| 701 |
+
class DIToken:
|
| 702 |
+
"""
|
| 703 |
+
A debug information enumeration value that should appear bare in
|
| 704 |
+
the emitted metadata.
|
| 705 |
+
|
| 706 |
+
Use this to wrap known constants, e.g. the DW_* enumerations.
|
| 707 |
+
"""
|
| 708 |
+
|
| 709 |
+
def __init__(self, value):
|
| 710 |
+
self.value = value
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
class DIValue(NamedValue):
|
| 714 |
+
"""
|
| 715 |
+
A debug information descriptor, containing key-value pairs.
|
| 716 |
+
|
| 717 |
+
Do not instantiate directly, use Module.add_debug_info() instead.
|
| 718 |
+
"""
|
| 719 |
+
name_prefix = '!'
|
| 720 |
+
|
| 721 |
+
def __init__(self, parent, is_distinct, kind, operands, name):
|
| 722 |
+
super(DIValue, self).__init__(parent,
|
| 723 |
+
types.MetaDataType(),
|
| 724 |
+
name=name)
|
| 725 |
+
self.is_distinct = is_distinct
|
| 726 |
+
self.kind = kind
|
| 727 |
+
self.operands = tuple(operands)
|
| 728 |
+
parent.metadata.append(self)
|
| 729 |
+
|
| 730 |
+
def descr(self, buf):
|
| 731 |
+
if self.is_distinct:
|
| 732 |
+
buf += ("distinct ",)
|
| 733 |
+
operands = []
|
| 734 |
+
for key, value in self.operands:
|
| 735 |
+
if value is None:
|
| 736 |
+
strvalue = "null"
|
| 737 |
+
elif value is True:
|
| 738 |
+
strvalue = "true"
|
| 739 |
+
elif value is False:
|
| 740 |
+
strvalue = "false"
|
| 741 |
+
elif isinstance(value, DIToken):
|
| 742 |
+
strvalue = value.value
|
| 743 |
+
elif isinstance(value, str):
|
| 744 |
+
strvalue = '"{}"'.format(_escape_string(value))
|
| 745 |
+
elif isinstance(value, int):
|
| 746 |
+
strvalue = str(value)
|
| 747 |
+
elif isinstance(value, NamedValue):
|
| 748 |
+
strvalue = value.get_reference()
|
| 749 |
+
else:
|
| 750 |
+
raise TypeError("invalid operand type for debug info: %r"
|
| 751 |
+
% (value,))
|
| 752 |
+
operands.append("{0}: {1}".format(key, strvalue))
|
| 753 |
+
operands = ', '.join(operands)
|
| 754 |
+
buf += ("!", self.kind, "(", operands, ")\n")
|
| 755 |
+
|
| 756 |
+
def _get_reference(self):
|
| 757 |
+
return self.name_prefix + str(self.name)
|
| 758 |
+
|
| 759 |
+
def __eq__(self, other):
|
| 760 |
+
if isinstance(other, DIValue):
|
| 761 |
+
return self.is_distinct == other.is_distinct and \
|
| 762 |
+
self.kind == other.kind and \
|
| 763 |
+
self.operands == other.operands
|
| 764 |
+
else:
|
| 765 |
+
return False
|
| 766 |
+
|
| 767 |
+
def __ne__(self, other):
|
| 768 |
+
return not self.__eq__(other)
|
| 769 |
+
|
| 770 |
+
def __hash__(self):
|
| 771 |
+
return hash((self.is_distinct, self.kind, self.operands))
|
| 772 |
+
|
| 773 |
+
|
| 774 |
+
class GlobalValue(NamedValue, _ConstOpMixin, _HasMetadata):
|
| 775 |
+
"""
|
| 776 |
+
A global value.
|
| 777 |
+
"""
|
| 778 |
+
name_prefix = '@'
|
| 779 |
+
deduplicate_name = False
|
| 780 |
+
|
| 781 |
+
def __init__(self, *args, **kwargs):
|
| 782 |
+
super(GlobalValue, self).__init__(*args, **kwargs)
|
| 783 |
+
self.linkage = ''
|
| 784 |
+
self.storage_class = ''
|
| 785 |
+
self.section = ''
|
| 786 |
+
self.metadata = {}
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
class GlobalVariable(GlobalValue):
|
| 790 |
+
"""
|
| 791 |
+
A global variable.
|
| 792 |
+
"""
|
| 793 |
+
|
| 794 |
+
def __init__(self, module, typ, name, addrspace=0):
|
| 795 |
+
assert isinstance(typ, types.Type)
|
| 796 |
+
super(GlobalVariable, self).__init__(module, typ.as_pointer(addrspace),
|
| 797 |
+
name=name)
|
| 798 |
+
self.value_type = typ
|
| 799 |
+
self.initializer = None
|
| 800 |
+
self.unnamed_addr = False
|
| 801 |
+
self.global_constant = False
|
| 802 |
+
self.addrspace = addrspace
|
| 803 |
+
self.align = None
|
| 804 |
+
self.parent.add_global(self)
|
| 805 |
+
|
| 806 |
+
def descr(self, buf):
|
| 807 |
+
if self.global_constant:
|
| 808 |
+
kind = 'constant'
|
| 809 |
+
else:
|
| 810 |
+
kind = 'global'
|
| 811 |
+
|
| 812 |
+
if not self.linkage:
|
| 813 |
+
# Default to external linkage
|
| 814 |
+
linkage = 'external' if self.initializer is None else ''
|
| 815 |
+
else:
|
| 816 |
+
linkage = self.linkage
|
| 817 |
+
|
| 818 |
+
if linkage:
|
| 819 |
+
buf.append(linkage + " ")
|
| 820 |
+
if self.storage_class:
|
| 821 |
+
buf.append(self.storage_class + " ")
|
| 822 |
+
if self.unnamed_addr:
|
| 823 |
+
buf.append("unnamed_addr ")
|
| 824 |
+
if self.addrspace != 0:
|
| 825 |
+
buf.append('addrspace({0:d}) '.format(self.addrspace))
|
| 826 |
+
|
| 827 |
+
buf.append("{kind} {type}" .format(kind=kind, type=self.value_type))
|
| 828 |
+
|
| 829 |
+
if self.initializer is not None:
|
| 830 |
+
if self.initializer.type != self.value_type:
|
| 831 |
+
raise TypeError("got initializer of type %s "
|
| 832 |
+
"for global value type %s"
|
| 833 |
+
% (self.initializer.type, self.value_type))
|
| 834 |
+
buf.append(" " + self.initializer.get_reference())
|
| 835 |
+
elif linkage not in ('external', 'extern_weak'):
|
| 836 |
+
# emit 'undef' for non-external linkage GV
|
| 837 |
+
buf.append(" " + self.value_type(Undefined).get_reference())
|
| 838 |
+
|
| 839 |
+
if self.section:
|
| 840 |
+
buf.append(", section \"%s\"" % (self.section,))
|
| 841 |
+
|
| 842 |
+
if self.align is not None:
|
| 843 |
+
buf.append(", align %d" % (self.align,))
|
| 844 |
+
|
| 845 |
+
if self.metadata:
|
| 846 |
+
buf.append(self._stringify_metadata(leading_comma=True))
|
| 847 |
+
|
| 848 |
+
buf.append("\n")
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
class AttributeSet(set):
|
| 852 |
+
"""A set of string attribute.
|
| 853 |
+
Only accept items listed in *_known*.
|
| 854 |
+
|
| 855 |
+
Properties:
|
| 856 |
+
* Iterate in sorted order
|
| 857 |
+
"""
|
| 858 |
+
_known = ()
|
| 859 |
+
|
| 860 |
+
def __init__(self, args=()):
|
| 861 |
+
super().__init__()
|
| 862 |
+
if isinstance(args, str):
|
| 863 |
+
args = [args]
|
| 864 |
+
for name in args:
|
| 865 |
+
self.add(name)
|
| 866 |
+
|
| 867 |
+
def _expand(self, name, typ):
|
| 868 |
+
return name
|
| 869 |
+
|
| 870 |
+
def add(self, name):
|
| 871 |
+
if name not in self._known:
|
| 872 |
+
raise ValueError('unknown attr {!r} for {}'.format(name, self))
|
| 873 |
+
return super(AttributeSet, self).add(name)
|
| 874 |
+
|
| 875 |
+
def _to_list(self, typ):
|
| 876 |
+
return [self._expand(i, typ) for i in sorted(self)]
|
| 877 |
+
|
| 878 |
+
|
| 879 |
+
class FunctionAttributes(AttributeSet):
|
| 880 |
+
_known = frozenset([
|
| 881 |
+
'argmemonly', 'alwaysinline', 'builtin', 'cold', 'convergent',
|
| 882 |
+
'inaccessiblememonly', 'inaccessiblemem_or_argmemonly', 'inlinehint',
|
| 883 |
+
'jumptable', 'minsize', 'naked', 'nobuiltin', 'noduplicate',
|
| 884 |
+
'noimplicitfloat', 'noinline', 'nonlazybind', 'norecurse',
|
| 885 |
+
'noredzone', 'noreturn', 'nounwind', 'optnone', 'optsize',
|
| 886 |
+
'readnone', 'readonly', 'returns_twice', 'sanitize_address',
|
| 887 |
+
'sanitize_memory', 'sanitize_thread', 'ssp',
|
| 888 |
+
'sspreg', 'sspstrong', 'uwtable'])
|
| 889 |
+
|
| 890 |
+
def __init__(self, args=()):
|
| 891 |
+
self._alignstack = 0
|
| 892 |
+
self._personality = None
|
| 893 |
+
super(FunctionAttributes, self).__init__(args)
|
| 894 |
+
|
| 895 |
+
def add(self, name):
|
| 896 |
+
if ((name == 'alwaysinline' and 'noinline' in self) or
|
| 897 |
+
(name == 'noinline' and 'alwaysinline' in self)):
|
| 898 |
+
raise ValueError("Can't have alwaysinline and noinline")
|
| 899 |
+
|
| 900 |
+
super().add(name)
|
| 901 |
+
|
| 902 |
+
@property
|
| 903 |
+
def alignstack(self):
|
| 904 |
+
return self._alignstack
|
| 905 |
+
|
| 906 |
+
@alignstack.setter
|
| 907 |
+
def alignstack(self, val):
|
| 908 |
+
assert val >= 0
|
| 909 |
+
self._alignstack = val
|
| 910 |
+
|
| 911 |
+
@property
|
| 912 |
+
def personality(self):
|
| 913 |
+
return self._personality
|
| 914 |
+
|
| 915 |
+
@personality.setter
|
| 916 |
+
def personality(self, val):
|
| 917 |
+
assert val is None or isinstance(val, GlobalValue)
|
| 918 |
+
self._personality = val
|
| 919 |
+
|
| 920 |
+
def _to_list(self, ret_type):
|
| 921 |
+
attrs = super()._to_list(ret_type)
|
| 922 |
+
if self.alignstack:
|
| 923 |
+
attrs.append('alignstack({0:d})'.format(self.alignstack))
|
| 924 |
+
if self.personality:
|
| 925 |
+
attrs.append('personality {persty} {persfn}'.format(
|
| 926 |
+
persty=self.personality.type,
|
| 927 |
+
persfn=self.personality.get_reference()))
|
| 928 |
+
return attrs
|
| 929 |
+
|
| 930 |
+
|
| 931 |
+
class Function(GlobalValue):
|
| 932 |
+
"""Represent a LLVM Function but does uses a Module as parent.
|
| 933 |
+
Global Values are stored as a set of dependencies (attribute `depends`).
|
| 934 |
+
"""
|
| 935 |
+
|
| 936 |
+
def __init__(self, module, ftype, name):
|
| 937 |
+
assert isinstance(ftype, types.Type)
|
| 938 |
+
super(Function, self).__init__(module, ftype.as_pointer(), name=name)
|
| 939 |
+
self.ftype = ftype
|
| 940 |
+
self.scope = _utils.NameScope()
|
| 941 |
+
self.blocks = []
|
| 942 |
+
self.attributes = FunctionAttributes()
|
| 943 |
+
self.args = tuple([Argument(self, t)
|
| 944 |
+
for t in ftype.args])
|
| 945 |
+
self.return_value = ReturnValue(self, ftype.return_type)
|
| 946 |
+
self.parent.add_global(self)
|
| 947 |
+
self.calling_convention = ''
|
| 948 |
+
|
| 949 |
+
@property
|
| 950 |
+
def module(self):
|
| 951 |
+
return self.parent
|
| 952 |
+
|
| 953 |
+
@property
|
| 954 |
+
def entry_basic_block(self):
|
| 955 |
+
return self.blocks[0]
|
| 956 |
+
|
| 957 |
+
@property
|
| 958 |
+
def basic_blocks(self):
|
| 959 |
+
return self.blocks
|
| 960 |
+
|
| 961 |
+
def append_basic_block(self, name=''):
|
| 962 |
+
blk = Block(parent=self, name=name)
|
| 963 |
+
self.blocks.append(blk)
|
| 964 |
+
return blk
|
| 965 |
+
|
| 966 |
+
def insert_basic_block(self, before, name=''):
|
| 967 |
+
"""Insert block before
|
| 968 |
+
"""
|
| 969 |
+
blk = Block(parent=self, name=name)
|
| 970 |
+
self.blocks.insert(before, blk)
|
| 971 |
+
return blk
|
| 972 |
+
|
| 973 |
+
def descr_prototype(self, buf):
|
| 974 |
+
"""
|
| 975 |
+
Describe the prototype ("head") of the function.
|
| 976 |
+
"""
|
| 977 |
+
state = "define" if self.blocks else "declare"
|
| 978 |
+
ret = self.return_value
|
| 979 |
+
args = ", ".join(str(a) for a in self.args)
|
| 980 |
+
name = self.get_reference()
|
| 981 |
+
attrs = ' ' + ' '.join(self.attributes._to_list(
|
| 982 |
+
self.ftype.return_type)) if self.attributes else ''
|
| 983 |
+
if any(self.args):
|
| 984 |
+
vararg = ', ...' if self.ftype.var_arg else ''
|
| 985 |
+
else:
|
| 986 |
+
vararg = '...' if self.ftype.var_arg else ''
|
| 987 |
+
linkage = self.linkage
|
| 988 |
+
cconv = self.calling_convention
|
| 989 |
+
prefix = " ".join(str(x) for x in [state, linkage, cconv, ret] if x)
|
| 990 |
+
metadata = self._stringify_metadata()
|
| 991 |
+
metadata = ' {}'.format(metadata) if metadata else ''
|
| 992 |
+
section = ' section "{}"'.format(self.section) if self.section else ''
|
| 993 |
+
pt_str = "{prefix} {name}({args}{vararg}){attrs}{section}{metadata}\n"
|
| 994 |
+
prototype = pt_str.format(prefix=prefix, name=name, args=args,
|
| 995 |
+
vararg=vararg, attrs=attrs, section=section,
|
| 996 |
+
metadata=metadata)
|
| 997 |
+
buf.append(prototype)
|
| 998 |
+
|
| 999 |
+
def descr_body(self, buf):
|
| 1000 |
+
"""
|
| 1001 |
+
Describe of the body of the function.
|
| 1002 |
+
"""
|
| 1003 |
+
for blk in self.blocks:
|
| 1004 |
+
blk.descr(buf)
|
| 1005 |
+
|
| 1006 |
+
def descr(self, buf):
|
| 1007 |
+
self.descr_prototype(buf)
|
| 1008 |
+
if self.blocks:
|
| 1009 |
+
buf.append("{\n")
|
| 1010 |
+
self.descr_body(buf)
|
| 1011 |
+
buf.append("}\n")
|
| 1012 |
+
|
| 1013 |
+
def __str__(self):
|
| 1014 |
+
buf = []
|
| 1015 |
+
self.descr(buf)
|
| 1016 |
+
return "".join(buf)
|
| 1017 |
+
|
| 1018 |
+
@property
|
| 1019 |
+
def is_declaration(self):
|
| 1020 |
+
return len(self.blocks) == 0
|
| 1021 |
+
|
| 1022 |
+
|
| 1023 |
+
class ArgumentAttributes(AttributeSet):
|
| 1024 |
+
# List from
|
| 1025 |
+
# https://releases.llvm.org/14.0.0/docs/LangRef.html#parameter-attributes
|
| 1026 |
+
_known = MappingProxyType({
|
| 1027 |
+
# True (emit type),
|
| 1028 |
+
# False (emit name only)
|
| 1029 |
+
'byref': True,
|
| 1030 |
+
'byval': True,
|
| 1031 |
+
'elementtype': True,
|
| 1032 |
+
'immarg': False,
|
| 1033 |
+
'inalloca': True,
|
| 1034 |
+
'inreg': False,
|
| 1035 |
+
'nest': False,
|
| 1036 |
+
'noalias': False,
|
| 1037 |
+
'nocapture': False,
|
| 1038 |
+
'nofree': False,
|
| 1039 |
+
'nonnull': False,
|
| 1040 |
+
'noundef': False,
|
| 1041 |
+
'preallocated': True,
|
| 1042 |
+
'returned': False,
|
| 1043 |
+
'signext': False,
|
| 1044 |
+
'sret': True,
|
| 1045 |
+
'swiftasync': False,
|
| 1046 |
+
'swifterror': False,
|
| 1047 |
+
'swiftself': False,
|
| 1048 |
+
'zeroext': False,
|
| 1049 |
+
})
|
| 1050 |
+
|
| 1051 |
+
def __init__(self, args=()):
|
| 1052 |
+
self._align = 0
|
| 1053 |
+
self._dereferenceable = 0
|
| 1054 |
+
self._dereferenceable_or_null = 0
|
| 1055 |
+
super(ArgumentAttributes, self).__init__(args)
|
| 1056 |
+
|
| 1057 |
+
def _expand(self, name, typ):
|
| 1058 |
+
requires_type = self._known.get(name)
|
| 1059 |
+
if requires_type:
|
| 1060 |
+
return f"{name}({typ.pointee})"
|
| 1061 |
+
else:
|
| 1062 |
+
return name
|
| 1063 |
+
|
| 1064 |
+
@property
|
| 1065 |
+
def align(self):
|
| 1066 |
+
return self._align
|
| 1067 |
+
|
| 1068 |
+
@align.setter
|
| 1069 |
+
def align(self, val):
|
| 1070 |
+
assert isinstance(val, int) and val >= 0
|
| 1071 |
+
self._align = val
|
| 1072 |
+
|
| 1073 |
+
@property
|
| 1074 |
+
def dereferenceable(self):
|
| 1075 |
+
return self._dereferenceable
|
| 1076 |
+
|
| 1077 |
+
@dereferenceable.setter
|
| 1078 |
+
def dereferenceable(self, val):
|
| 1079 |
+
assert isinstance(val, int) and val >= 0
|
| 1080 |
+
self._dereferenceable = val
|
| 1081 |
+
|
| 1082 |
+
@property
|
| 1083 |
+
def dereferenceable_or_null(self):
|
| 1084 |
+
return self._dereferenceable_or_null
|
| 1085 |
+
|
| 1086 |
+
@dereferenceable_or_null.setter
|
| 1087 |
+
def dereferenceable_or_null(self, val):
|
| 1088 |
+
assert isinstance(val, int) and val >= 0
|
| 1089 |
+
self._dereferenceable_or_null = val
|
| 1090 |
+
|
| 1091 |
+
def _to_list(self, typ):
|
| 1092 |
+
attrs = super()._to_list(typ)
|
| 1093 |
+
if self.align:
|
| 1094 |
+
attrs.append('align {0:d}'.format(self.align))
|
| 1095 |
+
if self.dereferenceable:
|
| 1096 |
+
attrs.append('dereferenceable({0:d})'.format(self.dereferenceable))
|
| 1097 |
+
if self.dereferenceable_or_null:
|
| 1098 |
+
dref = 'dereferenceable_or_null({0:d})'
|
| 1099 |
+
attrs.append(dref.format(self.dereferenceable_or_null))
|
| 1100 |
+
return attrs
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
class _BaseArgument(NamedValue):
|
| 1104 |
+
def __init__(self, parent, typ, name=''):
|
| 1105 |
+
assert isinstance(typ, types.Type)
|
| 1106 |
+
super(_BaseArgument, self).__init__(parent, typ, name=name)
|
| 1107 |
+
self.parent = parent
|
| 1108 |
+
self.attributes = ArgumentAttributes()
|
| 1109 |
+
|
| 1110 |
+
def __repr__(self):
|
| 1111 |
+
return "<ir.%s %r of type %s>" % (self.__class__.__name__, self.name,
|
| 1112 |
+
self.type)
|
| 1113 |
+
|
| 1114 |
+
def add_attribute(self, attr):
|
| 1115 |
+
self.attributes.add(attr)
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
class Argument(_BaseArgument):
|
| 1119 |
+
"""
|
| 1120 |
+
The specification of a function argument.
|
| 1121 |
+
"""
|
| 1122 |
+
|
| 1123 |
+
def __str__(self):
|
| 1124 |
+
attrs = self.attributes._to_list(self.type)
|
| 1125 |
+
if attrs:
|
| 1126 |
+
return "{0} {1} {2}".format(self.type, ' '.join(attrs),
|
| 1127 |
+
self.get_reference())
|
| 1128 |
+
else:
|
| 1129 |
+
return "{0} {1}".format(self.type, self.get_reference())
|
| 1130 |
+
|
| 1131 |
+
|
| 1132 |
+
class ReturnValue(_BaseArgument):
|
| 1133 |
+
"""
|
| 1134 |
+
The specification of a function's return value.
|
| 1135 |
+
"""
|
| 1136 |
+
|
| 1137 |
+
def __str__(self):
|
| 1138 |
+
attrs = self.attributes._to_list(self.type)
|
| 1139 |
+
if attrs:
|
| 1140 |
+
return "{0} {1}".format(' '.join(attrs), self.type)
|
| 1141 |
+
else:
|
| 1142 |
+
return str(self.type)
|
| 1143 |
+
|
| 1144 |
+
|
| 1145 |
+
class Block(NamedValue):
|
| 1146 |
+
"""
|
| 1147 |
+
A LLVM IR basic block. A basic block is a sequence of
|
| 1148 |
+
instructions whose execution always goes from start to end. That
|
| 1149 |
+
is, a control flow instruction (branch) can only appear as the
|
| 1150 |
+
last instruction, and incoming branches can only jump to the first
|
| 1151 |
+
instruction.
|
| 1152 |
+
"""
|
| 1153 |
+
|
| 1154 |
+
def __init__(self, parent, name=''):
|
| 1155 |
+
super(Block, self).__init__(parent, types.LabelType(), name=name)
|
| 1156 |
+
self.scope = parent.scope
|
| 1157 |
+
self.instructions = []
|
| 1158 |
+
self.terminator = None
|
| 1159 |
+
|
| 1160 |
+
@property
|
| 1161 |
+
def is_terminated(self):
|
| 1162 |
+
return self.terminator is not None
|
| 1163 |
+
|
| 1164 |
+
@property
|
| 1165 |
+
def function(self):
|
| 1166 |
+
return self.parent
|
| 1167 |
+
|
| 1168 |
+
@property
|
| 1169 |
+
def module(self):
|
| 1170 |
+
return self.parent.module
|
| 1171 |
+
|
| 1172 |
+
def descr(self, buf):
|
| 1173 |
+
buf.append("{0}:\n".format(self._format_name()))
|
| 1174 |
+
buf += [" {0}\n".format(instr) for instr in self.instructions]
|
| 1175 |
+
|
| 1176 |
+
def replace(self, old, new):
|
| 1177 |
+
"""Replace an instruction"""
|
| 1178 |
+
if old.type != new.type:
|
| 1179 |
+
raise TypeError("new instruction has a different type")
|
| 1180 |
+
pos = self.instructions.index(old)
|
| 1181 |
+
self.instructions.remove(old)
|
| 1182 |
+
self.instructions.insert(pos, new)
|
| 1183 |
+
|
| 1184 |
+
for bb in self.parent.basic_blocks:
|
| 1185 |
+
for instr in bb.instructions:
|
| 1186 |
+
instr.replace_usage(old, new)
|
| 1187 |
+
|
| 1188 |
+
def _format_name(self):
|
| 1189 |
+
# Per the LLVM Language Ref on identifiers, names matching the following
|
| 1190 |
+
# regex do not need to be quoted: [%@][-a-zA-Z$._][-a-zA-Z$._0-9]*
|
| 1191 |
+
# Otherwise, the identifier must be quoted and escaped.
|
| 1192 |
+
name = self.name
|
| 1193 |
+
if not _SIMPLE_IDENTIFIER_RE.match(name):
|
| 1194 |
+
name = name.replace('\\', '\\5c').replace('"', '\\22')
|
| 1195 |
+
name = '"{0}"'.format(name)
|
| 1196 |
+
return name
|
| 1197 |
+
|
| 1198 |
+
|
| 1199 |
+
class BlockAddress(Value):
|
| 1200 |
+
"""
|
| 1201 |
+
The address of a basic block.
|
| 1202 |
+
"""
|
| 1203 |
+
|
| 1204 |
+
def __init__(self, function, basic_block):
|
| 1205 |
+
assert isinstance(function, Function)
|
| 1206 |
+
assert isinstance(basic_block, Block)
|
| 1207 |
+
self.type = types.IntType(8).as_pointer()
|
| 1208 |
+
self.function = function
|
| 1209 |
+
self.basic_block = basic_block
|
| 1210 |
+
|
| 1211 |
+
def __str__(self):
|
| 1212 |
+
return '{0} {1}'.format(self.type, self.get_reference())
|
| 1213 |
+
|
| 1214 |
+
def get_reference(self):
|
| 1215 |
+
return "blockaddress({0}, {1})".format(
|
| 1216 |
+
self.function.get_reference(),
|
| 1217 |
+
self.basic_block.get_reference())
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.54 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/__main__.cpython-310.pyc
ADDED
|
Binary file (215 Bytes). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/customize.cpython-310.pyc
ADDED
|
Binary file (11.4 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/refprune_proto.cpython-310.pyc
ADDED
|
Binary file (7.11 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_binding.cpython-310.pyc
ADDED
|
Binary file (82.7 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_ir.cpython-310.pyc
ADDED
|
Binary file (92.1 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_refprune.cpython-310.pyc
ADDED
|
Binary file (15.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/__pycache__/test_valuerepr.cpython-310.pyc
ADDED
|
Binary file (2.85 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/refprune_proto.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Contains tests and a prototype implementation for the fanout algorithm in
|
| 3 |
+
the LLVM refprune pass.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
try:
|
| 7 |
+
from graphviz import Digraph
|
| 8 |
+
except ImportError:
|
| 9 |
+
pass
|
| 10 |
+
from collections import defaultdict
|
| 11 |
+
|
| 12 |
+
# The entry block. It's always the same.
|
| 13 |
+
ENTRY = "A"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
# The following caseNN() functions returns a 3-tuple of
|
| 17 |
+
# (nodes, edges, expected).
|
| 18 |
+
# `nodes` maps BB nodes to incref/decref inside the block.
|
| 19 |
+
# `edges` maps BB nodes to their successor BB.
|
| 20 |
+
# `expected` maps BB-node with incref to a set of BB-nodes with the decrefs, or
|
| 21 |
+
# the value can be None, indicating invalid prune.
|
| 22 |
+
|
| 23 |
+
def case1():
|
| 24 |
+
edges = {
|
| 25 |
+
"A": ["B"],
|
| 26 |
+
"B": ["C", "D"],
|
| 27 |
+
"C": [],
|
| 28 |
+
"D": ["E", "F"],
|
| 29 |
+
"E": ["G"],
|
| 30 |
+
"F": [],
|
| 31 |
+
"G": ["H", "I"],
|
| 32 |
+
"I": ["G", "F"],
|
| 33 |
+
"H": ["J", "K"],
|
| 34 |
+
"J": ["L", "M"],
|
| 35 |
+
"K": [],
|
| 36 |
+
"L": ["Z"],
|
| 37 |
+
"M": ["Z", "O", "P"],
|
| 38 |
+
"O": ["Z"],
|
| 39 |
+
"P": ["Z"],
|
| 40 |
+
"Z": [],
|
| 41 |
+
}
|
| 42 |
+
nodes = defaultdict(list)
|
| 43 |
+
nodes["D"] = ["incref"]
|
| 44 |
+
nodes["H"] = ["decref"]
|
| 45 |
+
nodes["F"] = ["decref", "decref"]
|
| 46 |
+
expected = {"D": {"H", "F"}}
|
| 47 |
+
return nodes, edges, expected
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def case2():
|
| 51 |
+
edges = {
|
| 52 |
+
"A": ["B", "C"],
|
| 53 |
+
"B": ["C"],
|
| 54 |
+
"C": [],
|
| 55 |
+
}
|
| 56 |
+
nodes = defaultdict(list)
|
| 57 |
+
nodes["A"] = ["incref"]
|
| 58 |
+
nodes["B"] = ["decref"]
|
| 59 |
+
nodes["C"] = ["decref"]
|
| 60 |
+
expected = {"A": None}
|
| 61 |
+
return nodes, edges, expected
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def case3():
|
| 65 |
+
nodes, edges, _ = case1()
|
| 66 |
+
# adds an invalid edge
|
| 67 |
+
edges["H"].append("F")
|
| 68 |
+
expected = {"D": None}
|
| 69 |
+
return nodes, edges, expected
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def case4():
|
| 73 |
+
nodes, edges, _ = case1()
|
| 74 |
+
# adds an invalid edge
|
| 75 |
+
edges["H"].append("E")
|
| 76 |
+
expected = {"D": None}
|
| 77 |
+
return nodes, edges, expected
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def case5():
|
| 81 |
+
nodes, edges, _ = case1()
|
| 82 |
+
# adds backedge to go before incref
|
| 83 |
+
edges["B"].append("I")
|
| 84 |
+
expected = {"D": None}
|
| 85 |
+
return nodes, edges, expected
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def case6():
|
| 89 |
+
nodes, edges, _ = case1()
|
| 90 |
+
# adds backedge to go before incref
|
| 91 |
+
edges["I"].append("B")
|
| 92 |
+
expected = {"D": None}
|
| 93 |
+
return nodes, edges, expected
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def case7():
|
| 97 |
+
nodes, edges, _ = case1()
|
| 98 |
+
# adds forward jump outside
|
| 99 |
+
edges["I"].append("M")
|
| 100 |
+
expected = {"D": None}
|
| 101 |
+
return nodes, edges, expected
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def case8():
|
| 105 |
+
edges = {
|
| 106 |
+
"A": ["B", "C"],
|
| 107 |
+
"B": ["C"],
|
| 108 |
+
"C": [],
|
| 109 |
+
}
|
| 110 |
+
nodes = defaultdict(list)
|
| 111 |
+
nodes["A"] = ["incref"]
|
| 112 |
+
nodes["C"] = ["decref"]
|
| 113 |
+
expected = {"A": {"C"}}
|
| 114 |
+
return nodes, edges, expected
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def case9():
|
| 118 |
+
nodes, edges, _ = case8()
|
| 119 |
+
# adds back edge
|
| 120 |
+
edges["C"].append("B")
|
| 121 |
+
expected = {"A": None}
|
| 122 |
+
return nodes, edges, expected
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def case10():
|
| 126 |
+
nodes, edges, _ = case8()
|
| 127 |
+
# adds back edge to A
|
| 128 |
+
edges["C"].append("A")
|
| 129 |
+
expected = {"A": {"C"}}
|
| 130 |
+
return nodes, edges, expected
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def case11():
|
| 134 |
+
nodes, edges, _ = case8()
|
| 135 |
+
edges["C"].append("D")
|
| 136 |
+
edges["D"] = []
|
| 137 |
+
expected = {"A": {"C"}}
|
| 138 |
+
return nodes, edges, expected
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def case12():
|
| 142 |
+
nodes, edges, _ = case8()
|
| 143 |
+
edges["C"].append("D")
|
| 144 |
+
edges["D"] = ["A"]
|
| 145 |
+
expected = {"A": {"C"}}
|
| 146 |
+
return nodes, edges, expected
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
def case13():
|
| 150 |
+
nodes, edges, _ = case8()
|
| 151 |
+
edges["C"].append("D")
|
| 152 |
+
edges["D"] = ["B"]
|
| 153 |
+
expected = {"A": None}
|
| 154 |
+
return nodes, edges, expected
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def make_predecessor_map(edges):
|
| 158 |
+
d = defaultdict(set)
|
| 159 |
+
for src, outgoings in edges.items():
|
| 160 |
+
for dst in outgoings:
|
| 161 |
+
d[dst].add(src)
|
| 162 |
+
return d
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class FanoutAlgorithm:
|
| 166 |
+
def __init__(self, nodes, edges, verbose=False):
|
| 167 |
+
self.nodes = nodes
|
| 168 |
+
self.edges = edges
|
| 169 |
+
self.rev_edges = make_predecessor_map(edges)
|
| 170 |
+
self.print = print if verbose else self._null_print
|
| 171 |
+
|
| 172 |
+
def run(self):
|
| 173 |
+
return self.find_fanout_in_function()
|
| 174 |
+
|
| 175 |
+
def _null_print(self, *args, **kwargs):
|
| 176 |
+
pass
|
| 177 |
+
|
| 178 |
+
def find_fanout_in_function(self):
|
| 179 |
+
got = {}
|
| 180 |
+
for cur_node in self.edges:
|
| 181 |
+
for incref in (x for x in self.nodes[cur_node] if x == "incref"):
|
| 182 |
+
decref_blocks = self.find_fanout(cur_node)
|
| 183 |
+
self.print(">>", cur_node, "===", decref_blocks)
|
| 184 |
+
got[cur_node] = decref_blocks
|
| 185 |
+
return got
|
| 186 |
+
|
| 187 |
+
def find_fanout(self, head_node):
|
| 188 |
+
decref_blocks = self.find_decref_candidates(head_node)
|
| 189 |
+
self.print("candidates", decref_blocks)
|
| 190 |
+
if not decref_blocks:
|
| 191 |
+
return None
|
| 192 |
+
if not self.verify_non_overlapping(
|
| 193 |
+
head_node, decref_blocks, entry=ENTRY
|
| 194 |
+
):
|
| 195 |
+
return None
|
| 196 |
+
return set(decref_blocks)
|
| 197 |
+
|
| 198 |
+
def verify_non_overlapping(self, head_node, decref_blocks, entry):
|
| 199 |
+
self.print("verify_non_overlapping".center(80, "-"))
|
| 200 |
+
# reverse walk for each decref_blocks
|
| 201 |
+
# they should end at head_node
|
| 202 |
+
todo = list(decref_blocks)
|
| 203 |
+
while todo:
|
| 204 |
+
cur_node = todo.pop()
|
| 205 |
+
visited = set()
|
| 206 |
+
|
| 207 |
+
workstack = [cur_node]
|
| 208 |
+
del cur_node
|
| 209 |
+
while workstack:
|
| 210 |
+
cur_node = workstack.pop()
|
| 211 |
+
self.print("cur_node", cur_node, "|", workstack)
|
| 212 |
+
if cur_node in visited:
|
| 213 |
+
continue # skip
|
| 214 |
+
if cur_node == entry:
|
| 215 |
+
# Entry node
|
| 216 |
+
self.print(
|
| 217 |
+
"!! failed because we arrived at entry", cur_node
|
| 218 |
+
)
|
| 219 |
+
return False
|
| 220 |
+
visited.add(cur_node)
|
| 221 |
+
# check all predecessors
|
| 222 |
+
self.print(
|
| 223 |
+
f" {cur_node} preds {self.get_predecessors(cur_node)}"
|
| 224 |
+
)
|
| 225 |
+
for pred in self.get_predecessors(cur_node):
|
| 226 |
+
if pred in decref_blocks:
|
| 227 |
+
# reject because there's a predecessor in decref_blocks
|
| 228 |
+
self.print(
|
| 229 |
+
"!! reject because predecessor in decref_blocks"
|
| 230 |
+
)
|
| 231 |
+
return False
|
| 232 |
+
if pred != head_node:
|
| 233 |
+
|
| 234 |
+
workstack.append(pred)
|
| 235 |
+
|
| 236 |
+
return True
|
| 237 |
+
|
| 238 |
+
def get_successors(self, node):
|
| 239 |
+
return tuple(self.edges[node])
|
| 240 |
+
|
| 241 |
+
def get_predecessors(self, node):
|
| 242 |
+
return tuple(self.rev_edges[node])
|
| 243 |
+
|
| 244 |
+
def has_decref(self, node):
|
| 245 |
+
return "decref" in self.nodes[node]
|
| 246 |
+
|
| 247 |
+
def walk_child_for_decref(
|
| 248 |
+
self, cur_node, path_stack, decref_blocks, depth=10
|
| 249 |
+
):
|
| 250 |
+
indent = " " * len(path_stack)
|
| 251 |
+
self.print(indent, "walk", path_stack, cur_node)
|
| 252 |
+
if depth <= 0:
|
| 253 |
+
return False # missing
|
| 254 |
+
if cur_node in path_stack:
|
| 255 |
+
if cur_node == path_stack[0]:
|
| 256 |
+
return False # reject interior node backedge
|
| 257 |
+
return True # skip
|
| 258 |
+
if self.has_decref(cur_node):
|
| 259 |
+
decref_blocks.add(cur_node)
|
| 260 |
+
self.print(indent, "found decref")
|
| 261 |
+
return True
|
| 262 |
+
|
| 263 |
+
depth -= 1
|
| 264 |
+
path_stack += (cur_node,)
|
| 265 |
+
found = False
|
| 266 |
+
for child in self.get_successors(cur_node):
|
| 267 |
+
if not self.walk_child_for_decref(
|
| 268 |
+
child, path_stack, decref_blocks
|
| 269 |
+
):
|
| 270 |
+
found = False
|
| 271 |
+
break
|
| 272 |
+
else:
|
| 273 |
+
found = True
|
| 274 |
+
|
| 275 |
+
self.print(indent, f"ret {found}")
|
| 276 |
+
return found
|
| 277 |
+
|
| 278 |
+
def find_decref_candidates(self, cur_node):
|
| 279 |
+
# Forward pass
|
| 280 |
+
self.print("find_decref_candidates".center(80, "-"))
|
| 281 |
+
path_stack = (cur_node,)
|
| 282 |
+
found = False
|
| 283 |
+
decref_blocks = set()
|
| 284 |
+
for child in self.get_successors(cur_node):
|
| 285 |
+
if not self.walk_child_for_decref(
|
| 286 |
+
child, path_stack, decref_blocks
|
| 287 |
+
):
|
| 288 |
+
found = False
|
| 289 |
+
break
|
| 290 |
+
else:
|
| 291 |
+
found = True
|
| 292 |
+
if not found:
|
| 293 |
+
return set()
|
| 294 |
+
else:
|
| 295 |
+
return decref_blocks
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def check_once():
|
| 299 |
+
nodes, edges, expected = case13()
|
| 300 |
+
|
| 301 |
+
# Render graph
|
| 302 |
+
G = Digraph()
|
| 303 |
+
for node in edges:
|
| 304 |
+
G.node(node, shape="rect", label=f"{node}\n" + r"\l".join(nodes[node]))
|
| 305 |
+
for node, children in edges.items():
|
| 306 |
+
for child in children:
|
| 307 |
+
G.edge(node, child)
|
| 308 |
+
|
| 309 |
+
G.view()
|
| 310 |
+
|
| 311 |
+
algo = FanoutAlgorithm(nodes, edges, verbose=True)
|
| 312 |
+
got = algo.run()
|
| 313 |
+
assert expected == got
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def check_all():
|
| 317 |
+
for k, fn in list(globals().items()):
|
| 318 |
+
if k.startswith("case"):
|
| 319 |
+
print(f"{fn}".center(80, "-"))
|
| 320 |
+
nodes, edges, expected = fn()
|
| 321 |
+
algo = FanoutAlgorithm(nodes, edges)
|
| 322 |
+
got = algo.run()
|
| 323 |
+
assert expected == got
|
| 324 |
+
print("ALL PASSED")
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
if __name__ == "__main__":
|
| 328 |
+
# check_once()
|
| 329 |
+
check_all()
|
vllm/lib/python3.10/site-packages/llvmlite/tests/test_binding.py
ADDED
|
@@ -0,0 +1,2585 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ctypes
|
| 2 |
+
import threading
|
| 3 |
+
from ctypes import CFUNCTYPE, c_int, c_int32
|
| 4 |
+
from ctypes.util import find_library
|
| 5 |
+
import gc
|
| 6 |
+
import locale
|
| 7 |
+
import os
|
| 8 |
+
import platform
|
| 9 |
+
import re
|
| 10 |
+
import subprocess
|
| 11 |
+
import sys
|
| 12 |
+
import unittest
|
| 13 |
+
from contextlib import contextmanager
|
| 14 |
+
from tempfile import mkstemp
|
| 15 |
+
|
| 16 |
+
from llvmlite import ir
|
| 17 |
+
from llvmlite import binding as llvm
|
| 18 |
+
from llvmlite.binding import ffi
|
| 19 |
+
from llvmlite.tests import TestCase
|
| 20 |
+
|
| 21 |
+
llvm_version_major = llvm.llvm_version_info[0]
|
| 22 |
+
|
| 23 |
+
# arvm7l needs extra ABI symbols to link successfully
|
| 24 |
+
if platform.machine() == 'armv7l':
|
| 25 |
+
llvm.load_library_permanently('libgcc_s.so.1')
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def no_de_locale():
|
| 29 |
+
cur = locale.setlocale(locale.LC_ALL)
|
| 30 |
+
try:
|
| 31 |
+
locale.setlocale(locale.LC_ALL, 'de_DE')
|
| 32 |
+
except locale.Error:
|
| 33 |
+
return True
|
| 34 |
+
else:
|
| 35 |
+
return False
|
| 36 |
+
finally:
|
| 37 |
+
locale.setlocale(locale.LC_ALL, cur)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
asm_sum = r"""
|
| 41 |
+
; ModuleID = '<string>'
|
| 42 |
+
source_filename = "asm_sum.c"
|
| 43 |
+
target triple = "{triple}"
|
| 44 |
+
%struct.glob_type = type {{ i64, [2 x i64]}}
|
| 45 |
+
%struct.glob_type_vec = type {{ i64, <2 x i64>}}
|
| 46 |
+
|
| 47 |
+
@glob = global i32 0
|
| 48 |
+
@glob_b = global i8 0
|
| 49 |
+
@glob_f = global float 1.5
|
| 50 |
+
@glob_struct = global %struct.glob_type {{i64 0, [2 x i64] [i64 0, i64 0]}}
|
| 51 |
+
|
| 52 |
+
define i32 @sum(i32 %.1, i32 %.2) {{
|
| 53 |
+
%.3 = add i32 %.1, %.2
|
| 54 |
+
%.4 = add i32 0, %.3
|
| 55 |
+
ret i32 %.4
|
| 56 |
+
}}
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
asm_sum2 = r"""
|
| 60 |
+
; ModuleID = '<string>'
|
| 61 |
+
target triple = "{triple}"
|
| 62 |
+
|
| 63 |
+
define i32 @sum(i32 %.1, i32 %.2) {{
|
| 64 |
+
%.3 = add i32 %.1, %.2
|
| 65 |
+
ret i32 %.3
|
| 66 |
+
}}
|
| 67 |
+
"""
|
| 68 |
+
|
| 69 |
+
asm_sum3 = r"""
|
| 70 |
+
; ModuleID = '<string>'
|
| 71 |
+
target triple = "{triple}"
|
| 72 |
+
|
| 73 |
+
define i64 @sum(i64 %.1, i64 %.2) {{
|
| 74 |
+
%.3 = add i64 %.1, %.2
|
| 75 |
+
%.4 = add i64 5, %.3
|
| 76 |
+
%.5 = add i64 -5, %.4
|
| 77 |
+
ret i64 %.5
|
| 78 |
+
}}
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
asm_mul = r"""
|
| 82 |
+
; ModuleID = '<string>'
|
| 83 |
+
target triple = "{triple}"
|
| 84 |
+
@mul_glob = global i32 0
|
| 85 |
+
|
| 86 |
+
define i32 @mul(i32 %.1, i32 %.2) {{
|
| 87 |
+
%.3 = mul i32 %.1, %.2
|
| 88 |
+
ret i32 %.3
|
| 89 |
+
}}
|
| 90 |
+
"""
|
| 91 |
+
|
| 92 |
+
asm_square_sum = r"""
|
| 93 |
+
; ModuleID = '<string>'
|
| 94 |
+
target triple = "{triple}"
|
| 95 |
+
@mul_glob = global i32 0
|
| 96 |
+
|
| 97 |
+
declare i32 @sum(i32, i32)
|
| 98 |
+
define i32 @square_sum(i32 %.1, i32 %.2) {{
|
| 99 |
+
%.3 = call i32 @sum(i32 %.1, i32 %.2)
|
| 100 |
+
%.4 = mul i32 %.3, %.3
|
| 101 |
+
ret i32 %.4
|
| 102 |
+
}}
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
asm_getversion = r"""
|
| 106 |
+
; ModuleID = '<string>'
|
| 107 |
+
target triple = "{triple}"
|
| 108 |
+
|
| 109 |
+
declare i8* @Py_GetVersion()
|
| 110 |
+
|
| 111 |
+
define void @getversion(i32 %.1, i32 %.2) {{
|
| 112 |
+
%1 = call i8* @Py_GetVersion()
|
| 113 |
+
ret void
|
| 114 |
+
}}
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
if platform.python_implementation() == 'PyPy':
|
| 118 |
+
asm_getversion = asm_getversion.replace('Py_GetVersion', 'PyPy_GetVersion')
|
| 119 |
+
|
| 120 |
+
# `fadd` used on integer inputs
|
| 121 |
+
asm_parse_error = r"""
|
| 122 |
+
; ModuleID = '<string>'
|
| 123 |
+
target triple = "{triple}"
|
| 124 |
+
|
| 125 |
+
define i32 @sum(i32 %.1, i32 %.2) {{
|
| 126 |
+
%.3 = fadd i32 %.1, %.2
|
| 127 |
+
ret i32 %.3
|
| 128 |
+
}}
|
| 129 |
+
"""
|
| 130 |
+
|
| 131 |
+
# "%.bug" definition references itself
|
| 132 |
+
asm_verification_fail = r"""
|
| 133 |
+
; ModuleID = '<string>'
|
| 134 |
+
target triple = "{triple}"
|
| 135 |
+
|
| 136 |
+
define void @sum() {{
|
| 137 |
+
%.bug = add i32 1, %.bug
|
| 138 |
+
ret void
|
| 139 |
+
}}
|
| 140 |
+
"""
|
| 141 |
+
|
| 142 |
+
asm_sum_declare = r"""
|
| 143 |
+
; ModuleID = '<string>'
|
| 144 |
+
target triple = "{triple}"
|
| 145 |
+
|
| 146 |
+
declare i32 @sum(i32 %.1, i32 %.2)
|
| 147 |
+
"""
|
| 148 |
+
|
| 149 |
+
asm_vararg_declare = r"""
|
| 150 |
+
; ModuleID = '<string>'
|
| 151 |
+
target triple = "{triple}"
|
| 152 |
+
|
| 153 |
+
declare i32 @vararg(i32 %.1, ...)
|
| 154 |
+
"""
|
| 155 |
+
|
| 156 |
+
asm_double_inaccurate = r"""
|
| 157 |
+
; ModuleID = '<string>'
|
| 158 |
+
target triple = "{triple}"
|
| 159 |
+
|
| 160 |
+
define void @foo() {{
|
| 161 |
+
%const = fadd fp128 0xLF3CB1CCF26FBC178452FB4EC7F91DEAD, 0xL00000000000000000000000000000001
|
| 162 |
+
ret void
|
| 163 |
+
}}
|
| 164 |
+
""" # noqa E501
|
| 165 |
+
|
| 166 |
+
asm_double_locale = r"""
|
| 167 |
+
; ModuleID = '<string>'
|
| 168 |
+
target triple = "{triple}"
|
| 169 |
+
|
| 170 |
+
define void @foo() {{
|
| 171 |
+
%const = fadd double 0.0, 3.14
|
| 172 |
+
ret void
|
| 173 |
+
}}
|
| 174 |
+
"""
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
asm_inlineasm = r"""
|
| 178 |
+
; ModuleID = '<string>'
|
| 179 |
+
target triple = "{triple}"
|
| 180 |
+
|
| 181 |
+
define void @foo() {{
|
| 182 |
+
call void asm sideeffect "nop", ""()
|
| 183 |
+
ret void
|
| 184 |
+
}}
|
| 185 |
+
"""
|
| 186 |
+
|
| 187 |
+
asm_inlineasm2 = """
|
| 188 |
+
; ModuleID = '<string>'
|
| 189 |
+
target triple = "{triple}"
|
| 190 |
+
|
| 191 |
+
define void @inlineme() {{
|
| 192 |
+
ret void
|
| 193 |
+
}}
|
| 194 |
+
|
| 195 |
+
define i32 @caller(i32 %.1, i32 %.2) {{
|
| 196 |
+
entry:
|
| 197 |
+
%stack = alloca i32
|
| 198 |
+
store i32 %.1, i32* %stack
|
| 199 |
+
br label %main
|
| 200 |
+
main:
|
| 201 |
+
%loaded = load i32, i32* %stack
|
| 202 |
+
%.3 = add i32 %loaded, %.2
|
| 203 |
+
%.4 = add i32 0, %.3
|
| 204 |
+
call void @inlineme()
|
| 205 |
+
ret i32 %.4
|
| 206 |
+
}}
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
asm_inlineasm3 = """
|
| 210 |
+
; ModuleID = 'test.c'
|
| 211 |
+
source_filename = "test.c"
|
| 212 |
+
target triple = "{triple}"
|
| 213 |
+
|
| 214 |
+
; Function Attrs: noinline nounwind optnone ssp uwtable
|
| 215 |
+
define void @inlineme() noinline !dbg !15 {{
|
| 216 |
+
ret void, !dbg !18
|
| 217 |
+
}}
|
| 218 |
+
|
| 219 |
+
; Function Attrs: noinline nounwind optnone ssp uwtable
|
| 220 |
+
define i32 @foo(i32 %0, i32 %1) !dbg !19 {{
|
| 221 |
+
%3 = alloca i32, align 4
|
| 222 |
+
%4 = alloca i32, align 4
|
| 223 |
+
store i32 %0, i32* %3, align 4
|
| 224 |
+
call void @llvm.dbg.declare(metadata i32* %3, metadata !23, metadata !DIExpression()), !dbg !24
|
| 225 |
+
store i32 %1, i32* %4, align 4
|
| 226 |
+
call void @llvm.dbg.declare(metadata i32* %4, metadata !25, metadata !DIExpression()), !dbg !26
|
| 227 |
+
call void @inlineme(), !dbg !27
|
| 228 |
+
%5 = load i32, i32* %3, align 4, !dbg !28
|
| 229 |
+
%6 = load i32, i32* %4, align 4, !dbg !29
|
| 230 |
+
%7 = add nsw i32 %5, %6, !dbg !30
|
| 231 |
+
ret i32 %7, !dbg !31
|
| 232 |
+
}}
|
| 233 |
+
|
| 234 |
+
; Function Attrs: nofree nosync nounwind readnone speculatable willreturn
|
| 235 |
+
declare void @llvm.dbg.declare(metadata, metadata, metadata) #1
|
| 236 |
+
|
| 237 |
+
attributes #1 = {{ nofree nosync nounwind readnone speculatable willreturn }}
|
| 238 |
+
|
| 239 |
+
!llvm.module.flags = !{{!1, !2, !3, !4, !5, !6, !7, !8, !9, !10}}
|
| 240 |
+
!llvm.dbg.cu = !{{!11}}
|
| 241 |
+
!llvm.ident = !{{!14}}
|
| 242 |
+
|
| 243 |
+
!0 = !{{i32 2, !"SDK Version", [2 x i32] [i32 12, i32 3]}}
|
| 244 |
+
!1 = !{{i32 7, !"Dwarf Version", i32 4}}
|
| 245 |
+
!2 = !{{i32 2, !"Debug Info Version", i32 3}}
|
| 246 |
+
!3 = !{{i32 1, !"wchar_size", i32 4}}
|
| 247 |
+
!4 = !{{i32 1, !"branch-target-enforcement", i32 0}}
|
| 248 |
+
!5 = !{{i32 1, !"sign-return-address", i32 0}}
|
| 249 |
+
!6 = !{{i32 1, !"sign-return-address-all", i32 0}}
|
| 250 |
+
!7 = !{{i32 1, !"sign-return-address-with-bkey", i32 0}}
|
| 251 |
+
!8 = !{{i32 7, !"PIC Level", i32 2}}
|
| 252 |
+
!9 = !{{i32 7, !"uwtable", i32 1}}
|
| 253 |
+
!10 = !{{i32 7, !"frame-pointer", i32 1}}
|
| 254 |
+
!11 = distinct !DICompileUnit(language: DW_LANG_C99, file: !12, producer: "Apple clang version 13.1.6 (clang-1316.0.21.2.3)", isOptimized: false, runtimeVersion: 0, emissionKind: FullDebug, enums: !13, splitDebugInlining: false, nameTableKind: None, sysroot: "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk", sdk: "MacOSX.sdk")
|
| 255 |
+
!12 = !DIFile(filename: "test.c", directory: "/")
|
| 256 |
+
!13 = !{{}}
|
| 257 |
+
!14 = !{{!"Apple clang version 13.1.6 (clang-1316.0.21.2.3)"}}
|
| 258 |
+
!15 = distinct !DISubprogram(name: "inlineme", scope: !12, file: !12, line: 1, type: !16, scopeLine: 1, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13)
|
| 259 |
+
!16 = !DISubroutineType(types: !17)
|
| 260 |
+
!17 = !{{null}}
|
| 261 |
+
!18 = !DILocation(line: 1, column: 22, scope: !15)
|
| 262 |
+
!19 = distinct !DISubprogram(name: "foo", scope: !12, file: !12, line: 3, type: !20, scopeLine: 3, flags: DIFlagPrototyped, spFlags: DISPFlagDefinition, unit: !11, retainedNodes: !13)
|
| 263 |
+
!20 = !DISubroutineType(types: !21)
|
| 264 |
+
!21 = !{{!22, !22, !22}}
|
| 265 |
+
!22 = !DIBasicType(name: "int", size: 32, encoding: DW_ATE_signed)
|
| 266 |
+
!23 = !DILocalVariable(name: "a", arg: 1, scope: !19, file: !12, line: 3, type: !22)
|
| 267 |
+
!24 = !DILocation(line: 3, column: 13, scope: !19)
|
| 268 |
+
!25 = !DILocalVariable(name: "b", arg: 2, scope: !19, file: !12, line: 3, type: !22)
|
| 269 |
+
!26 = !DILocation(line: 3, column: 20, scope: !19)
|
| 270 |
+
!27 = !DILocation(line: 4, column: 5, scope: !19)
|
| 271 |
+
!28 = !DILocation(line: 5, column: 12, scope: !19)
|
| 272 |
+
!29 = !DILocation(line: 5, column: 16, scope: !19)
|
| 273 |
+
!30 = !DILocation(line: 5, column: 14, scope: !19)
|
| 274 |
+
!31 = !DILocation(line: 5, column: 5, scope: !19)
|
| 275 |
+
""" # noqa E501
|
| 276 |
+
|
| 277 |
+
licm_asm = r"""
|
| 278 |
+
; ModuleID = "<string>"
|
| 279 |
+
target triple = "{triple}"
|
| 280 |
+
|
| 281 |
+
define double @licm(i32 %0) {{
|
| 282 |
+
%2 = alloca i32, align 4
|
| 283 |
+
%3 = alloca double, align 8
|
| 284 |
+
%4 = alloca i32, align 4
|
| 285 |
+
%5 = alloca double, align 8
|
| 286 |
+
store i32 %0, i32* %2, align 4
|
| 287 |
+
store double 0.000000e+00, double* %3, align 8
|
| 288 |
+
store i32 0, i32* %4, align 4
|
| 289 |
+
br label %6
|
| 290 |
+
|
| 291 |
+
6: ; preds = %14, %1
|
| 292 |
+
%7 = load i32, i32* %4, align 4
|
| 293 |
+
%8 = load i32, i32* %2, align 4
|
| 294 |
+
%9 = icmp slt i32 %7, %8
|
| 295 |
+
br i1 %9, label %10, label %17
|
| 296 |
+
|
| 297 |
+
10: ; preds = %6
|
| 298 |
+
store double 7.000000e+00, double* %5, align 8
|
| 299 |
+
%11 = load double, double* %5, align 8
|
| 300 |
+
%12 = load double, double* %3, align 8
|
| 301 |
+
%13 = fadd double %12, %11
|
| 302 |
+
store double %13, double* %3, align 8
|
| 303 |
+
br label %14
|
| 304 |
+
|
| 305 |
+
14: ; preds = %10
|
| 306 |
+
%15 = load i32, i32* %4, align 4
|
| 307 |
+
%16 = add nsw i32 %15, 1
|
| 308 |
+
store i32 %16, i32* %4, align 4
|
| 309 |
+
br label %6
|
| 310 |
+
|
| 311 |
+
17: ; preds = %6
|
| 312 |
+
%18 = load double, double* %3, align 8
|
| 313 |
+
ret double %18
|
| 314 |
+
}}
|
| 315 |
+
""" # noqa E501
|
| 316 |
+
|
| 317 |
+
asm_global_ctors = r"""
|
| 318 |
+
; ModuleID = "<string>"
|
| 319 |
+
target triple = "{triple}"
|
| 320 |
+
|
| 321 |
+
@A = global i32 undef
|
| 322 |
+
|
| 323 |
+
define void @ctor_A()
|
| 324 |
+
{{
|
| 325 |
+
store i32 10, i32* @A
|
| 326 |
+
ret void
|
| 327 |
+
}}
|
| 328 |
+
|
| 329 |
+
define void @dtor_A()
|
| 330 |
+
{{
|
| 331 |
+
store i32 20, i32* @A
|
| 332 |
+
ret void
|
| 333 |
+
}}
|
| 334 |
+
|
| 335 |
+
define i32 @foo()
|
| 336 |
+
{{
|
| 337 |
+
%.2 = load i32, i32* @A
|
| 338 |
+
%.3 = add i32 %.2, 2
|
| 339 |
+
ret i32 %.3
|
| 340 |
+
}}
|
| 341 |
+
|
| 342 |
+
@llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}]
|
| 343 |
+
@llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}]
|
| 344 |
+
""" # noqa E501
|
| 345 |
+
|
| 346 |
+
asm_ext_ctors = r"""
|
| 347 |
+
; ModuleID = "<string>"
|
| 348 |
+
target triple = "{triple}"
|
| 349 |
+
|
| 350 |
+
@A = external global i32
|
| 351 |
+
|
| 352 |
+
define void @ctor_A()
|
| 353 |
+
{{
|
| 354 |
+
store i32 10, i32* @A
|
| 355 |
+
ret void
|
| 356 |
+
}}
|
| 357 |
+
|
| 358 |
+
define void @dtor_A()
|
| 359 |
+
{{
|
| 360 |
+
store i32 20, i32* @A
|
| 361 |
+
ret void
|
| 362 |
+
}}
|
| 363 |
+
|
| 364 |
+
define i32 @foo()
|
| 365 |
+
{{
|
| 366 |
+
%.2 = load i32, i32* @A
|
| 367 |
+
%.3 = add i32 %.2, 2
|
| 368 |
+
ret i32 %.3
|
| 369 |
+
}}
|
| 370 |
+
|
| 371 |
+
@llvm.global_ctors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @ctor_A, i8* null}}]
|
| 372 |
+
@llvm.global_dtors = appending global [1 x {{i32, void ()*, i8*}}] [{{i32, void ()*, i8*}} {{i32 0, void ()* @dtor_A, i8* null}}]
|
| 373 |
+
""" # noqa E501
|
| 374 |
+
|
| 375 |
+
|
| 376 |
+
asm_nonalphanum_blocklabel = """; ModuleID = ""
|
| 377 |
+
target triple = "unknown-unknown-unknown"
|
| 378 |
+
target datalayout = ""
|
| 379 |
+
|
| 380 |
+
define i32 @"foo"()
|
| 381 |
+
{
|
| 382 |
+
"<>!*''#":
|
| 383 |
+
ret i32 12345
|
| 384 |
+
}
|
| 385 |
+
""" # noqa W291 # trailing space needed for match later
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
asm_null_constant = r"""
|
| 389 |
+
; ModuleID = '<string>'
|
| 390 |
+
target triple = "{triple}"
|
| 391 |
+
|
| 392 |
+
define void @foo(i64* %.1) {{
|
| 393 |
+
ret void
|
| 394 |
+
}}
|
| 395 |
+
|
| 396 |
+
define void @bar() {{
|
| 397 |
+
call void @foo(i64* null)
|
| 398 |
+
ret void
|
| 399 |
+
}}
|
| 400 |
+
"""
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
riscv_asm_ilp32 = [
|
| 404 |
+
'addi\tsp, sp, -16',
|
| 405 |
+
'sw\ta1, 8(sp)',
|
| 406 |
+
'sw\ta2, 12(sp)',
|
| 407 |
+
'fld\tft0, 8(sp)',
|
| 408 |
+
'fmv.w.x\tft1, a0',
|
| 409 |
+
'fcvt.d.s\tft1, ft1',
|
| 410 |
+
'fadd.d\tft0, ft1, ft0',
|
| 411 |
+
'fsd\tft0, 8(sp)',
|
| 412 |
+
'lw\ta0, 8(sp)',
|
| 413 |
+
'lw\ta1, 12(sp)',
|
| 414 |
+
'addi\tsp, sp, 16',
|
| 415 |
+
'ret'
|
| 416 |
+
]
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
riscv_asm_ilp32f = [
|
| 420 |
+
'addi\tsp, sp, -16',
|
| 421 |
+
'sw\ta0, 8(sp)',
|
| 422 |
+
'sw\ta1, 12(sp)',
|
| 423 |
+
'fld\tft0, 8(sp)',
|
| 424 |
+
'fcvt.d.s\tft1, fa0',
|
| 425 |
+
'fadd.d\tft0, ft1, ft0',
|
| 426 |
+
'fsd\tft0, 8(sp)',
|
| 427 |
+
'lw\ta0, 8(sp)',
|
| 428 |
+
'lw\ta1, 12(sp)',
|
| 429 |
+
'addi\tsp, sp, 16',
|
| 430 |
+
'ret'
|
| 431 |
+
]
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
riscv_asm_ilp32d = [
|
| 435 |
+
'fcvt.d.s\tft0, fa0',
|
| 436 |
+
'fadd.d\tfa0, ft0, fa1',
|
| 437 |
+
'ret'
|
| 438 |
+
]
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
asm_attributes = r"""
|
| 442 |
+
declare void @a_readonly_func(i8 *) readonly
|
| 443 |
+
|
| 444 |
+
declare i8* @a_arg0_return_func(i8* returned, i32*)
|
| 445 |
+
"""
|
| 446 |
+
|
| 447 |
+
|
| 448 |
+
# This produces the following output from objdump:
|
| 449 |
+
#
|
| 450 |
+
# $ objdump -D 632.elf
|
| 451 |
+
#
|
| 452 |
+
# 632.elf: file format elf64-x86-64
|
| 453 |
+
#
|
| 454 |
+
#
|
| 455 |
+
# Disassembly of section .text:
|
| 456 |
+
#
|
| 457 |
+
# 0000000000000000 <__arybo>:
|
| 458 |
+
# 0: 48 c1 e2 20 shl $0x20,%rdx
|
| 459 |
+
# 4: 48 09 c2 or %rax,%rdx
|
| 460 |
+
# 7: 48 89 d0 mov %rdx,%rax
|
| 461 |
+
# a: 48 c1 c0 3d rol $0x3d,%rax
|
| 462 |
+
# e: 48 31 d0 xor %rdx,%rax
|
| 463 |
+
# 11: 48 b9 01 20 00 04 80 movabs $0x7010008004002001,%rcx
|
| 464 |
+
# 18: 00 10 70
|
| 465 |
+
# 1b: 48 0f af c8 imul %rax,%rcx
|
| 466 |
+
|
| 467 |
+
issue_632_elf = \
|
| 468 |
+
"7f454c4602010100000000000000000001003e00010000000000000000000000000000" \
|
| 469 |
+
"0000000000e0000000000000000000000040000000000040000500010048c1e2204809" \
|
| 470 |
+
"c24889d048c1c03d4831d048b90120000480001070480fafc800000000000000000000" \
|
| 471 |
+
"0000000000000000000000000000002f0000000400f1ff000000000000000000000000" \
|
| 472 |
+
"00000000070000001200020000000000000000001f00000000000000002e7465787400" \
|
| 473 |
+
"5f5f617279626f002e6e6f74652e474e552d737461636b002e737472746162002e7379" \
|
| 474 |
+
"6d746162003c737472696e673e00000000000000000000000000000000000000000000" \
|
| 475 |
+
"0000000000000000000000000000000000000000000000000000000000000000000000" \
|
| 476 |
+
"00000000000000001f0000000300000000000000000000000000000000000000a80000" \
|
| 477 |
+
"0000000000380000000000000000000000000000000100000000000000000000000000" \
|
| 478 |
+
"000001000000010000000600000000000000000000000000000040000000000000001f" \
|
| 479 |
+
"000000000000000000000000000000100000000000000000000000000000000f000000" \
|
| 480 |
+
"01000000000000000000000000000000000000005f0000000000000000000000000000" \
|
| 481 |
+
"0000000000000000000100000000000000000000000000000027000000020000000000" \
|
| 482 |
+
"0000000000000000000000000000600000000000000048000000000000000100000002" \
|
| 483 |
+
"00000008000000000000001800000000000000"
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
issue_632_text = \
|
| 487 |
+
"48c1e2204809c24889d048c1c03d4831d048b90120000480001070480fafc8"
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
asm_tli_exp2 = r"""
|
| 491 |
+
; ModuleID = '<lambda>'
|
| 492 |
+
source_filename = "<string>"
|
| 493 |
+
target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
|
| 494 |
+
target triple = "x86_64-pc-windows-msvc"
|
| 495 |
+
|
| 496 |
+
declare float @llvm.exp2.f32(float %casted)
|
| 497 |
+
|
| 498 |
+
define float @foo(i16 %arg) {
|
| 499 |
+
entry:
|
| 500 |
+
%casted = sitofp i16 %arg to float
|
| 501 |
+
%ret = call float @llvm.exp2.f32(float %casted)
|
| 502 |
+
ret float %ret
|
| 503 |
+
}
|
| 504 |
+
""" # noqa E501
|
| 505 |
+
|
| 506 |
+
asm_phi_blocks = r"""
|
| 507 |
+
; ModuleID = '<string>'
|
| 508 |
+
target triple = "{triple}"
|
| 509 |
+
|
| 510 |
+
define void @foo(i32 %N) {{
|
| 511 |
+
; unnamed block for testing
|
| 512 |
+
%cmp4 = icmp sgt i32 %N, 0
|
| 513 |
+
br i1 %cmp4, label %for.body, label %for.cond.cleanup
|
| 514 |
+
|
| 515 |
+
for.cond.cleanup:
|
| 516 |
+
ret void
|
| 517 |
+
|
| 518 |
+
for.body:
|
| 519 |
+
%i.05 = phi i32 [ %inc, %for.body ], [ 0, %0 ]
|
| 520 |
+
%inc = add nuw nsw i32 %i.05, 1
|
| 521 |
+
%exitcond.not = icmp eq i32 %inc, %N
|
| 522 |
+
br i1 %exitcond.not, label %for.cond.cleanup, label %for.body
|
| 523 |
+
}}
|
| 524 |
+
"""
|
| 525 |
+
|
| 526 |
+
|
| 527 |
+
class BaseTest(TestCase):
|
| 528 |
+
|
| 529 |
+
def setUp(self):
|
| 530 |
+
llvm.initialize()
|
| 531 |
+
llvm.initialize_native_target()
|
| 532 |
+
llvm.initialize_native_asmprinter()
|
| 533 |
+
gc.collect()
|
| 534 |
+
self.old_garbage = gc.garbage[:]
|
| 535 |
+
gc.garbage[:] = []
|
| 536 |
+
|
| 537 |
+
def tearDown(self):
|
| 538 |
+
# Test that no uncollectable objects were created
|
| 539 |
+
# (llvmlite objects have a __del__ so a reference cycle could
|
| 540 |
+
# create some).
|
| 541 |
+
gc.collect()
|
| 542 |
+
self.assertEqual(gc.garbage, [])
|
| 543 |
+
# This will probably put any existing garbage in gc.garbage again
|
| 544 |
+
del self.old_garbage
|
| 545 |
+
|
| 546 |
+
def module(self, asm=asm_sum, context=None):
|
| 547 |
+
asm = asm.format(triple=llvm.get_default_triple())
|
| 548 |
+
mod = llvm.parse_assembly(asm, context)
|
| 549 |
+
return mod
|
| 550 |
+
|
| 551 |
+
def glob(self, name='glob', mod=None):
|
| 552 |
+
if mod is None:
|
| 553 |
+
mod = self.module()
|
| 554 |
+
return mod.get_global_variable(name)
|
| 555 |
+
|
| 556 |
+
def target_machine(self, *, jit):
|
| 557 |
+
target = llvm.Target.from_default_triple()
|
| 558 |
+
return target.create_target_machine(jit=jit)
|
| 559 |
+
|
| 560 |
+
|
| 561 |
+
class TestDependencies(BaseTest):
|
| 562 |
+
"""
|
| 563 |
+
Test DLL dependencies are within a certain expected set.
|
| 564 |
+
"""
|
| 565 |
+
|
| 566 |
+
@unittest.skipUnless(sys.platform.startswith('linux'),
|
| 567 |
+
"Linux-specific test")
|
| 568 |
+
@unittest.skipUnless(os.environ.get('LLVMLITE_DIST_TEST'),
|
| 569 |
+
"Distribution-specific test")
|
| 570 |
+
def test_linux(self):
|
| 571 |
+
lib_path = ffi.lib._name
|
| 572 |
+
env = os.environ.copy()
|
| 573 |
+
env['LANG'] = 'C'
|
| 574 |
+
p = subprocess.Popen(["objdump", "-p", lib_path],
|
| 575 |
+
stdout=subprocess.PIPE, env=env)
|
| 576 |
+
out, _ = p.communicate()
|
| 577 |
+
self.assertEqual(0, p.returncode)
|
| 578 |
+
# Parse library dependencies
|
| 579 |
+
lib_pat = re.compile(r'^([+-_a-zA-Z0-9]+)\.so(?:\.\d+){0,3}$')
|
| 580 |
+
deps = set()
|
| 581 |
+
for line in out.decode().splitlines():
|
| 582 |
+
parts = line.split()
|
| 583 |
+
if parts and parts[0] == 'NEEDED':
|
| 584 |
+
dep = parts[1]
|
| 585 |
+
m = lib_pat.match(dep)
|
| 586 |
+
if len(parts) != 2 or not m:
|
| 587 |
+
self.fail("invalid NEEDED line: %r" % (line,))
|
| 588 |
+
deps.add(m.group(1))
|
| 589 |
+
# Sanity check that our dependencies were parsed ok
|
| 590 |
+
if 'libc' not in deps or 'libpthread' not in deps:
|
| 591 |
+
self.fail("failed parsing dependencies? got %r" % (deps,))
|
| 592 |
+
# Ensure all dependencies are expected
|
| 593 |
+
allowed = set(['librt', 'libdl', 'libpthread', 'libz', 'libm',
|
| 594 |
+
'libgcc_s', 'libc', 'ld-linux', 'ld64'])
|
| 595 |
+
if platform.python_implementation() == 'PyPy':
|
| 596 |
+
allowed.add('libtinfo')
|
| 597 |
+
|
| 598 |
+
for dep in deps:
|
| 599 |
+
if not dep.startswith('ld-linux-') and dep not in allowed:
|
| 600 |
+
self.fail("unexpected dependency %r in %r" % (dep, deps))
|
| 601 |
+
|
| 602 |
+
|
| 603 |
+
class TestRISCVABI(BaseTest):
|
| 604 |
+
"""
|
| 605 |
+
Test calling convention of floating point arguments of RISC-V
|
| 606 |
+
using different ABI.
|
| 607 |
+
"""
|
| 608 |
+
triple = "riscv32-unknown-linux"
|
| 609 |
+
|
| 610 |
+
def setUp(self):
|
| 611 |
+
super().setUp()
|
| 612 |
+
llvm.initialize_all_targets()
|
| 613 |
+
llvm.initialize_all_asmprinters()
|
| 614 |
+
|
| 615 |
+
def check_riscv_target(self):
|
| 616 |
+
try:
|
| 617 |
+
llvm.Target.from_triple(self.triple)
|
| 618 |
+
except RuntimeError as e:
|
| 619 |
+
if "No available targets are compatible with triple" in str(e):
|
| 620 |
+
self.skipTest("RISCV target unsupported by linked LLVM.")
|
| 621 |
+
else:
|
| 622 |
+
raise e
|
| 623 |
+
|
| 624 |
+
def riscv_target_machine(self, **kwarg):
|
| 625 |
+
lltarget = llvm.Target.from_triple(self.triple)
|
| 626 |
+
return lltarget.create_target_machine(**kwarg)
|
| 627 |
+
|
| 628 |
+
def fpadd_ll_module(self):
|
| 629 |
+
f64 = ir.DoubleType()
|
| 630 |
+
f32 = ir.FloatType()
|
| 631 |
+
fnty = ir.FunctionType(f64, (f32, f64))
|
| 632 |
+
module = ir.Module()
|
| 633 |
+
func = ir.Function(module, fnty, name="fpadd")
|
| 634 |
+
block = func.append_basic_block()
|
| 635 |
+
builder = ir.IRBuilder(block)
|
| 636 |
+
a, b = func.args
|
| 637 |
+
arg0 = builder.fpext(a, f64)
|
| 638 |
+
result = builder.fadd(arg0, b)
|
| 639 |
+
builder.ret(result)
|
| 640 |
+
|
| 641 |
+
llmod = llvm.parse_assembly(str(module))
|
| 642 |
+
llmod.verify()
|
| 643 |
+
return llmod
|
| 644 |
+
|
| 645 |
+
def break_up_asm(self, asm):
|
| 646 |
+
asm_list = []
|
| 647 |
+
for line in asm.splitlines():
|
| 648 |
+
s_line = line.strip()
|
| 649 |
+
if not (s_line.startswith(".") or s_line.startswith("fpadd")
|
| 650 |
+
or s_line == ""):
|
| 651 |
+
asm_list.append(s_line)
|
| 652 |
+
return asm_list
|
| 653 |
+
|
| 654 |
+
def test_rv32d_ilp32(self):
|
| 655 |
+
self.check_riscv_target()
|
| 656 |
+
llmod = self.fpadd_ll_module()
|
| 657 |
+
target = self.riscv_target_machine(features="+f,+d", abiname="ilp32")
|
| 658 |
+
self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)),
|
| 659 |
+
riscv_asm_ilp32)
|
| 660 |
+
|
| 661 |
+
def test_rv32d_ilp32f(self):
|
| 662 |
+
self.check_riscv_target()
|
| 663 |
+
llmod = self.fpadd_ll_module()
|
| 664 |
+
target = self.riscv_target_machine(features="+f,+d", abiname="ilp32f")
|
| 665 |
+
self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)),
|
| 666 |
+
riscv_asm_ilp32f)
|
| 667 |
+
|
| 668 |
+
def test_rv32d_ilp32d(self):
|
| 669 |
+
self.check_riscv_target()
|
| 670 |
+
llmod = self.fpadd_ll_module()
|
| 671 |
+
target = self.riscv_target_machine(features="+f,+d", abiname="ilp32d")
|
| 672 |
+
self.assertEqual(self.break_up_asm(target.emit_assembly(llmod)),
|
| 673 |
+
riscv_asm_ilp32d)
|
| 674 |
+
|
| 675 |
+
|
| 676 |
+
class TestMisc(BaseTest):
|
| 677 |
+
"""
|
| 678 |
+
Test miscellaneous functions in llvm.binding.
|
| 679 |
+
"""
|
| 680 |
+
|
| 681 |
+
def test_parse_assembly(self):
|
| 682 |
+
self.module(asm_sum)
|
| 683 |
+
|
| 684 |
+
def test_parse_assembly_error(self):
|
| 685 |
+
with self.assertRaises(RuntimeError) as cm:
|
| 686 |
+
self.module(asm_parse_error)
|
| 687 |
+
s = str(cm.exception)
|
| 688 |
+
self.assertIn("parsing error", s)
|
| 689 |
+
self.assertIn("invalid operand type", s)
|
| 690 |
+
|
| 691 |
+
def test_nonalphanum_block_name(self):
|
| 692 |
+
mod = ir.Module()
|
| 693 |
+
ft = ir.FunctionType(ir.IntType(32), [])
|
| 694 |
+
fn = ir.Function(mod, ft, "foo")
|
| 695 |
+
bd = ir.IRBuilder(fn.append_basic_block(name="<>!*''#"))
|
| 696 |
+
bd.ret(ir.Constant(ir.IntType(32), 12345))
|
| 697 |
+
asm = str(mod)
|
| 698 |
+
self.assertEqual(asm, asm_nonalphanum_blocklabel)
|
| 699 |
+
|
| 700 |
+
def test_global_context(self):
|
| 701 |
+
gcontext1 = llvm.context.get_global_context()
|
| 702 |
+
gcontext2 = llvm.context.get_global_context()
|
| 703 |
+
assert gcontext1 == gcontext2
|
| 704 |
+
|
| 705 |
+
def test_dylib_symbols(self):
|
| 706 |
+
llvm.add_symbol("__xyzzy", 1234)
|
| 707 |
+
llvm.add_symbol("__xyzzy", 5678)
|
| 708 |
+
addr = llvm.address_of_symbol("__xyzzy")
|
| 709 |
+
self.assertEqual(addr, 5678)
|
| 710 |
+
addr = llvm.address_of_symbol("__foobar")
|
| 711 |
+
self.assertIs(addr, None)
|
| 712 |
+
|
| 713 |
+
def test_get_default_triple(self):
|
| 714 |
+
triple = llvm.get_default_triple()
|
| 715 |
+
self.assertIsInstance(triple, str)
|
| 716 |
+
self.assertTrue(triple)
|
| 717 |
+
|
| 718 |
+
def test_get_process_triple(self):
|
| 719 |
+
# Sometimes we get synonyms for PPC
|
| 720 |
+
def normalize_ppc(arch):
|
| 721 |
+
if arch == 'powerpc64le':
|
| 722 |
+
return 'ppc64le'
|
| 723 |
+
else:
|
| 724 |
+
return arch
|
| 725 |
+
|
| 726 |
+
triple = llvm.get_process_triple()
|
| 727 |
+
default = llvm.get_default_triple()
|
| 728 |
+
self.assertIsInstance(triple, str)
|
| 729 |
+
self.assertTrue(triple)
|
| 730 |
+
|
| 731 |
+
default_arch = normalize_ppc(default.split('-')[0])
|
| 732 |
+
triple_arch = normalize_ppc(triple.split('-')[0])
|
| 733 |
+
# Arch must be equal
|
| 734 |
+
self.assertEqual(default_arch, triple_arch)
|
| 735 |
+
|
| 736 |
+
def test_get_host_cpu_features(self):
|
| 737 |
+
features = llvm.get_host_cpu_features()
|
| 738 |
+
# Check the content of `features`
|
| 739 |
+
self.assertIsInstance(features, dict)
|
| 740 |
+
self.assertIsInstance(features, llvm.FeatureMap)
|
| 741 |
+
for k, v in features.items():
|
| 742 |
+
self.assertIsInstance(k, str)
|
| 743 |
+
self.assertTrue(k) # single feature string cannot be empty
|
| 744 |
+
self.assertIsInstance(v, bool)
|
| 745 |
+
self.assertIsInstance(features.flatten(), str)
|
| 746 |
+
|
| 747 |
+
re_term = r"[+\-][a-zA-Z0-9\._-]+"
|
| 748 |
+
regex = r"^({0}|{0}(,{0})*)?$".format(re_term)
|
| 749 |
+
# quick check for our regex
|
| 750 |
+
self.assertIsNotNone(re.match(regex, ""))
|
| 751 |
+
self.assertIsNotNone(re.match(regex, "+aa"))
|
| 752 |
+
self.assertIsNotNone(re.match(regex, "+a,-bb"))
|
| 753 |
+
# check CpuFeature.flatten()
|
| 754 |
+
if len(features) == 0:
|
| 755 |
+
self.assertEqual(features.flatten(), "")
|
| 756 |
+
else:
|
| 757 |
+
self.assertIsNotNone(re.match(regex, features.flatten()))
|
| 758 |
+
|
| 759 |
+
def test_get_host_cpu_name(self):
|
| 760 |
+
cpu = llvm.get_host_cpu_name()
|
| 761 |
+
self.assertIsInstance(cpu, str)
|
| 762 |
+
self.assertTrue(cpu)
|
| 763 |
+
|
| 764 |
+
def test_initfini(self):
|
| 765 |
+
code = """if 1:
|
| 766 |
+
from llvmlite import binding as llvm
|
| 767 |
+
|
| 768 |
+
llvm.initialize()
|
| 769 |
+
llvm.initialize_native_target()
|
| 770 |
+
llvm.initialize_native_asmprinter()
|
| 771 |
+
llvm.initialize_all_targets()
|
| 772 |
+
llvm.initialize_all_asmprinters()
|
| 773 |
+
llvm.shutdown()
|
| 774 |
+
"""
|
| 775 |
+
subprocess.check_call([sys.executable, "-c", code])
|
| 776 |
+
|
| 777 |
+
def test_set_option(self):
|
| 778 |
+
# We cannot set an option multiple times (LLVM would exit() the
|
| 779 |
+
# process), so run the code in a subprocess.
|
| 780 |
+
code = """if 1:
|
| 781 |
+
from llvmlite import binding as llvm
|
| 782 |
+
|
| 783 |
+
llvm.set_option("progname", "-debug-pass=Disabled")
|
| 784 |
+
"""
|
| 785 |
+
subprocess.check_call([sys.executable, "-c", code])
|
| 786 |
+
|
| 787 |
+
def test_version(self):
|
| 788 |
+
major, minor, patch = llvm.llvm_version_info
|
| 789 |
+
# one of these can be valid
|
| 790 |
+
valid = (14, 15)
|
| 791 |
+
self.assertIn(major, valid)
|
| 792 |
+
self.assertIn(patch, range(8))
|
| 793 |
+
|
| 794 |
+
def test_check_jit_execution(self):
|
| 795 |
+
llvm.check_jit_execution()
|
| 796 |
+
|
| 797 |
+
@unittest.skipIf(no_de_locale(), "Locale not available")
|
| 798 |
+
def test_print_double_locale(self):
|
| 799 |
+
m = self.module(asm_double_locale)
|
| 800 |
+
expect = str(m)
|
| 801 |
+
# Change the locale so that comma is used as decimal-point
|
| 802 |
+
# to trigger the LLVM bug (llvmlite issue #80)
|
| 803 |
+
locale.setlocale(locale.LC_ALL, 'de_DE')
|
| 804 |
+
# The LLVM bug is trigged by print the module with double constant
|
| 805 |
+
got = str(m)
|
| 806 |
+
# Changing the locale should not affect the LLVM IR
|
| 807 |
+
self.assertEqual(expect, got)
|
| 808 |
+
|
| 809 |
+
def test_no_accidental_warnings(self):
|
| 810 |
+
code = "from llvmlite import binding"
|
| 811 |
+
flags = "-Werror"
|
| 812 |
+
cmdargs = [sys.executable, flags, "-c", code]
|
| 813 |
+
subprocess.check_call(cmdargs)
|
| 814 |
+
|
| 815 |
+
|
| 816 |
+
class TestModuleRef(BaseTest):
|
| 817 |
+
|
| 818 |
+
def test_str(self):
|
| 819 |
+
mod = self.module()
|
| 820 |
+
s = str(mod).strip()
|
| 821 |
+
self.assertTrue(s.startswith('; ModuleID ='), s)
|
| 822 |
+
|
| 823 |
+
def test_close(self):
|
| 824 |
+
mod = self.module()
|
| 825 |
+
str(mod)
|
| 826 |
+
mod.close()
|
| 827 |
+
with self.assertRaises(ctypes.ArgumentError):
|
| 828 |
+
str(mod)
|
| 829 |
+
mod.close()
|
| 830 |
+
|
| 831 |
+
def test_with(self):
|
| 832 |
+
mod = self.module()
|
| 833 |
+
str(mod)
|
| 834 |
+
with mod:
|
| 835 |
+
str(mod)
|
| 836 |
+
with self.assertRaises(ctypes.ArgumentError):
|
| 837 |
+
str(mod)
|
| 838 |
+
with self.assertRaises(RuntimeError):
|
| 839 |
+
with mod:
|
| 840 |
+
pass
|
| 841 |
+
|
| 842 |
+
def test_name(self):
|
| 843 |
+
mod = self.module()
|
| 844 |
+
mod.name = "foo"
|
| 845 |
+
self.assertEqual(mod.name, "foo")
|
| 846 |
+
mod.name = "bar"
|
| 847 |
+
self.assertEqual(mod.name, "bar")
|
| 848 |
+
|
| 849 |
+
def test_source_file(self):
|
| 850 |
+
mod = self.module()
|
| 851 |
+
self.assertEqual(mod.source_file, "asm_sum.c")
|
| 852 |
+
|
| 853 |
+
def test_data_layout(self):
|
| 854 |
+
mod = self.module()
|
| 855 |
+
s = mod.data_layout
|
| 856 |
+
self.assertIsInstance(s, str)
|
| 857 |
+
mod.data_layout = s
|
| 858 |
+
self.assertEqual(s, mod.data_layout)
|
| 859 |
+
|
| 860 |
+
def test_triple(self):
|
| 861 |
+
mod = self.module()
|
| 862 |
+
s = mod.triple
|
| 863 |
+
self.assertEqual(s, llvm.get_default_triple())
|
| 864 |
+
mod.triple = ''
|
| 865 |
+
self.assertEqual(mod.triple, '')
|
| 866 |
+
|
| 867 |
+
def test_verify(self):
|
| 868 |
+
# Verify successful
|
| 869 |
+
mod = self.module()
|
| 870 |
+
self.assertIs(mod.verify(), None)
|
| 871 |
+
# Verify failed
|
| 872 |
+
mod = self.module(asm_verification_fail)
|
| 873 |
+
with self.assertRaises(RuntimeError) as cm:
|
| 874 |
+
mod.verify()
|
| 875 |
+
s = str(cm.exception)
|
| 876 |
+
self.assertIn("%.bug = add i32 1, %.bug", s)
|
| 877 |
+
|
| 878 |
+
def test_get_function(self):
|
| 879 |
+
mod = self.module()
|
| 880 |
+
fn = mod.get_function("sum")
|
| 881 |
+
self.assertIsInstance(fn, llvm.ValueRef)
|
| 882 |
+
self.assertEqual(fn.name, "sum")
|
| 883 |
+
|
| 884 |
+
with self.assertRaises(NameError):
|
| 885 |
+
mod.get_function("foo")
|
| 886 |
+
|
| 887 |
+
# Check that fn keeps the module instance alive
|
| 888 |
+
del mod
|
| 889 |
+
str(fn.module)
|
| 890 |
+
|
| 891 |
+
def test_get_struct_type(self):
|
| 892 |
+
mod = self.module()
|
| 893 |
+
st_ty = mod.get_struct_type("struct.glob_type")
|
| 894 |
+
self.assertEqual(st_ty.name, "struct.glob_type")
|
| 895 |
+
# also match struct names of form "%struct.glob_type.{some_index}"
|
| 896 |
+
self.assertIsNotNone(re.match(
|
| 897 |
+
r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }',
|
| 898 |
+
str(st_ty)))
|
| 899 |
+
|
| 900 |
+
with self.assertRaises(NameError):
|
| 901 |
+
mod.get_struct_type("struct.doesnt_exist")
|
| 902 |
+
|
| 903 |
+
def test_get_global_variable(self):
|
| 904 |
+
mod = self.module()
|
| 905 |
+
gv = mod.get_global_variable("glob")
|
| 906 |
+
self.assertIsInstance(gv, llvm.ValueRef)
|
| 907 |
+
self.assertEqual(gv.name, "glob")
|
| 908 |
+
|
| 909 |
+
with self.assertRaises(NameError):
|
| 910 |
+
mod.get_global_variable("bar")
|
| 911 |
+
|
| 912 |
+
# Check that gv keeps the module instance alive
|
| 913 |
+
del mod
|
| 914 |
+
str(gv.module)
|
| 915 |
+
|
| 916 |
+
def test_global_variables(self):
|
| 917 |
+
mod = self.module()
|
| 918 |
+
it = mod.global_variables
|
| 919 |
+
del mod
|
| 920 |
+
globs = sorted(it, key=lambda value: value.name)
|
| 921 |
+
self.assertEqual(len(globs), 4)
|
| 922 |
+
self.assertEqual([g.name for g in globs],
|
| 923 |
+
["glob", "glob_b", "glob_f", "glob_struct"])
|
| 924 |
+
|
| 925 |
+
def test_functions(self):
|
| 926 |
+
mod = self.module()
|
| 927 |
+
it = mod.functions
|
| 928 |
+
del mod
|
| 929 |
+
funcs = list(it)
|
| 930 |
+
self.assertEqual(len(funcs), 1)
|
| 931 |
+
self.assertEqual(funcs[0].name, "sum")
|
| 932 |
+
|
| 933 |
+
def test_structs(self):
|
| 934 |
+
mod = self.module()
|
| 935 |
+
it = mod.struct_types
|
| 936 |
+
del mod
|
| 937 |
+
structs = list(it)
|
| 938 |
+
self.assertEqual(len(structs), 1)
|
| 939 |
+
self.assertIsNotNone(re.match(r'struct\.glob_type(\.[\d]+)?',
|
| 940 |
+
structs[0].name))
|
| 941 |
+
self.assertIsNotNone(re.match(
|
| 942 |
+
r'%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }',
|
| 943 |
+
str(structs[0])))
|
| 944 |
+
|
| 945 |
+
def test_link_in(self):
|
| 946 |
+
dest = self.module()
|
| 947 |
+
src = self.module(asm_mul)
|
| 948 |
+
dest.link_in(src)
|
| 949 |
+
self.assertEqual(
|
| 950 |
+
sorted(f.name for f in dest.functions), ["mul", "sum"])
|
| 951 |
+
dest.get_function("mul")
|
| 952 |
+
dest.close()
|
| 953 |
+
with self.assertRaises(ctypes.ArgumentError):
|
| 954 |
+
src.get_function("mul")
|
| 955 |
+
|
| 956 |
+
def test_link_in_preserve(self):
|
| 957 |
+
dest = self.module()
|
| 958 |
+
src2 = self.module(asm_mul)
|
| 959 |
+
dest.link_in(src2, preserve=True)
|
| 960 |
+
self.assertEqual(
|
| 961 |
+
sorted(f.name for f in dest.functions), ["mul", "sum"])
|
| 962 |
+
dest.close()
|
| 963 |
+
self.assertEqual(sorted(f.name for f in src2.functions), ["mul"])
|
| 964 |
+
src2.get_function("mul")
|
| 965 |
+
|
| 966 |
+
def test_link_in_error(self):
|
| 967 |
+
# Raise an error by trying to link two modules with the same global
|
| 968 |
+
# definition "sum".
|
| 969 |
+
dest = self.module()
|
| 970 |
+
src = self.module(asm_sum2)
|
| 971 |
+
with self.assertRaises(RuntimeError) as cm:
|
| 972 |
+
dest.link_in(src)
|
| 973 |
+
self.assertIn("symbol multiply defined", str(cm.exception))
|
| 974 |
+
|
| 975 |
+
def test_as_bitcode(self):
|
| 976 |
+
mod = self.module()
|
| 977 |
+
bc = mod.as_bitcode()
|
| 978 |
+
# Refer to http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00064 # noqa E501
|
| 979 |
+
# and http://llvm.org/docs/doxygen/html/ReaderWriter_8h_source.html#l00092 # noqa E501
|
| 980 |
+
bitcode_wrapper_magic = b'\xde\xc0\x17\x0b'
|
| 981 |
+
bitcode_magic = b'BC'
|
| 982 |
+
self.assertTrue(bc.startswith(bitcode_magic) or
|
| 983 |
+
bc.startswith(bitcode_wrapper_magic))
|
| 984 |
+
|
| 985 |
+
def test_parse_bitcode_error(self):
|
| 986 |
+
with self.assertRaises(RuntimeError) as cm:
|
| 987 |
+
llvm.parse_bitcode(b"")
|
| 988 |
+
self.assertIn("LLVM bitcode parsing error", str(cm.exception))
|
| 989 |
+
# for llvm < 9
|
| 990 |
+
if llvm.llvm_version_info[0] < 9:
|
| 991 |
+
self.assertIn("Invalid bitcode signature", str(cm.exception))
|
| 992 |
+
else:
|
| 993 |
+
self.assertIn(
|
| 994 |
+
"file too small to contain bitcode header", str(cm.exception),
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
def test_bitcode_roundtrip(self):
|
| 998 |
+
# create a new context to avoid struct renaming
|
| 999 |
+
context1 = llvm.create_context()
|
| 1000 |
+
bc = self.module(context=context1).as_bitcode()
|
| 1001 |
+
context2 = llvm.create_context()
|
| 1002 |
+
mod = llvm.parse_bitcode(bc, context2)
|
| 1003 |
+
self.assertEqual(mod.as_bitcode(), bc)
|
| 1004 |
+
|
| 1005 |
+
mod.get_function("sum")
|
| 1006 |
+
mod.get_global_variable("glob")
|
| 1007 |
+
|
| 1008 |
+
def test_cloning(self):
|
| 1009 |
+
m = self.module()
|
| 1010 |
+
cloned = m.clone()
|
| 1011 |
+
self.assertIsNot(cloned, m)
|
| 1012 |
+
self.assertEqual(cloned.as_bitcode(), m.as_bitcode())
|
| 1013 |
+
|
| 1014 |
+
|
| 1015 |
+
class JITTestMixin(object):
|
| 1016 |
+
"""
|
| 1017 |
+
Mixin for ExecutionEngine tests.
|
| 1018 |
+
"""
|
| 1019 |
+
|
| 1020 |
+
def get_sum(self, ee, func_name="sum"):
|
| 1021 |
+
ee.finalize_object()
|
| 1022 |
+
cfptr = ee.get_function_address(func_name)
|
| 1023 |
+
self.assertTrue(cfptr)
|
| 1024 |
+
return CFUNCTYPE(c_int, c_int, c_int)(cfptr)
|
| 1025 |
+
|
| 1026 |
+
def test_run_code(self):
|
| 1027 |
+
mod = self.module()
|
| 1028 |
+
with self.jit(mod) as ee:
|
| 1029 |
+
cfunc = self.get_sum(ee)
|
| 1030 |
+
res = cfunc(2, -5)
|
| 1031 |
+
self.assertEqual(-3, res)
|
| 1032 |
+
|
| 1033 |
+
def test_close(self):
|
| 1034 |
+
ee = self.jit(self.module())
|
| 1035 |
+
ee.close()
|
| 1036 |
+
ee.close()
|
| 1037 |
+
with self.assertRaises(ctypes.ArgumentError):
|
| 1038 |
+
ee.finalize_object()
|
| 1039 |
+
|
| 1040 |
+
def test_with(self):
|
| 1041 |
+
ee = self.jit(self.module())
|
| 1042 |
+
with ee:
|
| 1043 |
+
pass
|
| 1044 |
+
with self.assertRaises(RuntimeError):
|
| 1045 |
+
with ee:
|
| 1046 |
+
pass
|
| 1047 |
+
with self.assertRaises(ctypes.ArgumentError):
|
| 1048 |
+
ee.finalize_object()
|
| 1049 |
+
|
| 1050 |
+
def test_module_lifetime(self):
|
| 1051 |
+
mod = self.module()
|
| 1052 |
+
ee = self.jit(mod)
|
| 1053 |
+
ee.close()
|
| 1054 |
+
mod.close()
|
| 1055 |
+
|
| 1056 |
+
def test_module_lifetime2(self):
|
| 1057 |
+
mod = self.module()
|
| 1058 |
+
ee = self.jit(mod)
|
| 1059 |
+
mod.close()
|
| 1060 |
+
ee.close()
|
| 1061 |
+
|
| 1062 |
+
def test_add_module(self):
|
| 1063 |
+
ee = self.jit(self.module())
|
| 1064 |
+
mod = self.module(asm_mul)
|
| 1065 |
+
ee.add_module(mod)
|
| 1066 |
+
with self.assertRaises(KeyError):
|
| 1067 |
+
ee.add_module(mod)
|
| 1068 |
+
self.assertFalse(mod.closed)
|
| 1069 |
+
ee.close()
|
| 1070 |
+
self.assertTrue(mod.closed)
|
| 1071 |
+
|
| 1072 |
+
def test_add_module_lifetime(self):
|
| 1073 |
+
ee = self.jit(self.module())
|
| 1074 |
+
mod = self.module(asm_mul)
|
| 1075 |
+
ee.add_module(mod)
|
| 1076 |
+
mod.close()
|
| 1077 |
+
ee.close()
|
| 1078 |
+
|
| 1079 |
+
def test_add_module_lifetime2(self):
|
| 1080 |
+
ee = self.jit(self.module())
|
| 1081 |
+
mod = self.module(asm_mul)
|
| 1082 |
+
ee.add_module(mod)
|
| 1083 |
+
ee.close()
|
| 1084 |
+
mod.close()
|
| 1085 |
+
|
| 1086 |
+
def test_remove_module(self):
|
| 1087 |
+
ee = self.jit(self.module())
|
| 1088 |
+
mod = self.module(asm_mul)
|
| 1089 |
+
ee.add_module(mod)
|
| 1090 |
+
ee.remove_module(mod)
|
| 1091 |
+
with self.assertRaises(KeyError):
|
| 1092 |
+
ee.remove_module(mod)
|
| 1093 |
+
self.assertFalse(mod.closed)
|
| 1094 |
+
ee.close()
|
| 1095 |
+
self.assertFalse(mod.closed)
|
| 1096 |
+
|
| 1097 |
+
def test_target_data(self):
|
| 1098 |
+
mod = self.module()
|
| 1099 |
+
ee = self.jit(mod)
|
| 1100 |
+
td = ee.target_data
|
| 1101 |
+
# A singleton is returned
|
| 1102 |
+
self.assertIs(ee.target_data, td)
|
| 1103 |
+
str(td)
|
| 1104 |
+
del mod, ee
|
| 1105 |
+
str(td)
|
| 1106 |
+
|
| 1107 |
+
def test_target_data_abi_enquiries(self):
|
| 1108 |
+
mod = self.module()
|
| 1109 |
+
ee = self.jit(mod)
|
| 1110 |
+
td = ee.target_data
|
| 1111 |
+
gv_i32 = mod.get_global_variable("glob")
|
| 1112 |
+
gv_i8 = mod.get_global_variable("glob_b")
|
| 1113 |
+
gv_struct = mod.get_global_variable("glob_struct")
|
| 1114 |
+
# A global is a pointer, it has the ABI size of a pointer
|
| 1115 |
+
pointer_size = 4 if sys.maxsize < 2 ** 32 else 8
|
| 1116 |
+
for g in (gv_i32, gv_i8, gv_struct):
|
| 1117 |
+
self.assertEqual(td.get_abi_size(g.type), pointer_size)
|
| 1118 |
+
|
| 1119 |
+
self.assertEqual(td.get_pointee_abi_size(gv_i32.type), 4)
|
| 1120 |
+
self.assertEqual(td.get_pointee_abi_alignment(gv_i32.type), 4)
|
| 1121 |
+
|
| 1122 |
+
self.assertEqual(td.get_pointee_abi_size(gv_i8.type), 1)
|
| 1123 |
+
self.assertIn(td.get_pointee_abi_alignment(gv_i8.type), (1, 2, 4))
|
| 1124 |
+
|
| 1125 |
+
self.assertEqual(td.get_pointee_abi_size(gv_struct.type), 24)
|
| 1126 |
+
self.assertIn(td.get_pointee_abi_alignment(gv_struct.type), (4, 8))
|
| 1127 |
+
|
| 1128 |
+
def test_object_cache_notify(self):
|
| 1129 |
+
notifies = []
|
| 1130 |
+
|
| 1131 |
+
def notify(mod, buf):
|
| 1132 |
+
notifies.append((mod, buf))
|
| 1133 |
+
|
| 1134 |
+
mod = self.module()
|
| 1135 |
+
ee = self.jit(mod)
|
| 1136 |
+
ee.set_object_cache(notify)
|
| 1137 |
+
|
| 1138 |
+
self.assertEqual(len(notifies), 0)
|
| 1139 |
+
cfunc = self.get_sum(ee)
|
| 1140 |
+
cfunc(2, -5)
|
| 1141 |
+
self.assertEqual(len(notifies), 1)
|
| 1142 |
+
# The right module object was found
|
| 1143 |
+
self.assertIs(notifies[0][0], mod)
|
| 1144 |
+
self.assertIsInstance(notifies[0][1], bytes)
|
| 1145 |
+
|
| 1146 |
+
notifies[:] = []
|
| 1147 |
+
mod2 = self.module(asm_mul)
|
| 1148 |
+
ee.add_module(mod2)
|
| 1149 |
+
cfunc = self.get_sum(ee, "mul")
|
| 1150 |
+
self.assertEqual(len(notifies), 1)
|
| 1151 |
+
# The right module object was found
|
| 1152 |
+
self.assertIs(notifies[0][0], mod2)
|
| 1153 |
+
self.assertIsInstance(notifies[0][1], bytes)
|
| 1154 |
+
|
| 1155 |
+
def test_object_cache_getbuffer(self):
|
| 1156 |
+
notifies = []
|
| 1157 |
+
getbuffers = []
|
| 1158 |
+
|
| 1159 |
+
def notify(mod, buf):
|
| 1160 |
+
notifies.append((mod, buf))
|
| 1161 |
+
|
| 1162 |
+
def getbuffer(mod):
|
| 1163 |
+
getbuffers.append(mod)
|
| 1164 |
+
|
| 1165 |
+
mod = self.module()
|
| 1166 |
+
ee = self.jit(mod)
|
| 1167 |
+
ee.set_object_cache(notify, getbuffer)
|
| 1168 |
+
|
| 1169 |
+
# First return None from getbuffer(): the object is compiled normally
|
| 1170 |
+
self.assertEqual(len(notifies), 0)
|
| 1171 |
+
self.assertEqual(len(getbuffers), 0)
|
| 1172 |
+
cfunc = self.get_sum(ee)
|
| 1173 |
+
self.assertEqual(len(notifies), 1)
|
| 1174 |
+
self.assertEqual(len(getbuffers), 1)
|
| 1175 |
+
self.assertIs(getbuffers[0], mod)
|
| 1176 |
+
sum_buffer = notifies[0][1]
|
| 1177 |
+
|
| 1178 |
+
# Recreate a new EE, and use getbuffer() to return the previously
|
| 1179 |
+
# compiled object.
|
| 1180 |
+
|
| 1181 |
+
def getbuffer_successful(mod):
|
| 1182 |
+
getbuffers.append(mod)
|
| 1183 |
+
return sum_buffer
|
| 1184 |
+
|
| 1185 |
+
notifies[:] = []
|
| 1186 |
+
getbuffers[:] = []
|
| 1187 |
+
# Use another source module to make sure it is ignored
|
| 1188 |
+
mod = self.module(asm_mul)
|
| 1189 |
+
ee = self.jit(mod)
|
| 1190 |
+
ee.set_object_cache(notify, getbuffer_successful)
|
| 1191 |
+
|
| 1192 |
+
self.assertEqual(len(notifies), 0)
|
| 1193 |
+
self.assertEqual(len(getbuffers), 0)
|
| 1194 |
+
cfunc = self.get_sum(ee)
|
| 1195 |
+
self.assertEqual(cfunc(2, -5), -3)
|
| 1196 |
+
self.assertEqual(len(notifies), 0)
|
| 1197 |
+
self.assertEqual(len(getbuffers), 1)
|
| 1198 |
+
|
| 1199 |
+
|
| 1200 |
+
class JITWithTMTestMixin(JITTestMixin):
|
| 1201 |
+
|
| 1202 |
+
def test_emit_assembly(self):
|
| 1203 |
+
"""Test TargetMachineRef.emit_assembly()"""
|
| 1204 |
+
target_machine = self.target_machine(jit=True)
|
| 1205 |
+
mod = self.module()
|
| 1206 |
+
ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive
|
| 1207 |
+
raw_asm = target_machine.emit_assembly(mod)
|
| 1208 |
+
self.assertIn("sum", raw_asm)
|
| 1209 |
+
target_machine.set_asm_verbosity(True)
|
| 1210 |
+
raw_asm_verbose = target_machine.emit_assembly(mod)
|
| 1211 |
+
self.assertIn("sum", raw_asm)
|
| 1212 |
+
self.assertNotEqual(raw_asm, raw_asm_verbose)
|
| 1213 |
+
|
| 1214 |
+
def test_emit_object(self):
|
| 1215 |
+
"""Test TargetMachineRef.emit_object()"""
|
| 1216 |
+
target_machine = self.target_machine(jit=True)
|
| 1217 |
+
mod = self.module()
|
| 1218 |
+
ee = self.jit(mod, target_machine) # noqa F841 # Keeps pointers alive
|
| 1219 |
+
code_object = target_machine.emit_object(mod)
|
| 1220 |
+
self.assertIsInstance(code_object, bytes)
|
| 1221 |
+
if sys.platform.startswith('linux'):
|
| 1222 |
+
# Sanity check
|
| 1223 |
+
self.assertIn(b"ELF", code_object[:10])
|
| 1224 |
+
|
| 1225 |
+
|
| 1226 |
+
class TestMCJit(BaseTest, JITWithTMTestMixin):
|
| 1227 |
+
"""
|
| 1228 |
+
Test JIT engines created with create_mcjit_compiler().
|
| 1229 |
+
"""
|
| 1230 |
+
|
| 1231 |
+
def jit(self, mod, target_machine=None):
|
| 1232 |
+
if target_machine is None:
|
| 1233 |
+
target_machine = self.target_machine(jit=True)
|
| 1234 |
+
return llvm.create_mcjit_compiler(mod, target_machine)
|
| 1235 |
+
|
| 1236 |
+
|
| 1237 |
+
# There are some memory corruption issues with OrcJIT on AArch64 - see Issue
|
| 1238 |
+
# #1000. Since OrcJIT is experimental, and we don't test regularly during
|
| 1239 |
+
# llvmlite development on non-x86 platforms, it seems safest to skip these
|
| 1240 |
+
# tests on non-x86 platforms.
|
| 1241 |
+
@unittest.skipUnless(platform.machine().startswith("x86"), "x86 only")
|
| 1242 |
+
class TestOrcLLJIT(BaseTest):
|
| 1243 |
+
|
| 1244 |
+
def jit(self, asm=asm_sum, func_name="sum", target_machine=None,
|
| 1245 |
+
add_process=False, func_type=CFUNCTYPE(c_int, c_int, c_int),
|
| 1246 |
+
suppress_errors=False):
|
| 1247 |
+
lljit = llvm.create_lljit_compiler(target_machine,
|
| 1248 |
+
use_jit_link=False,
|
| 1249 |
+
suppress_errors=suppress_errors)
|
| 1250 |
+
builder = llvm.JITLibraryBuilder()
|
| 1251 |
+
if add_process:
|
| 1252 |
+
builder.add_current_process()
|
| 1253 |
+
rt = builder\
|
| 1254 |
+
.add_ir(asm.format(triple=llvm.get_default_triple()))\
|
| 1255 |
+
.export_symbol(func_name)\
|
| 1256 |
+
.link(lljit, func_name)
|
| 1257 |
+
cfptr = rt[func_name]
|
| 1258 |
+
self.assertTrue(cfptr)
|
| 1259 |
+
self.assertEqual(func_name, rt.name)
|
| 1260 |
+
return lljit, rt, func_type(cfptr)
|
| 1261 |
+
|
| 1262 |
+
# From test_dylib_symbols
|
| 1263 |
+
def test_define_symbol(self):
|
| 1264 |
+
lljit = llvm.create_lljit_compiler()
|
| 1265 |
+
rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\
|
| 1266 |
+
.export_symbol("__xyzzy").link(lljit, "foo")
|
| 1267 |
+
self.assertEqual(rt["__xyzzy"], 1234)
|
| 1268 |
+
|
| 1269 |
+
def test_lookup_undefined_symbol_fails(self):
|
| 1270 |
+
lljit = llvm.create_lljit_compiler()
|
| 1271 |
+
with self.assertRaisesRegex(RuntimeError, 'No such library'):
|
| 1272 |
+
lljit.lookup("foo", "__foobar")
|
| 1273 |
+
rt = llvm.JITLibraryBuilder().import_symbol("__xyzzy", 1234)\
|
| 1274 |
+
.export_symbol("__xyzzy").link(lljit, "foo")
|
| 1275 |
+
self.assertNotEqual(rt["__xyzzy"], 0)
|
| 1276 |
+
with self.assertRaisesRegex(RuntimeError,
|
| 1277 |
+
'Symbols not found.*__foobar'):
|
| 1278 |
+
lljit.lookup("foo", "__foobar")
|
| 1279 |
+
|
| 1280 |
+
def test_jit_link(self):
|
| 1281 |
+
if sys.platform == "win32":
|
| 1282 |
+
with self.assertRaisesRegex(RuntimeError,
|
| 1283 |
+
'JITLink .* Windows'):
|
| 1284 |
+
llvm.create_lljit_compiler(use_jit_link=True)
|
| 1285 |
+
else:
|
| 1286 |
+
self.assertIsNotNone(llvm.create_lljit_compiler(use_jit_link=True))
|
| 1287 |
+
|
| 1288 |
+
def test_run_code(self):
|
| 1289 |
+
(lljit, rt, cfunc) = self.jit()
|
| 1290 |
+
with lljit:
|
| 1291 |
+
res = cfunc(2, -5)
|
| 1292 |
+
self.assertEqual(-3, res)
|
| 1293 |
+
|
| 1294 |
+
def test_close(self):
|
| 1295 |
+
(lljit, rt, cfunc) = self.jit()
|
| 1296 |
+
lljit.close()
|
| 1297 |
+
lljit.close()
|
| 1298 |
+
with self.assertRaises(AssertionError):
|
| 1299 |
+
lljit.lookup("foo", "fn")
|
| 1300 |
+
|
| 1301 |
+
def test_with(self):
|
| 1302 |
+
(lljit, rt, cfunc) = self.jit()
|
| 1303 |
+
with lljit:
|
| 1304 |
+
pass
|
| 1305 |
+
with self.assertRaises(RuntimeError):
|
| 1306 |
+
with lljit:
|
| 1307 |
+
pass
|
| 1308 |
+
with self.assertRaises(AssertionError):
|
| 1309 |
+
lljit.lookup("foo", "fn")
|
| 1310 |
+
|
| 1311 |
+
def test_add_ir_module(self):
|
| 1312 |
+
(lljit, rt_sum, cfunc_sum) = self.jit()
|
| 1313 |
+
rt_mul = llvm.JITLibraryBuilder() \
|
| 1314 |
+
.add_ir(asm_mul.format(triple=llvm.get_default_triple())) \
|
| 1315 |
+
.export_symbol("mul") \
|
| 1316 |
+
.link(lljit, "mul")
|
| 1317 |
+
res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["mul"])(2, -5)
|
| 1318 |
+
self.assertEqual(-10, res)
|
| 1319 |
+
self.assertNotEqual(lljit.lookup("sum", "sum")["sum"], 0)
|
| 1320 |
+
self.assertNotEqual(lljit.lookup("mul", "mul")["mul"], 0)
|
| 1321 |
+
with self.assertRaises(RuntimeError):
|
| 1322 |
+
lljit.lookup("sum", "mul")
|
| 1323 |
+
with self.assertRaises(RuntimeError):
|
| 1324 |
+
lljit.lookup("mul", "sum")
|
| 1325 |
+
|
| 1326 |
+
def test_remove_module(self):
|
| 1327 |
+
(lljit, rt_sum, _) = self.jit()
|
| 1328 |
+
del rt_sum
|
| 1329 |
+
gc.collect()
|
| 1330 |
+
with self.assertRaises(RuntimeError):
|
| 1331 |
+
lljit.lookup("sum", "sum")
|
| 1332 |
+
lljit.close()
|
| 1333 |
+
|
| 1334 |
+
def test_lib_depends(self):
|
| 1335 |
+
(lljit, rt_sum, cfunc_sum) = self.jit()
|
| 1336 |
+
rt_mul = llvm.JITLibraryBuilder() \
|
| 1337 |
+
.add_ir(asm_square_sum.format(triple=llvm.get_default_triple())) \
|
| 1338 |
+
.export_symbol("square_sum") \
|
| 1339 |
+
.add_jit_library("sum") \
|
| 1340 |
+
.link(lljit, "square_sum")
|
| 1341 |
+
res = CFUNCTYPE(c_int, c_int, c_int)(rt_mul["square_sum"])(2, -5)
|
| 1342 |
+
self.assertEqual(9, res)
|
| 1343 |
+
|
| 1344 |
+
def test_target_data(self):
|
| 1345 |
+
(lljit, rt, _) = self.jit()
|
| 1346 |
+
td = lljit.target_data
|
| 1347 |
+
# A singleton is returned
|
| 1348 |
+
self.assertIs(lljit.target_data, td)
|
| 1349 |
+
str(td)
|
| 1350 |
+
del lljit
|
| 1351 |
+
str(td)
|
| 1352 |
+
|
| 1353 |
+
def test_global_ctors_dtors(self):
|
| 1354 |
+
# test issue #303
|
| 1355 |
+
# (https://github.com/numba/llvmlite/issues/303)
|
| 1356 |
+
shared_value = c_int32(0)
|
| 1357 |
+
lljit = llvm.create_lljit_compiler()
|
| 1358 |
+
builder = llvm.JITLibraryBuilder()
|
| 1359 |
+
rt = builder \
|
| 1360 |
+
.add_ir(asm_ext_ctors.format(triple=llvm.get_default_triple())) \
|
| 1361 |
+
.import_symbol("A", ctypes.addressof(shared_value)) \
|
| 1362 |
+
.export_symbol("foo") \
|
| 1363 |
+
.link(lljit, "foo")
|
| 1364 |
+
foo = rt["foo"]
|
| 1365 |
+
self.assertTrue(foo)
|
| 1366 |
+
self.assertEqual(CFUNCTYPE(c_int)(foo)(), 12)
|
| 1367 |
+
del rt
|
| 1368 |
+
self.assertNotEqual(shared_value.value, 20)
|
| 1369 |
+
|
| 1370 |
+
def test_lookup_current_process_symbol_fails(self):
|
| 1371 |
+
# An attempt to lookup a symbol in the current process (Py_GetVersion,
|
| 1372 |
+
# in this case) should fail with an appropriate error if we have not
|
| 1373 |
+
# enabled searching the current process for symbols.
|
| 1374 |
+
msg = 'Failed to materialize symbols:.*getversion'
|
| 1375 |
+
with self.assertRaisesRegex(RuntimeError, msg):
|
| 1376 |
+
self.jit(asm_getversion, "getversion", suppress_errors=True)
|
| 1377 |
+
|
| 1378 |
+
def test_lookup_current_process_symbol(self):
|
| 1379 |
+
self.jit(asm_getversion, "getversion", None, True)
|
| 1380 |
+
|
| 1381 |
+
def test_thread_safe(self):
|
| 1382 |
+
lljit = llvm.create_lljit_compiler()
|
| 1383 |
+
llvm_ir = asm_sum.format(triple=llvm.get_default_triple())
|
| 1384 |
+
|
| 1385 |
+
def compile_many(i):
|
| 1386 |
+
def do_work():
|
| 1387 |
+
tracking = []
|
| 1388 |
+
for c in range(50):
|
| 1389 |
+
tracking.append(llvm.JITLibraryBuilder()
|
| 1390 |
+
.add_ir(llvm_ir)
|
| 1391 |
+
.export_symbol("sum")
|
| 1392 |
+
.link(lljit, f"sum_{i}_{c}"))
|
| 1393 |
+
|
| 1394 |
+
return do_work
|
| 1395 |
+
|
| 1396 |
+
ths = [threading.Thread(target=compile_many(i))
|
| 1397 |
+
for i in range(os.cpu_count())]
|
| 1398 |
+
for th in ths:
|
| 1399 |
+
th.start()
|
| 1400 |
+
for th in ths:
|
| 1401 |
+
th.join()
|
| 1402 |
+
|
| 1403 |
+
def test_add_object_file(self):
|
| 1404 |
+
target_machine = self.target_machine(jit=False)
|
| 1405 |
+
mod = self.module()
|
| 1406 |
+
lljit = llvm.create_lljit_compiler(target_machine)
|
| 1407 |
+
rt = llvm.JITLibraryBuilder()\
|
| 1408 |
+
.add_object_img(target_machine.emit_object(mod))\
|
| 1409 |
+
.export_symbol("sum")\
|
| 1410 |
+
.link(lljit, "sum")
|
| 1411 |
+
sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"])
|
| 1412 |
+
self.assertEqual(sum(2, 3), 5)
|
| 1413 |
+
|
| 1414 |
+
def test_add_object_file_from_filesystem(self):
|
| 1415 |
+
target_machine = self.target_machine(jit=False)
|
| 1416 |
+
mod = self.module()
|
| 1417 |
+
obj_bin = target_machine.emit_object(mod)
|
| 1418 |
+
temp_desc, temp_path = mkstemp()
|
| 1419 |
+
|
| 1420 |
+
try:
|
| 1421 |
+
with os.fdopen(temp_desc, "wb") as f:
|
| 1422 |
+
f.write(obj_bin)
|
| 1423 |
+
lljit = llvm.create_lljit_compiler(target_machine)
|
| 1424 |
+
rt = llvm.JITLibraryBuilder() \
|
| 1425 |
+
.add_object_file(temp_path) \
|
| 1426 |
+
.export_symbol("sum") \
|
| 1427 |
+
.link(lljit, "sum")
|
| 1428 |
+
sum = CFUNCTYPE(c_int, c_int, c_int)(rt["sum"])
|
| 1429 |
+
self.assertEqual(sum(2, 3), 5)
|
| 1430 |
+
finally:
|
| 1431 |
+
os.unlink(temp_path)
|
| 1432 |
+
|
| 1433 |
+
|
| 1434 |
+
class TestValueRef(BaseTest):
|
| 1435 |
+
|
| 1436 |
+
def test_str(self):
|
| 1437 |
+
mod = self.module()
|
| 1438 |
+
glob = mod.get_global_variable("glob")
|
| 1439 |
+
self.assertEqual(str(glob), "@glob = global i32 0")
|
| 1440 |
+
|
| 1441 |
+
def test_name(self):
|
| 1442 |
+
mod = self.module()
|
| 1443 |
+
glob = mod.get_global_variable("glob")
|
| 1444 |
+
self.assertEqual(glob.name, "glob")
|
| 1445 |
+
glob.name = "foobar"
|
| 1446 |
+
self.assertEqual(glob.name, "foobar")
|
| 1447 |
+
|
| 1448 |
+
def test_linkage(self):
|
| 1449 |
+
mod = self.module()
|
| 1450 |
+
glob = mod.get_global_variable("glob")
|
| 1451 |
+
linkage = glob.linkage
|
| 1452 |
+
self.assertIsInstance(glob.linkage, llvm.Linkage)
|
| 1453 |
+
glob.linkage = linkage
|
| 1454 |
+
self.assertEqual(glob.linkage, linkage)
|
| 1455 |
+
for linkage in ("internal", "external"):
|
| 1456 |
+
glob.linkage = linkage
|
| 1457 |
+
self.assertIsInstance(glob.linkage, llvm.Linkage)
|
| 1458 |
+
self.assertEqual(glob.linkage.name, linkage)
|
| 1459 |
+
|
| 1460 |
+
def test_visibility(self):
|
| 1461 |
+
mod = self.module()
|
| 1462 |
+
glob = mod.get_global_variable("glob")
|
| 1463 |
+
visibility = glob.visibility
|
| 1464 |
+
self.assertIsInstance(glob.visibility, llvm.Visibility)
|
| 1465 |
+
glob.visibility = visibility
|
| 1466 |
+
self.assertEqual(glob.visibility, visibility)
|
| 1467 |
+
for visibility in ("hidden", "protected", "default"):
|
| 1468 |
+
glob.visibility = visibility
|
| 1469 |
+
self.assertIsInstance(glob.visibility, llvm.Visibility)
|
| 1470 |
+
self.assertEqual(glob.visibility.name, visibility)
|
| 1471 |
+
|
| 1472 |
+
def test_storage_class(self):
|
| 1473 |
+
mod = self.module()
|
| 1474 |
+
glob = mod.get_global_variable("glob")
|
| 1475 |
+
storage_class = glob.storage_class
|
| 1476 |
+
self.assertIsInstance(glob.storage_class, llvm.StorageClass)
|
| 1477 |
+
glob.storage_class = storage_class
|
| 1478 |
+
self.assertEqual(glob.storage_class, storage_class)
|
| 1479 |
+
for storage_class in ("dllimport", "dllexport", "default"):
|
| 1480 |
+
glob.storage_class = storage_class
|
| 1481 |
+
self.assertIsInstance(glob.storage_class, llvm.StorageClass)
|
| 1482 |
+
self.assertEqual(glob.storage_class.name, storage_class)
|
| 1483 |
+
|
| 1484 |
+
def test_add_function_attribute(self):
|
| 1485 |
+
mod = self.module()
|
| 1486 |
+
fn = mod.get_function("sum")
|
| 1487 |
+
fn.add_function_attribute("nocapture")
|
| 1488 |
+
with self.assertRaises(ValueError) as raises:
|
| 1489 |
+
fn.add_function_attribute("zext")
|
| 1490 |
+
self.assertEqual(str(raises.exception), "no such attribute 'zext'")
|
| 1491 |
+
|
| 1492 |
+
def test_module(self):
|
| 1493 |
+
mod = self.module()
|
| 1494 |
+
glob = mod.get_global_variable("glob")
|
| 1495 |
+
self.assertIs(glob.module, mod)
|
| 1496 |
+
|
| 1497 |
+
def test_type(self):
|
| 1498 |
+
mod = self.module()
|
| 1499 |
+
glob = mod.get_global_variable("glob")
|
| 1500 |
+
tp = glob.type
|
| 1501 |
+
self.assertIsInstance(tp, llvm.TypeRef)
|
| 1502 |
+
|
| 1503 |
+
def test_type_name(self):
|
| 1504 |
+
mod = self.module()
|
| 1505 |
+
glob = mod.get_global_variable("glob")
|
| 1506 |
+
tp = glob.type
|
| 1507 |
+
self.assertEqual(tp.name, "")
|
| 1508 |
+
st = mod.get_global_variable("glob_struct")
|
| 1509 |
+
self.assertIsNotNone(re.match(r"struct\.glob_type(\.[\d]+)?",
|
| 1510 |
+
st.type.element_type.name))
|
| 1511 |
+
|
| 1512 |
+
def test_type_printing_variable(self):
|
| 1513 |
+
mod = self.module()
|
| 1514 |
+
glob = mod.get_global_variable("glob")
|
| 1515 |
+
tp = glob.type
|
| 1516 |
+
self.assertEqual(str(tp), 'i32*')
|
| 1517 |
+
|
| 1518 |
+
def test_type_printing_function(self):
|
| 1519 |
+
mod = self.module()
|
| 1520 |
+
fn = mod.get_function("sum")
|
| 1521 |
+
self.assertEqual(str(fn.type), "i32 (i32, i32)*")
|
| 1522 |
+
|
| 1523 |
+
def test_type_printing_struct(self):
|
| 1524 |
+
mod = self.module()
|
| 1525 |
+
st = mod.get_global_variable("glob_struct")
|
| 1526 |
+
self.assertTrue(st.type.is_pointer)
|
| 1527 |
+
self.assertIsNotNone(re.match(r'%struct\.glob_type(\.[\d]+)?\*',
|
| 1528 |
+
str(st.type)))
|
| 1529 |
+
self.assertIsNotNone(re.match(
|
| 1530 |
+
r"%struct\.glob_type(\.[\d]+)? = type { i64, \[2 x i64\] }",
|
| 1531 |
+
str(st.type.element_type)))
|
| 1532 |
+
|
| 1533 |
+
def test_close(self):
|
| 1534 |
+
glob = self.glob()
|
| 1535 |
+
glob.close()
|
| 1536 |
+
glob.close()
|
| 1537 |
+
|
| 1538 |
+
def test_is_declaration(self):
|
| 1539 |
+
defined = self.module().get_function('sum')
|
| 1540 |
+
declared = self.module(asm_sum_declare).get_function('sum')
|
| 1541 |
+
self.assertFalse(defined.is_declaration)
|
| 1542 |
+
self.assertTrue(declared.is_declaration)
|
| 1543 |
+
|
| 1544 |
+
def test_module_global_variables(self):
|
| 1545 |
+
mod = self.module(asm_sum)
|
| 1546 |
+
gvars = list(mod.global_variables)
|
| 1547 |
+
self.assertEqual(len(gvars), 4)
|
| 1548 |
+
for v in gvars:
|
| 1549 |
+
self.assertTrue(v.is_global)
|
| 1550 |
+
|
| 1551 |
+
def test_module_functions(self):
|
| 1552 |
+
mod = self.module()
|
| 1553 |
+
funcs = list(mod.functions)
|
| 1554 |
+
self.assertEqual(len(funcs), 1)
|
| 1555 |
+
func = funcs[0]
|
| 1556 |
+
self.assertTrue(func.is_function)
|
| 1557 |
+
self.assertEqual(func.name, 'sum')
|
| 1558 |
+
|
| 1559 |
+
with self.assertRaises(ValueError):
|
| 1560 |
+
func.instructions
|
| 1561 |
+
with self.assertRaises(ValueError):
|
| 1562 |
+
func.operands
|
| 1563 |
+
with self.assertRaises(ValueError):
|
| 1564 |
+
func.opcode
|
| 1565 |
+
|
| 1566 |
+
def test_function_arguments(self):
|
| 1567 |
+
mod = self.module()
|
| 1568 |
+
func = mod.get_function('sum')
|
| 1569 |
+
self.assertTrue(func.is_function)
|
| 1570 |
+
args = list(func.arguments)
|
| 1571 |
+
self.assertEqual(len(args), 2)
|
| 1572 |
+
self.assertTrue(args[0].is_argument)
|
| 1573 |
+
self.assertTrue(args[1].is_argument)
|
| 1574 |
+
self.assertEqual(args[0].name, '.1')
|
| 1575 |
+
self.assertEqual(str(args[0].type), 'i32')
|
| 1576 |
+
self.assertEqual(args[1].name, '.2')
|
| 1577 |
+
self.assertEqual(str(args[1].type), 'i32')
|
| 1578 |
+
|
| 1579 |
+
with self.assertRaises(ValueError):
|
| 1580 |
+
args[0].blocks
|
| 1581 |
+
with self.assertRaises(ValueError):
|
| 1582 |
+
args[0].arguments
|
| 1583 |
+
|
| 1584 |
+
def test_function_blocks(self):
|
| 1585 |
+
func = self.module().get_function('sum')
|
| 1586 |
+
blocks = list(func.blocks)
|
| 1587 |
+
self.assertEqual(len(blocks), 1)
|
| 1588 |
+
block = blocks[0]
|
| 1589 |
+
self.assertTrue(block.is_block)
|
| 1590 |
+
|
| 1591 |
+
def test_block_instructions(self):
|
| 1592 |
+
func = self.module().get_function('sum')
|
| 1593 |
+
insts = list(list(func.blocks)[0].instructions)
|
| 1594 |
+
self.assertEqual(len(insts), 3)
|
| 1595 |
+
self.assertTrue(insts[0].is_instruction)
|
| 1596 |
+
self.assertTrue(insts[1].is_instruction)
|
| 1597 |
+
self.assertTrue(insts[2].is_instruction)
|
| 1598 |
+
self.assertEqual(insts[0].opcode, 'add')
|
| 1599 |
+
self.assertEqual(insts[1].opcode, 'add')
|
| 1600 |
+
self.assertEqual(insts[2].opcode, 'ret')
|
| 1601 |
+
|
| 1602 |
+
def test_instruction_operands(self):
|
| 1603 |
+
func = self.module().get_function('sum')
|
| 1604 |
+
add = list(list(func.blocks)[0].instructions)[0]
|
| 1605 |
+
self.assertEqual(add.opcode, 'add')
|
| 1606 |
+
operands = list(add.operands)
|
| 1607 |
+
self.assertEqual(len(operands), 2)
|
| 1608 |
+
self.assertTrue(operands[0].is_operand)
|
| 1609 |
+
self.assertTrue(operands[1].is_operand)
|
| 1610 |
+
self.assertEqual(operands[0].name, '.1')
|
| 1611 |
+
self.assertEqual(str(operands[0].type), 'i32')
|
| 1612 |
+
self.assertEqual(operands[1].name, '.2')
|
| 1613 |
+
self.assertEqual(str(operands[1].type), 'i32')
|
| 1614 |
+
|
| 1615 |
+
def test_function_attributes(self):
|
| 1616 |
+
mod = self.module(asm_attributes)
|
| 1617 |
+
for func in mod.functions:
|
| 1618 |
+
attrs = list(func.attributes)
|
| 1619 |
+
if func.name == 'a_readonly_func':
|
| 1620 |
+
self.assertEqual(attrs, [b'readonly'])
|
| 1621 |
+
elif func.name == 'a_arg0_return_func':
|
| 1622 |
+
self.assertEqual(attrs, [])
|
| 1623 |
+
args = list(func.arguments)
|
| 1624 |
+
self.assertEqual(list(args[0].attributes), [b'returned'])
|
| 1625 |
+
self.assertEqual(list(args[1].attributes), [])
|
| 1626 |
+
|
| 1627 |
+
def test_value_kind(self):
|
| 1628 |
+
mod = self.module()
|
| 1629 |
+
self.assertEqual(mod.get_global_variable('glob').value_kind,
|
| 1630 |
+
llvm.ValueKind.global_variable)
|
| 1631 |
+
func = mod.get_function('sum')
|
| 1632 |
+
self.assertEqual(func.value_kind, llvm.ValueKind.function)
|
| 1633 |
+
block = list(func.blocks)[0]
|
| 1634 |
+
self.assertEqual(block.value_kind, llvm.ValueKind.basic_block)
|
| 1635 |
+
inst = list(block.instructions)[1]
|
| 1636 |
+
self.assertEqual(inst.value_kind, llvm.ValueKind.instruction)
|
| 1637 |
+
self.assertEqual(list(inst.operands)[0].value_kind,
|
| 1638 |
+
llvm.ValueKind.constant_int)
|
| 1639 |
+
self.assertEqual(list(inst.operands)[1].value_kind,
|
| 1640 |
+
llvm.ValueKind.instruction)
|
| 1641 |
+
|
| 1642 |
+
iasm_func = self.module(asm_inlineasm).get_function('foo')
|
| 1643 |
+
iasm_inst = list(list(iasm_func.blocks)[0].instructions)[0]
|
| 1644 |
+
self.assertEqual(list(iasm_inst.operands)[0].value_kind,
|
| 1645 |
+
llvm.ValueKind.inline_asm)
|
| 1646 |
+
|
| 1647 |
+
def test_is_constant(self):
|
| 1648 |
+
mod = self.module()
|
| 1649 |
+
self.assertTrue(mod.get_global_variable('glob').is_constant)
|
| 1650 |
+
constant_operands = 0
|
| 1651 |
+
for func in mod.functions:
|
| 1652 |
+
self.assertTrue(func.is_constant)
|
| 1653 |
+
for block in func.blocks:
|
| 1654 |
+
self.assertFalse(block.is_constant)
|
| 1655 |
+
for inst in block.instructions:
|
| 1656 |
+
self.assertFalse(inst.is_constant)
|
| 1657 |
+
for op in inst.operands:
|
| 1658 |
+
if op.is_constant:
|
| 1659 |
+
constant_operands += 1
|
| 1660 |
+
|
| 1661 |
+
self.assertEqual(constant_operands, 1)
|
| 1662 |
+
|
| 1663 |
+
def test_constant_int(self):
|
| 1664 |
+
mod = self.module()
|
| 1665 |
+
func = mod.get_function('sum')
|
| 1666 |
+
insts = list(list(func.blocks)[0].instructions)
|
| 1667 |
+
self.assertEqual(insts[1].opcode, 'add')
|
| 1668 |
+
operands = list(insts[1].operands)
|
| 1669 |
+
self.assertTrue(operands[0].is_constant)
|
| 1670 |
+
self.assertFalse(operands[1].is_constant)
|
| 1671 |
+
self.assertEqual(operands[0].get_constant_value(), 0)
|
| 1672 |
+
with self.assertRaises(ValueError):
|
| 1673 |
+
operands[1].get_constant_value()
|
| 1674 |
+
|
| 1675 |
+
mod = self.module(asm_sum3)
|
| 1676 |
+
func = mod.get_function('sum')
|
| 1677 |
+
insts = list(list(func.blocks)[0].instructions)
|
| 1678 |
+
posint64 = list(insts[1].operands)[0]
|
| 1679 |
+
negint64 = list(insts[2].operands)[0]
|
| 1680 |
+
self.assertEqual(posint64.get_constant_value(), 5)
|
| 1681 |
+
self.assertEqual(negint64.get_constant_value(signed_int=True), -5)
|
| 1682 |
+
|
| 1683 |
+
# Convert from unsigned arbitrary-precision integer to signed i64
|
| 1684 |
+
as_u64 = negint64.get_constant_value(signed_int=False)
|
| 1685 |
+
as_i64 = int.from_bytes(as_u64.to_bytes(8, 'little'), 'little',
|
| 1686 |
+
signed=True)
|
| 1687 |
+
self.assertEqual(as_i64, -5)
|
| 1688 |
+
|
| 1689 |
+
def test_constant_fp(self):
|
| 1690 |
+
mod = self.module(asm_double_locale)
|
| 1691 |
+
func = mod.get_function('foo')
|
| 1692 |
+
insts = list(list(func.blocks)[0].instructions)
|
| 1693 |
+
self.assertEqual(len(insts), 2)
|
| 1694 |
+
self.assertEqual(insts[0].opcode, 'fadd')
|
| 1695 |
+
operands = list(insts[0].operands)
|
| 1696 |
+
self.assertTrue(operands[0].is_constant)
|
| 1697 |
+
self.assertAlmostEqual(operands[0].get_constant_value(), 0.0)
|
| 1698 |
+
self.assertTrue(operands[1].is_constant)
|
| 1699 |
+
self.assertAlmostEqual(operands[1].get_constant_value(), 3.14)
|
| 1700 |
+
|
| 1701 |
+
mod = self.module(asm_double_inaccurate)
|
| 1702 |
+
func = mod.get_function('foo')
|
| 1703 |
+
inst = list(list(func.blocks)[0].instructions)[0]
|
| 1704 |
+
operands = list(inst.operands)
|
| 1705 |
+
with self.assertRaises(ValueError):
|
| 1706 |
+
operands[0].get_constant_value()
|
| 1707 |
+
self.assertAlmostEqual(operands[1].get_constant_value(round_fp=True), 0)
|
| 1708 |
+
|
| 1709 |
+
def test_constant_as_string(self):
|
| 1710 |
+
mod = self.module(asm_null_constant)
|
| 1711 |
+
func = mod.get_function('bar')
|
| 1712 |
+
inst = list(list(func.blocks)[0].instructions)[0]
|
| 1713 |
+
arg = list(inst.operands)[0]
|
| 1714 |
+
self.assertTrue(arg.is_constant)
|
| 1715 |
+
self.assertEqual(arg.get_constant_value(), 'i64* null')
|
| 1716 |
+
|
| 1717 |
+
def test_incoming_phi_blocks(self):
|
| 1718 |
+
mod = self.module(asm_phi_blocks)
|
| 1719 |
+
func = mod.get_function('foo')
|
| 1720 |
+
blocks = list(func.blocks)
|
| 1721 |
+
instructions = list(blocks[-1].instructions)
|
| 1722 |
+
self.assertTrue(instructions[0].is_instruction)
|
| 1723 |
+
self.assertEqual(instructions[0].opcode, 'phi')
|
| 1724 |
+
|
| 1725 |
+
incoming_blocks = list(instructions[0].incoming_blocks)
|
| 1726 |
+
self.assertEqual(len(incoming_blocks), 2)
|
| 1727 |
+
self.assertTrue(incoming_blocks[0].is_block)
|
| 1728 |
+
self.assertTrue(incoming_blocks[1].is_block)
|
| 1729 |
+
# Test reference to blocks (named or unnamed)
|
| 1730 |
+
self.assertEqual(incoming_blocks[0], blocks[-1])
|
| 1731 |
+
self.assertEqual(incoming_blocks[1], blocks[0])
|
| 1732 |
+
|
| 1733 |
+
# Test case that should fail
|
| 1734 |
+
self.assertNotEqual(instructions[1].opcode, 'phi')
|
| 1735 |
+
with self.assertRaises(ValueError):
|
| 1736 |
+
instructions[1].incoming_blocks
|
| 1737 |
+
|
| 1738 |
+
|
| 1739 |
+
class TestTypeRef(BaseTest):
|
| 1740 |
+
|
| 1741 |
+
def test_str(self):
|
| 1742 |
+
mod = self.module()
|
| 1743 |
+
glob = mod.get_global_variable("glob")
|
| 1744 |
+
self.assertEqual(str(glob.type), "i32*")
|
| 1745 |
+
glob_struct_type = mod.get_struct_type("struct.glob_type")
|
| 1746 |
+
self.assertEqual(str(glob_struct_type),
|
| 1747 |
+
"%struct.glob_type = type { i64, [2 x i64] }")
|
| 1748 |
+
|
| 1749 |
+
elements = list(glob_struct_type.elements)
|
| 1750 |
+
self.assertEqual(len(elements), 2)
|
| 1751 |
+
self.assertEqual(str(elements[0]), "i64")
|
| 1752 |
+
self.assertEqual(str(elements[1]), "[2 x i64]")
|
| 1753 |
+
|
| 1754 |
+
def test_type_kind(self):
|
| 1755 |
+
mod = self.module()
|
| 1756 |
+
glob = mod.get_global_variable("glob")
|
| 1757 |
+
self.assertEqual(glob.type.type_kind, llvm.TypeKind.pointer)
|
| 1758 |
+
self.assertTrue(glob.type.is_pointer)
|
| 1759 |
+
|
| 1760 |
+
glob_struct = mod.get_global_variable("glob_struct")
|
| 1761 |
+
self.assertEqual(glob_struct.type.type_kind, llvm.TypeKind.pointer)
|
| 1762 |
+
self.assertTrue(glob_struct.type.is_pointer)
|
| 1763 |
+
|
| 1764 |
+
stype = next(iter(glob_struct.type.elements))
|
| 1765 |
+
self.assertEqual(stype.type_kind, llvm.TypeKind.struct)
|
| 1766 |
+
self.assertTrue(stype.is_struct)
|
| 1767 |
+
|
| 1768 |
+
stype_a, stype_b = stype.elements
|
| 1769 |
+
self.assertEqual(stype_a.type_kind, llvm.TypeKind.integer)
|
| 1770 |
+
self.assertEqual(stype_b.type_kind, llvm.TypeKind.array)
|
| 1771 |
+
self.assertTrue(stype_b.is_array)
|
| 1772 |
+
|
| 1773 |
+
glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec")
|
| 1774 |
+
_, vector_type = glob_vec_struct_type.elements
|
| 1775 |
+
self.assertEqual(vector_type.type_kind, llvm.TypeKind.vector)
|
| 1776 |
+
self.assertTrue(vector_type.is_vector)
|
| 1777 |
+
|
| 1778 |
+
funcptr = mod.get_function("sum").type
|
| 1779 |
+
self.assertEqual(funcptr.type_kind, llvm.TypeKind.pointer)
|
| 1780 |
+
functype, = funcptr.elements
|
| 1781 |
+
self.assertEqual(functype.type_kind, llvm.TypeKind.function)
|
| 1782 |
+
|
| 1783 |
+
def test_element_count(self):
|
| 1784 |
+
mod = self.module()
|
| 1785 |
+
glob_struct_type = mod.get_struct_type("struct.glob_type")
|
| 1786 |
+
_, array_type = glob_struct_type.elements
|
| 1787 |
+
self.assertEqual(array_type.element_count, 2)
|
| 1788 |
+
with self.assertRaises(ValueError):
|
| 1789 |
+
glob_struct_type.element_count
|
| 1790 |
+
|
| 1791 |
+
def test_type_width(self):
|
| 1792 |
+
mod = self.module()
|
| 1793 |
+
glob_struct_type = mod.get_struct_type("struct.glob_type")
|
| 1794 |
+
glob_vec_struct_type = mod.get_struct_type("struct.glob_type_vec")
|
| 1795 |
+
integer_type, array_type = glob_struct_type.elements
|
| 1796 |
+
_, vector_type = glob_vec_struct_type.elements
|
| 1797 |
+
self.assertEqual(integer_type.type_width, 64)
|
| 1798 |
+
self.assertEqual(vector_type.type_width, 64 * 2)
|
| 1799 |
+
|
| 1800 |
+
# Structs and arrays are not primitive types
|
| 1801 |
+
self.assertEqual(glob_struct_type.type_width, 0)
|
| 1802 |
+
self.assertEqual(array_type.type_width, 0)
|
| 1803 |
+
|
| 1804 |
+
def test_vararg_function(self):
|
| 1805 |
+
# Variadic function
|
| 1806 |
+
mod = self.module(asm_vararg_declare)
|
| 1807 |
+
func = mod.get_function('vararg')
|
| 1808 |
+
decltype = func.type.element_type
|
| 1809 |
+
self.assertTrue(decltype.is_function_vararg)
|
| 1810 |
+
|
| 1811 |
+
mod = self.module(asm_sum_declare)
|
| 1812 |
+
func = mod.get_function('sum')
|
| 1813 |
+
decltype = func.type.element_type
|
| 1814 |
+
self.assertFalse(decltype.is_function_vararg)
|
| 1815 |
+
|
| 1816 |
+
# test that the function pointer type cannot use is_function_vararg
|
| 1817 |
+
self.assertTrue(func.type.is_pointer)
|
| 1818 |
+
with self.assertRaises(ValueError) as raises:
|
| 1819 |
+
func.type.is_function_vararg
|
| 1820 |
+
self.assertIn("Type i32 (i32, i32)* is not a function",
|
| 1821 |
+
str(raises.exception))
|
| 1822 |
+
|
| 1823 |
+
|
| 1824 |
+
class TestTarget(BaseTest):
|
| 1825 |
+
|
| 1826 |
+
def test_from_triple(self):
|
| 1827 |
+
f = llvm.Target.from_triple
|
| 1828 |
+
with self.assertRaises(RuntimeError) as cm:
|
| 1829 |
+
f("foobar")
|
| 1830 |
+
self.assertIn("No available targets are compatible with",
|
| 1831 |
+
str(cm.exception))
|
| 1832 |
+
triple = llvm.get_default_triple()
|
| 1833 |
+
target = f(triple)
|
| 1834 |
+
self.assertEqual(target.triple, triple)
|
| 1835 |
+
target.close()
|
| 1836 |
+
|
| 1837 |
+
def test_create_target_machine(self):
|
| 1838 |
+
target = llvm.Target.from_triple(llvm.get_default_triple())
|
| 1839 |
+
# With the default settings
|
| 1840 |
+
target.create_target_machine('', '', 1, 'default', 'default')
|
| 1841 |
+
# With the host's CPU
|
| 1842 |
+
cpu = llvm.get_host_cpu_name()
|
| 1843 |
+
target.create_target_machine(cpu, '', 1, 'default', 'default')
|
| 1844 |
+
|
| 1845 |
+
def test_name(self):
|
| 1846 |
+
t = llvm.Target.from_triple(llvm.get_default_triple())
|
| 1847 |
+
u = llvm.Target.from_default_triple()
|
| 1848 |
+
self.assertIsInstance(t.name, str)
|
| 1849 |
+
self.assertEqual(t.name, u.name)
|
| 1850 |
+
|
| 1851 |
+
def test_description(self):
|
| 1852 |
+
t = llvm.Target.from_triple(llvm.get_default_triple())
|
| 1853 |
+
u = llvm.Target.from_default_triple()
|
| 1854 |
+
self.assertIsInstance(t.description, str)
|
| 1855 |
+
self.assertEqual(t.description, u.description)
|
| 1856 |
+
|
| 1857 |
+
def test_str(self):
|
| 1858 |
+
target = llvm.Target.from_triple(llvm.get_default_triple())
|
| 1859 |
+
s = str(target)
|
| 1860 |
+
self.assertIn(target.name, s)
|
| 1861 |
+
self.assertIn(target.description, s)
|
| 1862 |
+
|
| 1863 |
+
|
| 1864 |
+
class TestTargetData(BaseTest):
|
| 1865 |
+
|
| 1866 |
+
def target_data(self):
|
| 1867 |
+
return llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")
|
| 1868 |
+
|
| 1869 |
+
def test_get_abi_size(self):
|
| 1870 |
+
td = self.target_data()
|
| 1871 |
+
glob = self.glob()
|
| 1872 |
+
self.assertEqual(td.get_abi_size(glob.type), 8)
|
| 1873 |
+
|
| 1874 |
+
def test_get_pointee_abi_size(self):
|
| 1875 |
+
td = self.target_data()
|
| 1876 |
+
|
| 1877 |
+
glob = self.glob()
|
| 1878 |
+
self.assertEqual(td.get_pointee_abi_size(glob.type), 4)
|
| 1879 |
+
|
| 1880 |
+
glob = self.glob("glob_struct")
|
| 1881 |
+
self.assertEqual(td.get_pointee_abi_size(glob.type), 24)
|
| 1882 |
+
|
| 1883 |
+
def test_get_struct_element_offset(self):
|
| 1884 |
+
td = self.target_data()
|
| 1885 |
+
glob = self.glob("glob_struct")
|
| 1886 |
+
|
| 1887 |
+
with self.assertRaises(ValueError):
|
| 1888 |
+
td.get_element_offset(glob.type, 0)
|
| 1889 |
+
|
| 1890 |
+
struct_type = glob.type.element_type
|
| 1891 |
+
self.assertEqual(td.get_element_offset(struct_type, 0), 0)
|
| 1892 |
+
self.assertEqual(td.get_element_offset(struct_type, 1), 8)
|
| 1893 |
+
|
| 1894 |
+
|
| 1895 |
+
class TestTargetMachine(BaseTest):
|
| 1896 |
+
|
| 1897 |
+
def test_add_analysis_passes(self):
|
| 1898 |
+
tm = self.target_machine(jit=False)
|
| 1899 |
+
pm = llvm.create_module_pass_manager()
|
| 1900 |
+
tm.add_analysis_passes(pm)
|
| 1901 |
+
|
| 1902 |
+
def test_target_data_from_tm(self):
|
| 1903 |
+
tm = self.target_machine(jit=False)
|
| 1904 |
+
td = tm.target_data
|
| 1905 |
+
mod = self.module()
|
| 1906 |
+
gv_i32 = mod.get_global_variable("glob")
|
| 1907 |
+
# A global is a pointer, it has the ABI size of a pointer
|
| 1908 |
+
pointer_size = 4 if sys.maxsize < 2 ** 32 else 8
|
| 1909 |
+
self.assertEqual(td.get_abi_size(gv_i32.type), pointer_size)
|
| 1910 |
+
|
| 1911 |
+
|
| 1912 |
+
class TestPassManagerBuilder(BaseTest):
|
| 1913 |
+
|
| 1914 |
+
def pmb(self):
|
| 1915 |
+
return llvm.PassManagerBuilder()
|
| 1916 |
+
|
| 1917 |
+
def test_old_api(self):
|
| 1918 |
+
# Test the create_pass_manager_builder() factory function
|
| 1919 |
+
pmb = llvm.create_pass_manager_builder()
|
| 1920 |
+
pmb.inlining_threshold = 2
|
| 1921 |
+
pmb.opt_level = 3
|
| 1922 |
+
|
| 1923 |
+
def test_close(self):
|
| 1924 |
+
pmb = self.pmb()
|
| 1925 |
+
pmb.close()
|
| 1926 |
+
pmb.close()
|
| 1927 |
+
|
| 1928 |
+
def test_opt_level(self):
|
| 1929 |
+
pmb = self.pmb()
|
| 1930 |
+
self.assertIsInstance(pmb.opt_level, int)
|
| 1931 |
+
for i in range(4):
|
| 1932 |
+
pmb.opt_level = i
|
| 1933 |
+
self.assertEqual(pmb.opt_level, i)
|
| 1934 |
+
|
| 1935 |
+
def test_size_level(self):
|
| 1936 |
+
pmb = self.pmb()
|
| 1937 |
+
self.assertIsInstance(pmb.size_level, int)
|
| 1938 |
+
for i in range(4):
|
| 1939 |
+
pmb.size_level = i
|
| 1940 |
+
self.assertEqual(pmb.size_level, i)
|
| 1941 |
+
|
| 1942 |
+
def test_inlining_threshold(self):
|
| 1943 |
+
pmb = self.pmb()
|
| 1944 |
+
with self.assertRaises(NotImplementedError):
|
| 1945 |
+
pmb.inlining_threshold
|
| 1946 |
+
for i in (25, 80, 350):
|
| 1947 |
+
pmb.inlining_threshold = i
|
| 1948 |
+
|
| 1949 |
+
def test_disable_unroll_loops(self):
|
| 1950 |
+
pmb = self.pmb()
|
| 1951 |
+
self.assertIsInstance(pmb.disable_unroll_loops, bool)
|
| 1952 |
+
for b in (True, False):
|
| 1953 |
+
pmb.disable_unroll_loops = b
|
| 1954 |
+
self.assertEqual(pmb.disable_unroll_loops, b)
|
| 1955 |
+
|
| 1956 |
+
def test_loop_vectorize(self):
|
| 1957 |
+
pmb = self.pmb()
|
| 1958 |
+
self.assertIsInstance(pmb.loop_vectorize, bool)
|
| 1959 |
+
for b in (True, False):
|
| 1960 |
+
pmb.loop_vectorize = b
|
| 1961 |
+
self.assertEqual(pmb.loop_vectorize, b)
|
| 1962 |
+
|
| 1963 |
+
def test_slp_vectorize(self):
|
| 1964 |
+
pmb = self.pmb()
|
| 1965 |
+
self.assertIsInstance(pmb.slp_vectorize, bool)
|
| 1966 |
+
for b in (True, False):
|
| 1967 |
+
pmb.slp_vectorize = b
|
| 1968 |
+
self.assertEqual(pmb.slp_vectorize, b)
|
| 1969 |
+
|
| 1970 |
+
def test_populate_module_pass_manager(self):
|
| 1971 |
+
pmb = self.pmb()
|
| 1972 |
+
pm = llvm.create_module_pass_manager()
|
| 1973 |
+
pmb.populate(pm)
|
| 1974 |
+
pmb.close()
|
| 1975 |
+
pm.close()
|
| 1976 |
+
|
| 1977 |
+
def test_populate_function_pass_manager(self):
|
| 1978 |
+
mod = self.module()
|
| 1979 |
+
pmb = self.pmb()
|
| 1980 |
+
pm = llvm.create_function_pass_manager(mod)
|
| 1981 |
+
pmb.populate(pm)
|
| 1982 |
+
pmb.close()
|
| 1983 |
+
pm.close()
|
| 1984 |
+
|
| 1985 |
+
|
| 1986 |
+
class PassManagerTestMixin(object):
|
| 1987 |
+
|
| 1988 |
+
def pmb(self):
|
| 1989 |
+
pmb = llvm.create_pass_manager_builder()
|
| 1990 |
+
pmb.opt_level = 2
|
| 1991 |
+
pmb.inlining_threshold = 300
|
| 1992 |
+
return pmb
|
| 1993 |
+
|
| 1994 |
+
def test_close(self):
|
| 1995 |
+
pm = self.pm()
|
| 1996 |
+
pm.close()
|
| 1997 |
+
pm.close()
|
| 1998 |
+
|
| 1999 |
+
|
| 2000 |
+
class TestModulePassManager(BaseTest, PassManagerTestMixin):
|
| 2001 |
+
|
| 2002 |
+
def pm(self):
|
| 2003 |
+
return llvm.create_module_pass_manager()
|
| 2004 |
+
|
| 2005 |
+
def test_run(self):
|
| 2006 |
+
pm = self.pm()
|
| 2007 |
+
self.pmb().populate(pm)
|
| 2008 |
+
mod = self.module()
|
| 2009 |
+
orig_asm = str(mod)
|
| 2010 |
+
pm.run(mod)
|
| 2011 |
+
opt_asm = str(mod)
|
| 2012 |
+
# Quick check that optimizations were run, should get:
|
| 2013 |
+
# define i32 @sum(i32 %.1, i32 %.2) local_unnamed_addr #0 {
|
| 2014 |
+
# %.X = add i32 %.2, %.1
|
| 2015 |
+
# ret i32 %.X
|
| 2016 |
+
# }
|
| 2017 |
+
# where X in %.X is 3 or 4
|
| 2018 |
+
opt_asm_split = opt_asm.splitlines()
|
| 2019 |
+
for idx, l in enumerate(opt_asm_split):
|
| 2020 |
+
if l.strip().startswith('ret i32'):
|
| 2021 |
+
toks = {'%.3', '%.4'}
|
| 2022 |
+
for t in toks:
|
| 2023 |
+
if t in l:
|
| 2024 |
+
break
|
| 2025 |
+
else:
|
| 2026 |
+
raise RuntimeError("expected tokens not found")
|
| 2027 |
+
othertoken = (toks ^ {t}).pop()
|
| 2028 |
+
|
| 2029 |
+
self.assertIn("%.3", orig_asm)
|
| 2030 |
+
self.assertNotIn(othertoken, opt_asm)
|
| 2031 |
+
break
|
| 2032 |
+
else:
|
| 2033 |
+
raise RuntimeError("expected IR not found")
|
| 2034 |
+
|
| 2035 |
+
def test_run_with_remarks_successful_inline(self):
|
| 2036 |
+
pm = self.pm()
|
| 2037 |
+
pm.add_function_inlining_pass(70)
|
| 2038 |
+
self.pmb().populate(pm)
|
| 2039 |
+
mod = self.module(asm_inlineasm2)
|
| 2040 |
+
(status, remarks) = pm.run_with_remarks(mod)
|
| 2041 |
+
self.assertTrue(status)
|
| 2042 |
+
# Inlining has happened? The remark will tell us.
|
| 2043 |
+
self.assertIn("Passed", remarks)
|
| 2044 |
+
self.assertIn("inlineme", remarks)
|
| 2045 |
+
|
| 2046 |
+
def test_run_with_remarks_failed_inline(self):
|
| 2047 |
+
pm = self.pm()
|
| 2048 |
+
pm.add_function_inlining_pass(0)
|
| 2049 |
+
self.pmb().populate(pm)
|
| 2050 |
+
mod = self.module(asm_inlineasm3)
|
| 2051 |
+
(status, remarks) = pm.run_with_remarks(mod)
|
| 2052 |
+
self.assertTrue(status)
|
| 2053 |
+
|
| 2054 |
+
# Inlining has not happened? The remark will tell us.
|
| 2055 |
+
self.assertIn("Missed", remarks)
|
| 2056 |
+
self.assertIn("inlineme", remarks)
|
| 2057 |
+
self.assertIn("noinline function attribute", remarks)
|
| 2058 |
+
|
| 2059 |
+
def test_run_with_remarks_inline_filter_out(self):
|
| 2060 |
+
pm = self.pm()
|
| 2061 |
+
pm.add_function_inlining_pass(70)
|
| 2062 |
+
self.pmb().populate(pm)
|
| 2063 |
+
mod = self.module(asm_inlineasm2)
|
| 2064 |
+
(status, remarks) = pm.run_with_remarks(mod, remarks_filter="nothing")
|
| 2065 |
+
self.assertTrue(status)
|
| 2066 |
+
self.assertEqual("", remarks)
|
| 2067 |
+
|
| 2068 |
+
def test_run_with_remarks_inline_filter_in(self):
|
| 2069 |
+
pm = self.pm()
|
| 2070 |
+
pm.add_function_inlining_pass(70)
|
| 2071 |
+
self.pmb().populate(pm)
|
| 2072 |
+
mod = self.module(asm_inlineasm2)
|
| 2073 |
+
(status, remarks) = pm.run_with_remarks(mod, remarks_filter="inlin.*")
|
| 2074 |
+
self.assertTrue(status)
|
| 2075 |
+
self.assertIn("Passed", remarks)
|
| 2076 |
+
self.assertIn("inlineme", remarks)
|
| 2077 |
+
|
| 2078 |
+
|
| 2079 |
+
class TestFunctionPassManager(BaseTest, PassManagerTestMixin):
|
| 2080 |
+
|
| 2081 |
+
def pm(self, mod=None):
|
| 2082 |
+
mod = mod or self.module()
|
| 2083 |
+
return llvm.create_function_pass_manager(mod)
|
| 2084 |
+
|
| 2085 |
+
def test_initfini(self):
|
| 2086 |
+
pm = self.pm()
|
| 2087 |
+
pm.initialize()
|
| 2088 |
+
pm.finalize()
|
| 2089 |
+
|
| 2090 |
+
def test_run(self):
|
| 2091 |
+
mod = self.module()
|
| 2092 |
+
fn = mod.get_function("sum")
|
| 2093 |
+
pm = self.pm(mod)
|
| 2094 |
+
self.pmb().populate(pm)
|
| 2095 |
+
mod.close()
|
| 2096 |
+
orig_asm = str(fn)
|
| 2097 |
+
pm.initialize()
|
| 2098 |
+
pm.run(fn)
|
| 2099 |
+
pm.finalize()
|
| 2100 |
+
opt_asm = str(fn)
|
| 2101 |
+
# Quick check that optimizations were run
|
| 2102 |
+
self.assertIn("%.4", orig_asm)
|
| 2103 |
+
self.assertNotIn("%.4", opt_asm)
|
| 2104 |
+
|
| 2105 |
+
def test_run_with_remarks(self):
|
| 2106 |
+
mod = self.module(licm_asm)
|
| 2107 |
+
fn = mod.get_function("licm")
|
| 2108 |
+
pm = self.pm(mod)
|
| 2109 |
+
pm.add_licm_pass()
|
| 2110 |
+
self.pmb().populate(pm)
|
| 2111 |
+
mod.close()
|
| 2112 |
+
|
| 2113 |
+
pm.initialize()
|
| 2114 |
+
(ok, remarks) = pm.run_with_remarks(fn)
|
| 2115 |
+
pm.finalize()
|
| 2116 |
+
self.assertTrue(ok)
|
| 2117 |
+
self.assertIn("Passed", remarks)
|
| 2118 |
+
self.assertIn("licm", remarks)
|
| 2119 |
+
|
| 2120 |
+
def test_run_with_remarks_filter_out(self):
|
| 2121 |
+
mod = self.module(licm_asm)
|
| 2122 |
+
fn = mod.get_function("licm")
|
| 2123 |
+
pm = self.pm(mod)
|
| 2124 |
+
pm.add_licm_pass()
|
| 2125 |
+
self.pmb().populate(pm)
|
| 2126 |
+
mod.close()
|
| 2127 |
+
|
| 2128 |
+
pm.initialize()
|
| 2129 |
+
(ok, remarks) = pm.run_with_remarks(fn, remarks_filter="nothing")
|
| 2130 |
+
pm.finalize()
|
| 2131 |
+
self.assertTrue(ok)
|
| 2132 |
+
self.assertEqual("", remarks)
|
| 2133 |
+
|
| 2134 |
+
def test_run_with_remarks_filter_in(self):
|
| 2135 |
+
mod = self.module(licm_asm)
|
| 2136 |
+
fn = mod.get_function("licm")
|
| 2137 |
+
pm = self.pm(mod)
|
| 2138 |
+
pm.add_licm_pass()
|
| 2139 |
+
self.pmb().populate(pm)
|
| 2140 |
+
mod.close()
|
| 2141 |
+
|
| 2142 |
+
pm.initialize()
|
| 2143 |
+
(ok, remarks) = pm.run_with_remarks(fn, remarks_filter="licm")
|
| 2144 |
+
pm.finalize()
|
| 2145 |
+
self.assertTrue(ok)
|
| 2146 |
+
self.assertIn("Passed", remarks)
|
| 2147 |
+
self.assertIn("licm", remarks)
|
| 2148 |
+
|
| 2149 |
+
|
| 2150 |
+
class TestPasses(BaseTest, PassManagerTestMixin):
|
| 2151 |
+
|
| 2152 |
+
def pm(self):
|
| 2153 |
+
return llvm.create_module_pass_manager()
|
| 2154 |
+
|
| 2155 |
+
def test_populate(self):
|
| 2156 |
+
pm = self.pm()
|
| 2157 |
+
pm.add_target_library_info("") # unspecified target triple
|
| 2158 |
+
pm.add_constant_merge_pass()
|
| 2159 |
+
pm.add_dead_arg_elimination_pass()
|
| 2160 |
+
pm.add_function_attrs_pass()
|
| 2161 |
+
pm.add_function_inlining_pass(225)
|
| 2162 |
+
pm.add_global_dce_pass()
|
| 2163 |
+
pm.add_global_optimizer_pass()
|
| 2164 |
+
pm.add_ipsccp_pass()
|
| 2165 |
+
pm.add_dead_code_elimination_pass()
|
| 2166 |
+
pm.add_cfg_simplification_pass()
|
| 2167 |
+
pm.add_gvn_pass()
|
| 2168 |
+
pm.add_instruction_combining_pass()
|
| 2169 |
+
pm.add_licm_pass()
|
| 2170 |
+
pm.add_sccp_pass()
|
| 2171 |
+
pm.add_sroa_pass()
|
| 2172 |
+
pm.add_type_based_alias_analysis_pass()
|
| 2173 |
+
pm.add_basic_alias_analysis_pass()
|
| 2174 |
+
pm.add_loop_rotate_pass()
|
| 2175 |
+
pm.add_region_info_pass()
|
| 2176 |
+
pm.add_scalar_evolution_aa_pass()
|
| 2177 |
+
pm.add_aggressive_dead_code_elimination_pass()
|
| 2178 |
+
pm.add_aa_eval_pass()
|
| 2179 |
+
pm.add_always_inliner_pass()
|
| 2180 |
+
if llvm_version_major < 15:
|
| 2181 |
+
pm.add_arg_promotion_pass(42)
|
| 2182 |
+
pm.add_break_critical_edges_pass()
|
| 2183 |
+
pm.add_dead_store_elimination_pass()
|
| 2184 |
+
pm.add_reverse_post_order_function_attrs_pass()
|
| 2185 |
+
pm.add_aggressive_instruction_combining_pass()
|
| 2186 |
+
pm.add_internalize_pass()
|
| 2187 |
+
pm.add_jump_threading_pass(7)
|
| 2188 |
+
pm.add_lcssa_pass()
|
| 2189 |
+
pm.add_loop_deletion_pass()
|
| 2190 |
+
pm.add_loop_extractor_pass()
|
| 2191 |
+
pm.add_single_loop_extractor_pass()
|
| 2192 |
+
pm.add_loop_strength_reduce_pass()
|
| 2193 |
+
pm.add_loop_simplification_pass()
|
| 2194 |
+
pm.add_loop_unroll_pass()
|
| 2195 |
+
pm.add_loop_unroll_and_jam_pass()
|
| 2196 |
+
if llvm_version_major < 15:
|
| 2197 |
+
pm.add_loop_unswitch_pass()
|
| 2198 |
+
pm.add_lower_atomic_pass()
|
| 2199 |
+
pm.add_lower_invoke_pass()
|
| 2200 |
+
pm.add_lower_switch_pass()
|
| 2201 |
+
pm.add_memcpy_optimization_pass()
|
| 2202 |
+
pm.add_merge_functions_pass()
|
| 2203 |
+
pm.add_merge_returns_pass()
|
| 2204 |
+
pm.add_partial_inlining_pass()
|
| 2205 |
+
pm.add_prune_exception_handling_pass()
|
| 2206 |
+
pm.add_reassociate_expressions_pass()
|
| 2207 |
+
pm.add_demote_register_to_memory_pass()
|
| 2208 |
+
pm.add_sink_pass()
|
| 2209 |
+
pm.add_strip_symbols_pass()
|
| 2210 |
+
pm.add_strip_dead_debug_info_pass()
|
| 2211 |
+
pm.add_strip_dead_prototypes_pass()
|
| 2212 |
+
pm.add_strip_debug_declare_pass()
|
| 2213 |
+
pm.add_strip_nondebug_symbols_pass()
|
| 2214 |
+
pm.add_tail_call_elimination_pass()
|
| 2215 |
+
pm.add_basic_aa_pass()
|
| 2216 |
+
pm.add_dependence_analysis_pass()
|
| 2217 |
+
pm.add_dot_call_graph_pass()
|
| 2218 |
+
pm.add_dot_cfg_printer_pass()
|
| 2219 |
+
pm.add_dot_dom_printer_pass()
|
| 2220 |
+
pm.add_dot_postdom_printer_pass()
|
| 2221 |
+
pm.add_globals_mod_ref_aa_pass()
|
| 2222 |
+
pm.add_iv_users_pass()
|
| 2223 |
+
pm.add_lazy_value_info_pass()
|
| 2224 |
+
pm.add_lint_pass()
|
| 2225 |
+
pm.add_module_debug_info_pass()
|
| 2226 |
+
pm.add_refprune_pass()
|
| 2227 |
+
pm.add_instruction_namer_pass()
|
| 2228 |
+
|
| 2229 |
+
@unittest.skipUnless(platform.machine().startswith("x86"), "x86 only")
|
| 2230 |
+
def test_target_library_info_behavior(self):
|
| 2231 |
+
"""Test a specific situation that demonstrate TLI is affecting
|
| 2232 |
+
optimization. See https://github.com/numba/numba/issues/8898.
|
| 2233 |
+
"""
|
| 2234 |
+
def run(use_tli):
|
| 2235 |
+
mod = llvm.parse_assembly(asm_tli_exp2)
|
| 2236 |
+
target = llvm.Target.from_triple(mod.triple)
|
| 2237 |
+
tm = target.create_target_machine()
|
| 2238 |
+
pm = llvm.ModulePassManager()
|
| 2239 |
+
tm.add_analysis_passes(pm)
|
| 2240 |
+
if use_tli:
|
| 2241 |
+
pm.add_target_library_info(mod.triple)
|
| 2242 |
+
pm.add_instruction_combining_pass()
|
| 2243 |
+
pm.run(mod)
|
| 2244 |
+
return mod
|
| 2245 |
+
|
| 2246 |
+
# Run with TLI should suppress transformation of exp2 -> ldexpf
|
| 2247 |
+
mod = run(use_tli=True)
|
| 2248 |
+
self.assertIn("call float @llvm.exp2.f32", str(mod))
|
| 2249 |
+
|
| 2250 |
+
# Run without TLI will enable the transformation
|
| 2251 |
+
mod = run(use_tli=False)
|
| 2252 |
+
self.assertNotIn("call float @llvm.exp2.f32", str(mod))
|
| 2253 |
+
self.assertIn("call float @ldexpf", str(mod))
|
| 2254 |
+
|
| 2255 |
+
def test_instruction_namer_pass(self):
|
| 2256 |
+
asm = asm_inlineasm3.format(triple=llvm.get_default_triple())
|
| 2257 |
+
mod = llvm.parse_assembly(asm)
|
| 2258 |
+
|
| 2259 |
+
# Run instnamer pass
|
| 2260 |
+
pm = llvm.ModulePassManager()
|
| 2261 |
+
pm.add_instruction_namer_pass()
|
| 2262 |
+
pm.run(mod)
|
| 2263 |
+
|
| 2264 |
+
# Test that unnamed instructions are now named
|
| 2265 |
+
func = mod.get_function('foo')
|
| 2266 |
+
first_block = next(func.blocks)
|
| 2267 |
+
instructions = list(first_block.instructions)
|
| 2268 |
+
self.assertEqual(instructions[0].name, 'i')
|
| 2269 |
+
self.assertEqual(instructions[1].name, 'i2')
|
| 2270 |
+
|
| 2271 |
+
|
| 2272 |
+
class TestDylib(BaseTest):
|
| 2273 |
+
|
| 2274 |
+
def test_bad_library(self):
|
| 2275 |
+
with self.assertRaises(RuntimeError):
|
| 2276 |
+
llvm.load_library_permanently("zzzasdkf;jasd;l")
|
| 2277 |
+
|
| 2278 |
+
@unittest.skipUnless(platform.system() in ["Linux"],
|
| 2279 |
+
"test only works on Linux")
|
| 2280 |
+
def test_libm(self):
|
| 2281 |
+
libm = find_library("m")
|
| 2282 |
+
llvm.load_library_permanently(libm)
|
| 2283 |
+
|
| 2284 |
+
|
| 2285 |
+
class TestAnalysis(BaseTest):
|
| 2286 |
+
def build_ir_module(self):
|
| 2287 |
+
m = ir.Module()
|
| 2288 |
+
ft = ir.FunctionType(ir.IntType(32), [ir.IntType(32), ir.IntType(32)])
|
| 2289 |
+
fn = ir.Function(m, ft, "foo")
|
| 2290 |
+
bd = ir.IRBuilder(fn.append_basic_block())
|
| 2291 |
+
x, y = fn.args
|
| 2292 |
+
z = bd.add(x, y)
|
| 2293 |
+
bd.ret(z)
|
| 2294 |
+
return m
|
| 2295 |
+
|
| 2296 |
+
def test_get_function_cfg_on_ir(self):
|
| 2297 |
+
mod = self.build_ir_module()
|
| 2298 |
+
foo = mod.get_global('foo')
|
| 2299 |
+
dot_showing_inst = llvm.get_function_cfg(foo)
|
| 2300 |
+
dot_without_inst = llvm.get_function_cfg(foo, show_inst=False)
|
| 2301 |
+
inst = "%.5 = add i32 %.1, %.2"
|
| 2302 |
+
self.assertIn(inst, dot_showing_inst)
|
| 2303 |
+
self.assertNotIn(inst, dot_without_inst)
|
| 2304 |
+
|
| 2305 |
+
def test_function_cfg_on_llvm_value(self):
|
| 2306 |
+
defined = self.module().get_function('sum')
|
| 2307 |
+
dot_showing_inst = llvm.get_function_cfg(defined, show_inst=True)
|
| 2308 |
+
dot_without_inst = llvm.get_function_cfg(defined, show_inst=False)
|
| 2309 |
+
# Check "digraph"
|
| 2310 |
+
prefix = 'digraph'
|
| 2311 |
+
self.assertIn(prefix, dot_showing_inst)
|
| 2312 |
+
self.assertIn(prefix, dot_without_inst)
|
| 2313 |
+
# Check function name
|
| 2314 |
+
fname = "CFG for 'sum' function"
|
| 2315 |
+
self.assertIn(fname, dot_showing_inst)
|
| 2316 |
+
self.assertIn(fname, dot_without_inst)
|
| 2317 |
+
# Check instruction
|
| 2318 |
+
inst = "%.3 = add i32 %.1, %.2"
|
| 2319 |
+
self.assertIn(inst, dot_showing_inst)
|
| 2320 |
+
self.assertNotIn(inst, dot_without_inst)
|
| 2321 |
+
|
| 2322 |
+
|
| 2323 |
+
class TestTypeParsing(BaseTest):
|
| 2324 |
+
@contextmanager
|
| 2325 |
+
def check_parsing(self):
|
| 2326 |
+
mod = ir.Module()
|
| 2327 |
+
# Yield to caller and provide the module for adding
|
| 2328 |
+
# new GV.
|
| 2329 |
+
yield mod
|
| 2330 |
+
# Caller yield back and continue with testing
|
| 2331 |
+
asm = str(mod)
|
| 2332 |
+
llvm.parse_assembly(asm)
|
| 2333 |
+
|
| 2334 |
+
def test_literal_struct(self):
|
| 2335 |
+
# Natural layout
|
| 2336 |
+
with self.check_parsing() as mod:
|
| 2337 |
+
typ = ir.LiteralStructType([ir.IntType(32)])
|
| 2338 |
+
gv = ir.GlobalVariable(mod, typ, "foo")
|
| 2339 |
+
# Also test constant text repr
|
| 2340 |
+
gv.initializer = ir.Constant(typ, [1])
|
| 2341 |
+
|
| 2342 |
+
# Packed layout
|
| 2343 |
+
with self.check_parsing() as mod:
|
| 2344 |
+
typ = ir.LiteralStructType([ir.IntType(32)],
|
| 2345 |
+
packed=True)
|
| 2346 |
+
gv = ir.GlobalVariable(mod, typ, "foo")
|
| 2347 |
+
# Also test constant text repr
|
| 2348 |
+
gv.initializer = ir.Constant(typ, [1])
|
| 2349 |
+
|
| 2350 |
+
|
| 2351 |
+
class TestGlobalConstructors(TestMCJit):
|
| 2352 |
+
def test_global_ctors_dtors(self):
|
| 2353 |
+
# test issue #303
|
| 2354 |
+
# (https://github.com/numba/llvmlite/issues/303)
|
| 2355 |
+
mod = self.module(asm_global_ctors)
|
| 2356 |
+
ee = self.jit(mod)
|
| 2357 |
+
ee.finalize_object()
|
| 2358 |
+
|
| 2359 |
+
ee.run_static_constructors()
|
| 2360 |
+
|
| 2361 |
+
# global variable should have been initialized
|
| 2362 |
+
ptr_addr = ee.get_global_value_address("A")
|
| 2363 |
+
ptr_t = ctypes.POINTER(ctypes.c_int32)
|
| 2364 |
+
ptr = ctypes.cast(ptr_addr, ptr_t)
|
| 2365 |
+
self.assertEqual(ptr.contents.value, 10)
|
| 2366 |
+
|
| 2367 |
+
foo_addr = ee.get_function_address("foo")
|
| 2368 |
+
foo = ctypes.CFUNCTYPE(ctypes.c_int32)(foo_addr)
|
| 2369 |
+
self.assertEqual(foo(), 12)
|
| 2370 |
+
|
| 2371 |
+
ee.run_static_destructors()
|
| 2372 |
+
|
| 2373 |
+
# destructor should have run
|
| 2374 |
+
self.assertEqual(ptr.contents.value, 20)
|
| 2375 |
+
|
| 2376 |
+
|
| 2377 |
+
class TestGlobalVariables(BaseTest):
|
| 2378 |
+
def check_global_variable_linkage(self, linkage, has_undef=True):
|
| 2379 |
+
# This test default initializer on global variables with different
|
| 2380 |
+
# linkages. Some linkages requires an initializer be present, while
|
| 2381 |
+
# it is optional for others. This test uses ``parse_assembly()``
|
| 2382 |
+
# to verify that we are adding an `undef` automatically if user didn't
|
| 2383 |
+
# specific one for certain linkages. It is a IR syntax error if the
|
| 2384 |
+
# initializer is not present for certain linkages e.g. "external".
|
| 2385 |
+
mod = ir.Module()
|
| 2386 |
+
typ = ir.IntType(32)
|
| 2387 |
+
gv = ir.GlobalVariable(mod, typ, "foo")
|
| 2388 |
+
gv.linkage = linkage
|
| 2389 |
+
asm = str(mod)
|
| 2390 |
+
# check if 'undef' is present
|
| 2391 |
+
if has_undef:
|
| 2392 |
+
self.assertIn('undef', asm)
|
| 2393 |
+
else:
|
| 2394 |
+
self.assertNotIn('undef', asm)
|
| 2395 |
+
# parse assembly to ensure correctness
|
| 2396 |
+
self.module(asm)
|
| 2397 |
+
|
| 2398 |
+
def test_internal_linkage(self):
|
| 2399 |
+
self.check_global_variable_linkage('internal')
|
| 2400 |
+
|
| 2401 |
+
def test_common_linkage(self):
|
| 2402 |
+
self.check_global_variable_linkage('common')
|
| 2403 |
+
|
| 2404 |
+
def test_external_linkage(self):
|
| 2405 |
+
self.check_global_variable_linkage('external', has_undef=False)
|
| 2406 |
+
|
| 2407 |
+
def test_available_externally_linkage(self):
|
| 2408 |
+
self.check_global_variable_linkage('available_externally')
|
| 2409 |
+
|
| 2410 |
+
def test_private_linkage(self):
|
| 2411 |
+
self.check_global_variable_linkage('private')
|
| 2412 |
+
|
| 2413 |
+
def test_linkonce_linkage(self):
|
| 2414 |
+
self.check_global_variable_linkage('linkonce')
|
| 2415 |
+
|
| 2416 |
+
def test_weak_linkage(self):
|
| 2417 |
+
self.check_global_variable_linkage('weak')
|
| 2418 |
+
|
| 2419 |
+
def test_appending_linkage(self):
|
| 2420 |
+
self.check_global_variable_linkage('appending')
|
| 2421 |
+
|
| 2422 |
+
def test_extern_weak_linkage(self):
|
| 2423 |
+
self.check_global_variable_linkage('extern_weak', has_undef=False)
|
| 2424 |
+
|
| 2425 |
+
def test_linkonce_odr_linkage(self):
|
| 2426 |
+
self.check_global_variable_linkage('linkonce_odr')
|
| 2427 |
+
|
| 2428 |
+
def test_weak_odr_linkage(self):
|
| 2429 |
+
self.check_global_variable_linkage('weak_odr')
|
| 2430 |
+
|
| 2431 |
+
|
| 2432 |
+
@unittest.skipUnless(platform.machine().startswith('x86'), "only on x86")
|
| 2433 |
+
class TestInlineAsm(BaseTest):
|
| 2434 |
+
def test_inlineasm(self):
|
| 2435 |
+
llvm.initialize_native_asmparser()
|
| 2436 |
+
m = self.module(asm=asm_inlineasm)
|
| 2437 |
+
tm = self.target_machine(jit=False)
|
| 2438 |
+
asm = tm.emit_assembly(m)
|
| 2439 |
+
self.assertIn('nop', asm)
|
| 2440 |
+
|
| 2441 |
+
|
| 2442 |
+
class TestObjectFile(BaseTest):
|
| 2443 |
+
|
| 2444 |
+
mod_asm = """
|
| 2445 |
+
;ModuleID = <string>
|
| 2446 |
+
target triple = "{triple}"
|
| 2447 |
+
|
| 2448 |
+
declare i32 @sum(i32 %.1, i32 %.2)
|
| 2449 |
+
|
| 2450 |
+
define i32 @sum_twice(i32 %.1, i32 %.2) {{
|
| 2451 |
+
%.3 = call i32 @sum(i32 %.1, i32 %.2)
|
| 2452 |
+
%.4 = call i32 @sum(i32 %.3, i32 %.3)
|
| 2453 |
+
ret i32 %.4
|
| 2454 |
+
}}
|
| 2455 |
+
"""
|
| 2456 |
+
|
| 2457 |
+
def test_object_file(self):
|
| 2458 |
+
target_machine = self.target_machine(jit=False)
|
| 2459 |
+
mod = self.module()
|
| 2460 |
+
obj_bin = target_machine.emit_object(mod)
|
| 2461 |
+
obj = llvm.ObjectFileRef.from_data(obj_bin)
|
| 2462 |
+
# Check that we have a text section, and that she has a name and data
|
| 2463 |
+
has_text = False
|
| 2464 |
+
last_address = -1
|
| 2465 |
+
for s in obj.sections():
|
| 2466 |
+
if s.is_text():
|
| 2467 |
+
has_text = True
|
| 2468 |
+
self.assertIsNotNone(s.name())
|
| 2469 |
+
self.assertTrue(s.size() > 0)
|
| 2470 |
+
self.assertTrue(len(s.data()) > 0)
|
| 2471 |
+
self.assertIsNotNone(s.address())
|
| 2472 |
+
self.assertTrue(last_address < s.address())
|
| 2473 |
+
last_address = s.address()
|
| 2474 |
+
break
|
| 2475 |
+
self.assertTrue(has_text)
|
| 2476 |
+
|
| 2477 |
+
def test_add_object_file(self):
|
| 2478 |
+
target_machine = self.target_machine(jit=False)
|
| 2479 |
+
mod = self.module()
|
| 2480 |
+
obj_bin = target_machine.emit_object(mod)
|
| 2481 |
+
obj = llvm.ObjectFileRef.from_data(obj_bin)
|
| 2482 |
+
|
| 2483 |
+
jit = llvm.create_mcjit_compiler(self.module(self.mod_asm),
|
| 2484 |
+
target_machine)
|
| 2485 |
+
|
| 2486 |
+
jit.add_object_file(obj)
|
| 2487 |
+
|
| 2488 |
+
sum_twice = CFUNCTYPE(c_int, c_int, c_int)(
|
| 2489 |
+
jit.get_function_address("sum_twice"))
|
| 2490 |
+
|
| 2491 |
+
self.assertEqual(sum_twice(2, 3), 10)
|
| 2492 |
+
|
| 2493 |
+
def test_add_object_file_from_filesystem(self):
|
| 2494 |
+
target_machine = self.target_machine(jit=False)
|
| 2495 |
+
mod = self.module()
|
| 2496 |
+
obj_bin = target_machine.emit_object(mod)
|
| 2497 |
+
temp_desc, temp_path = mkstemp()
|
| 2498 |
+
|
| 2499 |
+
try:
|
| 2500 |
+
try:
|
| 2501 |
+
f = os.fdopen(temp_desc, "wb")
|
| 2502 |
+
f.write(obj_bin)
|
| 2503 |
+
f.flush()
|
| 2504 |
+
finally:
|
| 2505 |
+
f.close()
|
| 2506 |
+
|
| 2507 |
+
jit = llvm.create_mcjit_compiler(self.module(self.mod_asm),
|
| 2508 |
+
target_machine)
|
| 2509 |
+
|
| 2510 |
+
jit.add_object_file(temp_path)
|
| 2511 |
+
finally:
|
| 2512 |
+
os.unlink(temp_path)
|
| 2513 |
+
|
| 2514 |
+
sum_twice = CFUNCTYPE(c_int, c_int, c_int)(
|
| 2515 |
+
jit.get_function_address("sum_twice"))
|
| 2516 |
+
|
| 2517 |
+
self.assertEqual(sum_twice(2, 3), 10)
|
| 2518 |
+
|
| 2519 |
+
def test_get_section_content(self):
|
| 2520 |
+
# See Issue #632 - section contents were getting truncated at null
|
| 2521 |
+
# bytes.
|
| 2522 |
+
elf = bytes.fromhex(issue_632_elf)
|
| 2523 |
+
obj = llvm.ObjectFileRef.from_data(elf)
|
| 2524 |
+
for s in obj.sections():
|
| 2525 |
+
if s.is_text():
|
| 2526 |
+
self.assertEqual(len(s.data()), 31)
|
| 2527 |
+
self.assertEqual(s.data().hex(), issue_632_text)
|
| 2528 |
+
|
| 2529 |
+
|
| 2530 |
+
class TestTimePasses(BaseTest):
|
| 2531 |
+
def test_reporting(self):
|
| 2532 |
+
mp = llvm.create_module_pass_manager()
|
| 2533 |
+
|
| 2534 |
+
pmb = llvm.create_pass_manager_builder()
|
| 2535 |
+
pmb.opt_level = 3
|
| 2536 |
+
pmb.populate(mp)
|
| 2537 |
+
|
| 2538 |
+
try:
|
| 2539 |
+
llvm.set_time_passes(True)
|
| 2540 |
+
mp.run(self.module())
|
| 2541 |
+
mp.run(self.module())
|
| 2542 |
+
mp.run(self.module())
|
| 2543 |
+
finally:
|
| 2544 |
+
report = llvm.report_and_reset_timings()
|
| 2545 |
+
llvm.set_time_passes(False)
|
| 2546 |
+
|
| 2547 |
+
self.assertIsInstance(report, str)
|
| 2548 |
+
self.assertEqual(report.count("Pass execution timing report"), 1)
|
| 2549 |
+
|
| 2550 |
+
def test_empty_report(self):
|
| 2551 |
+
# Returns empty str if no data is collected
|
| 2552 |
+
self.assertFalse(llvm.report_and_reset_timings())
|
| 2553 |
+
|
| 2554 |
+
|
| 2555 |
+
class TestLLVMLockCallbacks(BaseTest):
|
| 2556 |
+
def test_lock_callbacks(self):
|
| 2557 |
+
events = []
|
| 2558 |
+
|
| 2559 |
+
def acq():
|
| 2560 |
+
events.append('acq')
|
| 2561 |
+
|
| 2562 |
+
def rel():
|
| 2563 |
+
events.append('rel')
|
| 2564 |
+
|
| 2565 |
+
# register callback
|
| 2566 |
+
llvm.ffi.register_lock_callback(acq, rel)
|
| 2567 |
+
|
| 2568 |
+
# Check: events are initially empty
|
| 2569 |
+
self.assertFalse(events)
|
| 2570 |
+
# Call LLVM functions
|
| 2571 |
+
llvm.create_module_pass_manager()
|
| 2572 |
+
# Check: there must be at least one acq and one rel
|
| 2573 |
+
self.assertIn("acq", events)
|
| 2574 |
+
self.assertIn("rel", events)
|
| 2575 |
+
|
| 2576 |
+
# unregister callback
|
| 2577 |
+
llvm.ffi.unregister_lock_callback(acq, rel)
|
| 2578 |
+
|
| 2579 |
+
# Check: removing non-existent callbacks will trigger a ValueError
|
| 2580 |
+
with self.assertRaises(ValueError):
|
| 2581 |
+
llvm.ffi.unregister_lock_callback(acq, rel)
|
| 2582 |
+
|
| 2583 |
+
|
| 2584 |
+
if __name__ == "__main__":
|
| 2585 |
+
unittest.main()
|
vllm/lib/python3.10/site-packages/llvmlite/tests/test_ir.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
vllm/lib/python3.10/site-packages/llvmlite/tests/test_refprune.py
ADDED
|
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
from llvmlite import ir
|
| 3 |
+
from llvmlite import binding as llvm
|
| 4 |
+
from llvmlite.tests import TestCase
|
| 5 |
+
|
| 6 |
+
from . import refprune_proto as proto
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _iterate_cases(generate_test):
|
| 10 |
+
def wrap(fn):
|
| 11 |
+
def wrapped(self):
|
| 12 |
+
return generate_test(self, fn)
|
| 13 |
+
wrapped.__doc__ = f"generated test for {fn.__module__}.{fn.__name__}"
|
| 14 |
+
return wrapped
|
| 15 |
+
|
| 16 |
+
for k, case_fn in proto.__dict__.items():
|
| 17 |
+
if k.startswith('case'):
|
| 18 |
+
yield f'test_{k}', wrap(case_fn)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestRefPrunePrototype(TestCase):
|
| 22 |
+
"""
|
| 23 |
+
Test that the prototype is working.
|
| 24 |
+
"""
|
| 25 |
+
def generate_test(self, case_gen):
|
| 26 |
+
nodes, edges, expected = case_gen()
|
| 27 |
+
got = proto.FanoutAlgorithm(nodes, edges).run()
|
| 28 |
+
self.assertEqual(expected, got)
|
| 29 |
+
|
| 30 |
+
# Generate tests
|
| 31 |
+
for name, case in _iterate_cases(generate_test):
|
| 32 |
+
locals()[name] = case
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
ptr_ty = ir.IntType(8).as_pointer()
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class TestRefPrunePass(TestCase):
|
| 39 |
+
"""
|
| 40 |
+
Test that the C++ implementation matches the expected behavior as for
|
| 41 |
+
the prototype.
|
| 42 |
+
|
| 43 |
+
This generates a LLVM module for each test case, runs the pruner and checks
|
| 44 |
+
that the expected results are achieved.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def make_incref(self, m):
|
| 48 |
+
fnty = ir.FunctionType(ir.VoidType(), [ptr_ty])
|
| 49 |
+
return ir.Function(m, fnty, name='NRT_incref')
|
| 50 |
+
|
| 51 |
+
def make_decref(self, m):
|
| 52 |
+
fnty = ir.FunctionType(ir.VoidType(), [ptr_ty])
|
| 53 |
+
return ir.Function(m, fnty, name='NRT_decref')
|
| 54 |
+
|
| 55 |
+
def make_switcher(self, m):
|
| 56 |
+
fnty = ir.FunctionType(ir.IntType(32), ())
|
| 57 |
+
return ir.Function(m, fnty, name='switcher')
|
| 58 |
+
|
| 59 |
+
def make_brancher(self, m):
|
| 60 |
+
fnty = ir.FunctionType(ir.IntType(1), ())
|
| 61 |
+
return ir.Function(m, fnty, name='brancher')
|
| 62 |
+
|
| 63 |
+
def generate_ir(self, nodes, edges):
|
| 64 |
+
# Build LLVM module for the CFG
|
| 65 |
+
m = ir.Module()
|
| 66 |
+
|
| 67 |
+
incref_fn = self.make_incref(m)
|
| 68 |
+
decref_fn = self.make_decref(m)
|
| 69 |
+
switcher_fn = self.make_switcher(m)
|
| 70 |
+
brancher_fn = self.make_brancher(m)
|
| 71 |
+
|
| 72 |
+
fnty = ir.FunctionType(ir.VoidType(), [ptr_ty])
|
| 73 |
+
fn = ir.Function(m, fnty, name='main')
|
| 74 |
+
[ptr] = fn.args
|
| 75 |
+
ptr.name = 'mem'
|
| 76 |
+
# populate the BB nodes
|
| 77 |
+
bbmap = {}
|
| 78 |
+
for bb in edges:
|
| 79 |
+
bbmap[bb] = fn.append_basic_block(bb)
|
| 80 |
+
# populate the BB
|
| 81 |
+
builder = ir.IRBuilder()
|
| 82 |
+
for bb, jump_targets in edges.items():
|
| 83 |
+
builder.position_at_end(bbmap[bb])
|
| 84 |
+
# Insert increfs and decrefs
|
| 85 |
+
for action in nodes[bb]:
|
| 86 |
+
if action == 'incref':
|
| 87 |
+
builder.call(incref_fn, [ptr])
|
| 88 |
+
elif action == 'decref':
|
| 89 |
+
builder.call(decref_fn, [ptr])
|
| 90 |
+
else:
|
| 91 |
+
raise AssertionError('unreachable')
|
| 92 |
+
|
| 93 |
+
# Insert the terminator.
|
| 94 |
+
# Switch base on the number of jump targets.
|
| 95 |
+
n_targets = len(jump_targets)
|
| 96 |
+
if n_targets == 0:
|
| 97 |
+
builder.ret_void()
|
| 98 |
+
elif n_targets == 1:
|
| 99 |
+
[dst] = jump_targets
|
| 100 |
+
builder.branch(bbmap[dst])
|
| 101 |
+
elif n_targets == 2:
|
| 102 |
+
[left, right] = jump_targets
|
| 103 |
+
sel = builder.call(brancher_fn, ())
|
| 104 |
+
builder.cbranch(sel, bbmap[left], bbmap[right])
|
| 105 |
+
elif n_targets > 2:
|
| 106 |
+
sel = builder.call(switcher_fn, ())
|
| 107 |
+
[head, *tail] = jump_targets
|
| 108 |
+
|
| 109 |
+
sw = builder.switch(sel, default=bbmap[head])
|
| 110 |
+
for i, dst in enumerate(tail):
|
| 111 |
+
sw.add_case(sel.type(i), bbmap[dst])
|
| 112 |
+
else:
|
| 113 |
+
raise AssertionError('unreachable')
|
| 114 |
+
|
| 115 |
+
return m
|
| 116 |
+
|
| 117 |
+
def apply_refprune(self, irmod):
|
| 118 |
+
mod = llvm.parse_assembly(str(irmod))
|
| 119 |
+
pm = llvm.ModulePassManager()
|
| 120 |
+
pm.add_refprune_pass()
|
| 121 |
+
pm.run(mod)
|
| 122 |
+
return mod
|
| 123 |
+
|
| 124 |
+
def check(self, mod, expected, nodes):
|
| 125 |
+
# preprocess incref/decref locations
|
| 126 |
+
d = {}
|
| 127 |
+
for k, vs in nodes.items():
|
| 128 |
+
n_incref = vs.count('incref')
|
| 129 |
+
n_decref = vs.count('decref')
|
| 130 |
+
d[k] = {'incref': n_incref, 'decref': n_decref}
|
| 131 |
+
for k, stats in d.items():
|
| 132 |
+
if expected.get(k):
|
| 133 |
+
stats['incref'] -= 1
|
| 134 |
+
for dec_bb in expected[k]:
|
| 135 |
+
d[dec_bb]['decref'] -= 1
|
| 136 |
+
|
| 137 |
+
# find the main function
|
| 138 |
+
for f in mod.functions:
|
| 139 |
+
if f.name == 'main':
|
| 140 |
+
break
|
| 141 |
+
# check each BB
|
| 142 |
+
for bb in f.blocks:
|
| 143 |
+
stats = d[bb.name]
|
| 144 |
+
text = str(bb)
|
| 145 |
+
n_incref = text.count('NRT_incref')
|
| 146 |
+
n_decref = text.count('NRT_decref')
|
| 147 |
+
self.assertEqual(stats['incref'], n_incref, msg=f'BB {bb}')
|
| 148 |
+
self.assertEqual(stats['decref'], n_decref, msg=f'BB {bb}')
|
| 149 |
+
|
| 150 |
+
def generate_test(self, case_gen):
|
| 151 |
+
nodes, edges, expected = case_gen()
|
| 152 |
+
irmod = self.generate_ir(nodes, edges)
|
| 153 |
+
outmod = self.apply_refprune(irmod)
|
| 154 |
+
self.check(outmod, expected, nodes)
|
| 155 |
+
|
| 156 |
+
# Generate tests
|
| 157 |
+
for name, case in _iterate_cases(generate_test):
|
| 158 |
+
locals()[name] = case
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class BaseTestByIR(TestCase):
|
| 162 |
+
refprune_bitmask = 0
|
| 163 |
+
|
| 164 |
+
prologue = r"""
|
| 165 |
+
declare void @NRT_incref(i8* %ptr)
|
| 166 |
+
declare void @NRT_decref(i8* %ptr)
|
| 167 |
+
"""
|
| 168 |
+
|
| 169 |
+
def check(self, irmod, subgraph_limit=None):
|
| 170 |
+
mod = llvm.parse_assembly(f"{self.prologue}\n{irmod}")
|
| 171 |
+
pm = llvm.ModulePassManager()
|
| 172 |
+
if subgraph_limit is None:
|
| 173 |
+
pm.add_refprune_pass(self.refprune_bitmask)
|
| 174 |
+
else:
|
| 175 |
+
pm.add_refprune_pass(self.refprune_bitmask,
|
| 176 |
+
subgraph_limit=subgraph_limit)
|
| 177 |
+
before = llvm.dump_refprune_stats()
|
| 178 |
+
pm.run(mod)
|
| 179 |
+
after = llvm.dump_refprune_stats()
|
| 180 |
+
return mod, after - before
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class TestPerBB(BaseTestByIR):
|
| 184 |
+
refprune_bitmask = llvm.RefPruneSubpasses.PER_BB
|
| 185 |
+
|
| 186 |
+
per_bb_ir_1 = r"""
|
| 187 |
+
define void @main(i8* %ptr) {
|
| 188 |
+
call void @NRT_incref(i8* %ptr)
|
| 189 |
+
call void @NRT_decref(i8* %ptr)
|
| 190 |
+
ret void
|
| 191 |
+
}
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
def test_per_bb_1(self):
|
| 195 |
+
mod, stats = self.check(self.per_bb_ir_1)
|
| 196 |
+
self.assertEqual(stats.basicblock, 2)
|
| 197 |
+
|
| 198 |
+
per_bb_ir_2 = r"""
|
| 199 |
+
define void @main(i8* %ptr) {
|
| 200 |
+
call void @NRT_incref(i8* %ptr)
|
| 201 |
+
call void @NRT_incref(i8* %ptr)
|
| 202 |
+
call void @NRT_incref(i8* %ptr)
|
| 203 |
+
call void @NRT_decref(i8* %ptr)
|
| 204 |
+
call void @NRT_decref(i8* %ptr)
|
| 205 |
+
ret void
|
| 206 |
+
}
|
| 207 |
+
"""
|
| 208 |
+
|
| 209 |
+
def test_per_bb_2(self):
|
| 210 |
+
mod, stats = self.check(self.per_bb_ir_2)
|
| 211 |
+
self.assertEqual(stats.basicblock, 4)
|
| 212 |
+
# not pruned
|
| 213 |
+
self.assertIn("call void @NRT_incref(i8* %ptr)", str(mod))
|
| 214 |
+
|
| 215 |
+
per_bb_ir_3 = r"""
|
| 216 |
+
define void @main(i8* %ptr, i8* %other) {
|
| 217 |
+
call void @NRT_incref(i8* %ptr)
|
| 218 |
+
call void @NRT_incref(i8* %ptr)
|
| 219 |
+
call void @NRT_decref(i8* %ptr)
|
| 220 |
+
call void @NRT_decref(i8* %other)
|
| 221 |
+
ret void
|
| 222 |
+
}
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
def test_per_bb_3(self):
|
| 226 |
+
mod, stats = self.check(self.per_bb_ir_3)
|
| 227 |
+
self.assertEqual(stats.basicblock, 2)
|
| 228 |
+
# not pruned
|
| 229 |
+
self.assertIn("call void @NRT_decref(i8* %other)", str(mod))
|
| 230 |
+
|
| 231 |
+
per_bb_ir_4 = r"""
|
| 232 |
+
; reordered
|
| 233 |
+
define void @main(i8* %ptr, i8* %other) {
|
| 234 |
+
call void @NRT_incref(i8* %ptr)
|
| 235 |
+
call void @NRT_decref(i8* %ptr)
|
| 236 |
+
call void @NRT_decref(i8* %ptr)
|
| 237 |
+
call void @NRT_decref(i8* %other)
|
| 238 |
+
call void @NRT_incref(i8* %ptr)
|
| 239 |
+
ret void
|
| 240 |
+
}
|
| 241 |
+
"""
|
| 242 |
+
|
| 243 |
+
def test_per_bb_4(self):
|
| 244 |
+
mod, stats = self.check(self.per_bb_ir_4)
|
| 245 |
+
self.assertEqual(stats.basicblock, 4)
|
| 246 |
+
# not pruned
|
| 247 |
+
self.assertIn("call void @NRT_decref(i8* %other)", str(mod))
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class TestDiamond(BaseTestByIR):
|
| 251 |
+
refprune_bitmask = llvm.RefPruneSubpasses.DIAMOND
|
| 252 |
+
|
| 253 |
+
per_diamond_1 = r"""
|
| 254 |
+
define void @main(i8* %ptr) {
|
| 255 |
+
bb_A:
|
| 256 |
+
call void @NRT_incref(i8* %ptr)
|
| 257 |
+
br label %bb_B
|
| 258 |
+
bb_B:
|
| 259 |
+
call void @NRT_decref(i8* %ptr)
|
| 260 |
+
ret void
|
| 261 |
+
}
|
| 262 |
+
"""
|
| 263 |
+
|
| 264 |
+
def test_per_diamond_1(self):
|
| 265 |
+
mod, stats = self.check(self.per_diamond_1)
|
| 266 |
+
self.assertEqual(stats.diamond, 2)
|
| 267 |
+
|
| 268 |
+
per_diamond_2 = r"""
|
| 269 |
+
define void @main(i8* %ptr, i1 %cond) {
|
| 270 |
+
bb_A:
|
| 271 |
+
call void @NRT_incref(i8* %ptr)
|
| 272 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 273 |
+
bb_B:
|
| 274 |
+
br label %bb_D
|
| 275 |
+
bb_C:
|
| 276 |
+
br label %bb_D
|
| 277 |
+
bb_D:
|
| 278 |
+
call void @NRT_decref(i8* %ptr)
|
| 279 |
+
ret void
|
| 280 |
+
}
|
| 281 |
+
"""
|
| 282 |
+
|
| 283 |
+
def test_per_diamond_2(self):
|
| 284 |
+
mod, stats = self.check(self.per_diamond_2)
|
| 285 |
+
self.assertEqual(stats.diamond, 2)
|
| 286 |
+
|
| 287 |
+
per_diamond_3 = r"""
|
| 288 |
+
define void @main(i8* %ptr, i1 %cond) {
|
| 289 |
+
bb_A:
|
| 290 |
+
call void @NRT_incref(i8* %ptr)
|
| 291 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 292 |
+
bb_B:
|
| 293 |
+
br label %bb_D
|
| 294 |
+
bb_C:
|
| 295 |
+
call void @NRT_decref(i8* %ptr) ; reject because of decref in diamond
|
| 296 |
+
br label %bb_D
|
| 297 |
+
bb_D:
|
| 298 |
+
call void @NRT_decref(i8* %ptr)
|
| 299 |
+
ret void
|
| 300 |
+
}
|
| 301 |
+
"""
|
| 302 |
+
|
| 303 |
+
def test_per_diamond_3(self):
|
| 304 |
+
mod, stats = self.check(self.per_diamond_3)
|
| 305 |
+
self.assertEqual(stats.diamond, 0)
|
| 306 |
+
|
| 307 |
+
per_diamond_4 = r"""
|
| 308 |
+
define void @main(i8* %ptr, i1 %cond) {
|
| 309 |
+
bb_A:
|
| 310 |
+
call void @NRT_incref(i8* %ptr)
|
| 311 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 312 |
+
bb_B:
|
| 313 |
+
call void @NRT_incref(i8* %ptr) ; extra incref will not affect prune
|
| 314 |
+
br label %bb_D
|
| 315 |
+
bb_C:
|
| 316 |
+
br label %bb_D
|
| 317 |
+
bb_D:
|
| 318 |
+
call void @NRT_decref(i8* %ptr)
|
| 319 |
+
ret void
|
| 320 |
+
}
|
| 321 |
+
"""
|
| 322 |
+
|
| 323 |
+
def test_per_diamond_4(self):
|
| 324 |
+
mod, stats = self.check(self.per_diamond_4)
|
| 325 |
+
self.assertEqual(stats.diamond, 2)
|
| 326 |
+
|
| 327 |
+
per_diamond_5 = r"""
|
| 328 |
+
define void @main(i8* %ptr, i1 %cond) {
|
| 329 |
+
bb_A:
|
| 330 |
+
call void @NRT_incref(i8* %ptr)
|
| 331 |
+
call void @NRT_incref(i8* %ptr)
|
| 332 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 333 |
+
bb_B:
|
| 334 |
+
br label %bb_D
|
| 335 |
+
bb_C:
|
| 336 |
+
br label %bb_D
|
| 337 |
+
bb_D:
|
| 338 |
+
call void @NRT_decref(i8* %ptr)
|
| 339 |
+
call void @NRT_decref(i8* %ptr)
|
| 340 |
+
ret void
|
| 341 |
+
}
|
| 342 |
+
"""
|
| 343 |
+
|
| 344 |
+
def test_per_diamond_5(self):
|
| 345 |
+
mod, stats = self.check(self.per_diamond_5)
|
| 346 |
+
self.assertEqual(stats.diamond, 4)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
class TestFanout(BaseTestByIR):
|
| 350 |
+
"""More complex cases are tested in TestRefPrunePass
|
| 351 |
+
"""
|
| 352 |
+
|
| 353 |
+
refprune_bitmask = llvm.RefPruneSubpasses.FANOUT
|
| 354 |
+
|
| 355 |
+
fanout_1 = r"""
|
| 356 |
+
define void @main(i8* %ptr, i1 %cond) {
|
| 357 |
+
bb_A:
|
| 358 |
+
call void @NRT_incref(i8* %ptr)
|
| 359 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 360 |
+
bb_B:
|
| 361 |
+
call void @NRT_decref(i8* %ptr)
|
| 362 |
+
ret void
|
| 363 |
+
bb_C:
|
| 364 |
+
call void @NRT_decref(i8* %ptr)
|
| 365 |
+
ret void
|
| 366 |
+
}
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
def test_fanout_1(self):
|
| 370 |
+
mod, stats = self.check(self.fanout_1)
|
| 371 |
+
self.assertEqual(stats.fanout, 3)
|
| 372 |
+
|
| 373 |
+
fanout_2 = r"""
|
| 374 |
+
define void @main(i8* %ptr, i1 %cond, i8** %excinfo) {
|
| 375 |
+
bb_A:
|
| 376 |
+
call void @NRT_incref(i8* %ptr)
|
| 377 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 378 |
+
bb_B:
|
| 379 |
+
call void @NRT_decref(i8* %ptr)
|
| 380 |
+
ret void
|
| 381 |
+
bb_C:
|
| 382 |
+
call void @NRT_decref(i8* %ptr)
|
| 383 |
+
br label %bb_B ; illegal jump to other decref
|
| 384 |
+
}
|
| 385 |
+
"""
|
| 386 |
+
|
| 387 |
+
def test_fanout_2(self):
|
| 388 |
+
mod, stats = self.check(self.fanout_2)
|
| 389 |
+
self.assertEqual(stats.fanout, 0)
|
| 390 |
+
|
| 391 |
+
fanout_3 = r"""
|
| 392 |
+
define void @main(i8* %ptr, i1 %cond) {
|
| 393 |
+
bb_A:
|
| 394 |
+
call void @NRT_incref(i8* %ptr)
|
| 395 |
+
call void @NRT_incref(i8* %ptr)
|
| 396 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 397 |
+
bb_B:
|
| 398 |
+
call void @NRT_decref(i8* %ptr)
|
| 399 |
+
call void @NRT_decref(i8* %ptr)
|
| 400 |
+
call void @NRT_decref(i8* %ptr)
|
| 401 |
+
ret void
|
| 402 |
+
bb_C:
|
| 403 |
+
call void @NRT_decref(i8* %ptr)
|
| 404 |
+
call void @NRT_decref(i8* %ptr)
|
| 405 |
+
ret void
|
| 406 |
+
}
|
| 407 |
+
"""
|
| 408 |
+
|
| 409 |
+
def test_fanout_3(self):
|
| 410 |
+
mod, stats = self.check(self.fanout_3)
|
| 411 |
+
self.assertEqual(stats.fanout, 6)
|
| 412 |
+
|
| 413 |
+
def test_fanout_3_limited(self):
|
| 414 |
+
# With subgraph limit at 1, it is essentially turning off the fanout
|
| 415 |
+
# pruner.
|
| 416 |
+
mod, stats = self.check(self.fanout_3, subgraph_limit=1)
|
| 417 |
+
self.assertEqual(stats.fanout, 0)
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
class TestFanoutRaise(BaseTestByIR):
|
| 421 |
+
refprune_bitmask = llvm.RefPruneSubpasses.FANOUT_RAISE
|
| 422 |
+
|
| 423 |
+
fanout_raise_1 = r"""
|
| 424 |
+
define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) {
|
| 425 |
+
bb_A:
|
| 426 |
+
call void @NRT_incref(i8* %ptr)
|
| 427 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 428 |
+
bb_B:
|
| 429 |
+
call void @NRT_decref(i8* %ptr)
|
| 430 |
+
ret i32 0
|
| 431 |
+
bb_C:
|
| 432 |
+
store i8* null, i8** %excinfo, !numba_exception_output !0
|
| 433 |
+
ret i32 1
|
| 434 |
+
}
|
| 435 |
+
!0 = !{i1 true}
|
| 436 |
+
"""
|
| 437 |
+
|
| 438 |
+
def test_fanout_raise_1(self):
|
| 439 |
+
mod, stats = self.check(self.fanout_raise_1)
|
| 440 |
+
self.assertEqual(stats.fanout_raise, 2)
|
| 441 |
+
|
| 442 |
+
fanout_raise_2 = r"""
|
| 443 |
+
define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) {
|
| 444 |
+
bb_A:
|
| 445 |
+
call void @NRT_incref(i8* %ptr)
|
| 446 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 447 |
+
bb_B:
|
| 448 |
+
call void @NRT_decref(i8* %ptr)
|
| 449 |
+
ret i32 0
|
| 450 |
+
bb_C:
|
| 451 |
+
store i8* null, i8** %excinfo, !numba_exception_typo !0 ; bad metadata
|
| 452 |
+
ret i32 1
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
!0 = !{i1 true}
|
| 456 |
+
"""
|
| 457 |
+
|
| 458 |
+
def test_fanout_raise_2(self):
|
| 459 |
+
# This is ensuring that fanout_raise is not pruning when the metadata
|
| 460 |
+
# is incorrectly named.
|
| 461 |
+
mod, stats = self.check(self.fanout_raise_2)
|
| 462 |
+
self.assertEqual(stats.fanout_raise, 0)
|
| 463 |
+
|
| 464 |
+
fanout_raise_3 = r"""
|
| 465 |
+
define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) {
|
| 466 |
+
bb_A:
|
| 467 |
+
call void @NRT_incref(i8* %ptr)
|
| 468 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 469 |
+
bb_B:
|
| 470 |
+
call void @NRT_decref(i8* %ptr)
|
| 471 |
+
ret i32 0
|
| 472 |
+
bb_C:
|
| 473 |
+
store i8* null, i8** %excinfo, !numba_exception_output !0
|
| 474 |
+
ret i32 1
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
!0 = !{i32 1} ; ok; use i32
|
| 478 |
+
"""
|
| 479 |
+
|
| 480 |
+
def test_fanout_raise_3(self):
|
| 481 |
+
mod, stats = self.check(self.fanout_raise_3)
|
| 482 |
+
self.assertEqual(stats.fanout_raise, 2)
|
| 483 |
+
|
| 484 |
+
fanout_raise_4 = r"""
|
| 485 |
+
define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) {
|
| 486 |
+
bb_A:
|
| 487 |
+
call void @NRT_incref(i8* %ptr)
|
| 488 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 489 |
+
bb_B:
|
| 490 |
+
ret i32 1 ; BAD; all tails are raising without decref
|
| 491 |
+
bb_C:
|
| 492 |
+
ret i32 1 ; BAD; all tails are raising without decref
|
| 493 |
+
}
|
| 494 |
+
|
| 495 |
+
!0 = !{i1 1}
|
| 496 |
+
"""
|
| 497 |
+
|
| 498 |
+
def test_fanout_raise_4(self):
|
| 499 |
+
mod, stats = self.check(self.fanout_raise_4)
|
| 500 |
+
self.assertEqual(stats.fanout_raise, 0)
|
| 501 |
+
|
| 502 |
+
fanout_raise_5 = r"""
|
| 503 |
+
define i32 @main(i8* %ptr, i1 %cond, i8** %excinfo) {
|
| 504 |
+
bb_A:
|
| 505 |
+
call void @NRT_incref(i8* %ptr)
|
| 506 |
+
br i1 %cond, label %bb_B, label %bb_C
|
| 507 |
+
bb_B:
|
| 508 |
+
call void @NRT_decref(i8* %ptr)
|
| 509 |
+
br label %common.ret
|
| 510 |
+
bb_C:
|
| 511 |
+
store i8* null, i8** %excinfo, !numba_exception_output !0
|
| 512 |
+
br label %common.ret
|
| 513 |
+
common.ret:
|
| 514 |
+
%common.ret.op = phi i32 [ 0, %bb_B ], [ 1, %bb_C ]
|
| 515 |
+
ret i32 %common.ret.op
|
| 516 |
+
}
|
| 517 |
+
!0 = !{i1 1}
|
| 518 |
+
"""
|
| 519 |
+
|
| 520 |
+
def test_fanout_raise_5(self):
|
| 521 |
+
mod, stats = self.check(self.fanout_raise_5)
|
| 522 |
+
self.assertEqual(stats.fanout_raise, 2)
|
| 523 |
+
|
| 524 |
+
# test case 6 is from https://github.com/numba/llvmlite/issues/1023
|
| 525 |
+
fanout_raise_6 = r"""
|
| 526 |
+
define i32 @main(i8* %ptr, i1 %cond1, i1 %cond2, i1 %cond3, i8** %excinfo) {
|
| 527 |
+
bb_A:
|
| 528 |
+
call void @NRT_incref(i8* %ptr)
|
| 529 |
+
call void @NRT_incref(i8* %ptr)
|
| 530 |
+
br i1 %cond1, label %bb_B, label %bb_C
|
| 531 |
+
bb_B:
|
| 532 |
+
call void @NRT_decref(i8* %ptr)
|
| 533 |
+
br i1 %cond2, label %bb_D, label %bb_E
|
| 534 |
+
bb_C:
|
| 535 |
+
store i8* null, i8** %excinfo, !numba_exception_output !0
|
| 536 |
+
ret i32 1
|
| 537 |
+
bb_D:
|
| 538 |
+
call void @NRT_decref(i8* %ptr)
|
| 539 |
+
ret i32 0
|
| 540 |
+
bb_E:
|
| 541 |
+
call void @NRT_incref(i8* %ptr)
|
| 542 |
+
br i1 %cond3, label %bb_F, label %bb_C
|
| 543 |
+
bb_F:
|
| 544 |
+
call void @NRT_decref(i8* %ptr)
|
| 545 |
+
call void @NRT_decref(i8* %ptr)
|
| 546 |
+
ret i32 0
|
| 547 |
+
}
|
| 548 |
+
!0 = !{i1 1}
|
| 549 |
+
"""
|
| 550 |
+
|
| 551 |
+
def test_fanout_raise_6(self):
|
| 552 |
+
mod, stats = self.check(self.fanout_raise_6)
|
| 553 |
+
self.assertEqual(stats.fanout_raise, 7)
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
if __name__ == '__main__':
|
| 557 |
+
unittest.main()
|
vllm/lib/python3.10/site-packages/mpl_toolkits/axisartist/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .axislines import Axes
|
| 2 |
+
from .axislines import ( # noqa: F401
|
| 3 |
+
AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear,
|
| 4 |
+
GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero)
|
| 5 |
+
from .axis_artist import AxisArtist, GridlinesCollection # noqa: F401
|
| 6 |
+
from .grid_helper_curvelinear import GridHelperCurveLinear # noqa: F401
|
| 7 |
+
from .floating_axes import FloatingAxes, FloatingSubplot # noqa: F401
|
| 8 |
+
from mpl_toolkits.axes_grid1.parasite_axes import (
|
| 9 |
+
host_axes_class_factory, parasite_axes_class_factory)
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
ParasiteAxes = parasite_axes_class_factory(Axes)
|
| 13 |
+
HostAxes = host_axes_class_factory(Axes)
|
| 14 |
+
SubplotHost = HostAxes
|
vllm/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-310.pyc
ADDED
|
Binary file (11.2 kB). View file
|
|
|
vllm/lib/python3.10/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-310.pyc
ADDED
|
Binary file (322 Bytes). View file
|
|
|