-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
codegen.py
1457 lines (1250 loc) · 54.6 KB
/
codegen.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import warnings
import functools
import locale
import weakref
import ctypes
import html
import textwrap
import llvmlite.binding as ll
import llvmlite.ir as llvmir
from abc import abstractmethod, ABCMeta
from numba.core import utils, config, cgutils
from numba.core.llvm_bindings import create_pass_manager_builder
from numba.core.runtime.nrtopt import remove_redundant_nrt_refct
from numba.core.runtime import rtsys
from numba.core.compiler_lock import require_global_compiler_lock
from numba.core.errors import NumbaInvalidConfigWarning
from numba.misc.inspection import disassemble_elf_to_cfg
from numba.misc.llvm_pass_timings import PassTimingsCollection
_x86arch = frozenset(['x86', 'i386', 'i486', 'i586', 'i686', 'i786',
'i886', 'i986'])
def _is_x86(triple):
arch = triple.split('-')[0]
return arch in _x86arch
def _parse_refprune_flags():
"""Parse refprune flags from the `config`.
Invalid values are ignored an warn via a `NumbaInvalidConfigWarning`
category.
Returns
-------
flags : llvmlite.binding.RefPruneSubpasses
"""
flags = config.LLVM_REFPRUNE_FLAGS.split(',')
if not flags:
return 0
val = 0
for item in flags:
item = item.strip()
try:
val |= getattr(ll.RefPruneSubpasses, item.upper())
except AttributeError:
warnings.warn(f"invalid refprune flags {item!r}",
NumbaInvalidConfigWarning)
return val
def dump(header, body, lang):
if config.HIGHLIGHT_DUMPS:
try:
import pygments
except ImportError:
msg = "Please install pygments to see highlighted dumps"
raise ValueError(msg)
else:
from pygments import highlight
from pygments.lexers import GasLexer as gas_lexer
from pygments.lexers import LlvmLexer as llvm_lexer
from pygments.formatters import Terminal256Formatter
from numba.misc.dump_style import by_colorscheme
lexer_map = {'llvm': llvm_lexer, 'asm': gas_lexer}
lexer = lexer_map[lang]
def printer(arg):
print(highlight(arg, lexer(),
Terminal256Formatter(style=by_colorscheme())))
else:
printer = print
print('=' * 80)
print(header.center(80, '-'))
printer(body)
print('=' * 80)
class _CFG(object):
"""
Wraps the CFG graph for different display method.
Instance of the class can be stringified (``__repr__`` is defined) to get
the graph in DOT format. The ``.display()`` method plots the graph in
PDF. If in IPython notebook, the returned image can be inlined.
"""
def __init__(self, cres, name, py_func, **kwargs):
self.cres = cres
self.name = name
self.py_func = py_func
fn = cres.get_function(name)
self.dot = ll.get_function_cfg(fn)
self.kwargs = kwargs
def pretty_printer(self, filename=None, view=None, render_format=None,
highlight=True,
interleave=False, strip_ir=False, show_key=True,
fontsize=10):
"""
"Pretty" prints the DOT graph of the CFG.
For explanation of the parameters see the docstring for
numba.core.dispatcher::inspect_cfg.
"""
import graphviz as gv
import re
import json
import inspect
from llvmlite import binding as ll
from numba.typed import List
from types import SimpleNamespace
from collections import defaultdict
_default = False
_highlight = SimpleNamespace(incref=_default,
decref=_default,
returns=_default,
raises=_default,
meminfo=_default,
branches=_default,
llvm_intrin_calls=_default,
function_calls=_default,)
_interleave = SimpleNamespace(python=_default, lineinfo=_default)
def parse_config(_config, kwarg):
""" Parses the kwarg into a consistent format for use in configuring
the Digraph rendering. _config is the configuration instance to
update, kwarg is the kwarg on which to base the updates.
"""
if isinstance(kwarg, bool):
for attr in _config.__dict__:
setattr(_config, attr, kwarg)
elif isinstance(kwarg, dict):
for k, v in kwarg.items():
if k not in _config.__dict__:
raise ValueError("Unexpected key in kwarg: %s" % k)
if isinstance(v, bool):
setattr(_config, k, v)
else:
msg = "Unexpected value for key: %s, got:%s"
raise ValueError(msg % (k, v))
elif isinstance(kwarg, set):
for item in kwarg:
if item not in _config.__dict__:
raise ValueError("Unexpected key in kwarg: %s" % item)
else:
setattr(_config, item, True)
else:
msg = "Unhandled configuration type for kwarg %s"
raise ValueError(msg % type(kwarg))
parse_config(_highlight, highlight)
parse_config(_interleave, interleave)
# This is the colour scheme. The graphviz HTML label renderer only takes
# names for colours: https://www.graphviz.org/doc/info/shapes.html#html
cs = defaultdict(lambda: 'white') # default bg colour is white
cs['marker'] = 'orange'
cs['python'] = 'yellow'
cs['truebr'] = 'green'
cs['falsebr'] = 'red'
cs['incref'] = 'cyan'
cs['decref'] = 'turquoise'
cs['raise'] = 'lightpink'
cs['meminfo'] = 'lightseagreen'
cs['return'] = 'purple'
cs['llvm_intrin_calls'] = 'rosybrown'
cs['function_calls'] = 'tomato'
# Get the raw dot format information from LLVM and the LLVM IR
fn = self.cres.get_function(self.name)
#raw_dot = ll.get_function_cfg(fn).replace('\\l...', '')
llvm_str = self.cres.get_llvm_str()
def get_metadata(llvm_str):
""" Gets the metadata entries from the LLVM IR, these look something
like '!123 = INFORMATION'. Returns a map of metadata key to metadata
value, i.e. from the example {'!123': INFORMATION}"""
md = {}
metadata_entry = re.compile(r'(^[!][0-9]+)(\s+=\s+.*)')
for x in llvm_str.splitlines():
match = metadata_entry.match(x)
if match is not None:
g = match.groups()
if g is not None:
assert len(g) == 2
md[g[0]] = g[1]
return md
md = get_metadata(llvm_str)
# setup digraph with initial properties
def init_digraph(name, fname, fontsize):
# name and fname are arbitrary graph and file names, they appear in
# some rendering formats, the fontsize determines the output
# fontsize.
# truncate massive mangled names as file names as it causes OSError
# when trying to render to pdf
cmax = 200
if len(fname) > cmax:
wstr = (f'CFG output filename "{fname}" exceeds maximum '
f'supported length, it will be truncated.')
warnings.warn(wstr, NumbaInvalidConfigWarning)
fname = fname[:cmax]
f = gv.Digraph(name, filename=fname)
f.attr(rankdir='TB')
f.attr('node', shape='none', fontsize='%s' % str(fontsize))
return f
f = init_digraph(self.name, self.name, fontsize)
# A lot of regex is needed to parse the raw dot output. This output
# contains a mix of LLVM IR in the labels, and also DOT markup.
# DOT syntax, matches a "port" (where the tail of an edge starts)
port_match = re.compile('.*{(.*)}.*')
# DOT syntax, matches the "port" value from a found "port_match"
port_jmp_match = re.compile('.*<(.*)>(.*)')
# LLVM syntax, matches a LLVM debug marker
metadata_marker = re.compile(r'.*!dbg\s+(![0-9]+).*')
# LLVM syntax, matches a location entry
location_expr = (r'.*!DILocation\(line:\s+([0-9]+),'
r'\s+column:\s+([0-9]),.*')
location_entry = re.compile(location_expr)
# LLVM syntax, matches LLVMs internal debug value calls
dbg_value = re.compile(r'.*call void @llvm.dbg.value.*')
# LLVM syntax, matches tokens for highlighting
nrt_incref = re.compile(r"@NRT_incref\b")
nrt_decref = re.compile(r"@NRT_decref\b")
nrt_meminfo = re.compile("@NRT_MemInfo")
ll_intrin_calls = re.compile(r".*call.*@llvm\..*")
ll_function_call = re.compile(r".*call.*@.*")
ll_raise = re.compile(r"store .*\!numba_exception_output.*")
ll_return = re.compile("ret i32 [^1],?.*")
# wrapper function for line wrapping LLVM lines
def wrap(s):
return textwrap.wrap(s, width=120, subsequent_indent='... ')
# function to fix (sometimes escaped for DOT!) LLVM IR etc that needs to
# be HTML escaped
def clean(s):
# Grab first 300 chars only, 1. this should be enough to identify
# the token and it keeps names short. 2. graphviz/dot has a maximum
# buffer size near 585?!, with additional transforms it's hard to
# know if this would be exceeded. 3. hash of the token string is
# written into the rendering to permit exact identification against
# e.g. LLVM IR dump if necessary.
n = 300
if len(s) > n:
hs = str(hash(s))
s = '{}...<hash={}>'.format(s[:n], hs)
s = html.escape(s) # deals with &, < and >
s = s.replace('\\{', "{")
s = s.replace('\\}', "}")
s = s.replace('\\', "\")
s = s.replace('%', "%")
s = s.replace('!', "!")
return s
# These hold the node and edge ids from the raw dot information. They
# are used later to wire up a new DiGraph that has the same structure
# as the raw dot but with new nodes.
node_ids = {}
edge_ids = {}
# Python source lines, used if python source interleave is requested
if _interleave.python:
src_code, firstlineno = inspect.getsourcelines(self.py_func)
# This is the dot info from LLVM, it's in DOT form and has continuation
# lines, strip them and then re-parse into `dot_json` form for use in
# producing a formatted output.
raw_dot = ll.get_function_cfg(fn).replace('\\l...', '')
json_bytes = gv.Source(raw_dot).pipe(format='dot_json')
jzon = json.loads(json_bytes.decode('utf-8'))
idc = 0
# Walk the "objects" (nodes) in the DOT output
for obj in jzon['objects']:
# These are used to keep tabs on the current line and column numbers
# as per the markers. They are tracked so as to make sure a marker
# is only emitted if there's a change in the marker.
cur_line, cur_col = -1, -1
label = obj['label']
name = obj['name']
gvid = obj['_gvid']
node_ids[gvid] = name
# Label is DOT format, it needs the head and tail removing and then
# splitting for walking.
label = label[1:-1]
lines = label.split('\\l')
# Holds the new lines
new_lines = []
# Aim is to produce an HTML table a bit like this:
#
# |------------|
# | HEADER | <-- this is the block header
# |------------|
# | LLVM SRC | <--
# | Marker? | < this is the label/block body
# | Python src?| <--
# |------------|
# | T | F | <-- this is the "ports", also determines col_span
# --------------
#
# This is HTML syntax, its the column span. If there's a switch or a
# branch at the bottom of the node this is rendered as multiple
# columns in a table. First job is to go and render that and work
# out how many columns are needed as that dictates how many columns
# the rest of the source lines must span. In DOT syntax the places
# that edges join nodes are referred to as "ports". Syntax in DOT
# is like `node:port`.
col_span = 1
# First see if there is a port entry for this node
port_line = ''
matched = port_match.match(lines[-1])
sliced_lines = lines
if matched is not None:
# There is a port
ports = matched.groups()[0]
ports_tokens = ports.split('|')
col_span = len(ports_tokens)
# Generate HTML table data cells, one for each port. If the
# ports correspond to a branch then they can optionally
# highlighted based on T/F.
tdfmt = ('<td BGCOLOR="{}" BORDER="1" ALIGN="center" '
'PORT="{}">{}</td>')
tbl_data = []
if _highlight.branches:
colors = {'T': cs['truebr'], 'F': cs['falsebr']}
else:
colors = {}
for tok in ports_tokens:
target, value = port_jmp_match.match(tok).groups()
color = colors.get(value, 'white')
tbl_data.append(tdfmt.format(color, target, value))
port_line = ''.join(tbl_data)
# Drop the last line from the rest of the parse as it's the port
# and just been dealt with.
sliced_lines = lines[:-1]
# loop peel the block header, it needs a HTML border
fmtheader = ('<tr><td BGCOLOR="{}" BORDER="1" ALIGN="left" '
'COLSPAN="{}">{}</td></tr>')
new_lines.append(fmtheader.format(cs['default'], col_span,
clean(sliced_lines[0].strip())))
# process rest of block creating the table row at a time.
fmt = ('<tr><td BGCOLOR="{}" BORDER="0" ALIGN="left" '
'COLSPAN="{}">{}</td></tr>')
def metadata_interleave(l, new_lines):
"""
Search line `l` for metadata associated with python or line info
and inject it into `new_lines` if requested.
"""
matched = metadata_marker.match(l)
if matched is not None:
# there's a metadata marker
g = matched.groups()
if g is not None:
assert len(g) == 1, g
marker = g[0]
debug_data = md.get(marker, None)
if debug_data is not None:
# and the metadata marker has a corresponding piece
# of metadata
ld = location_entry.match(debug_data)
if ld is not None:
# and the metadata is line info... proceed
assert len(ld.groups()) == 2, ld
line, col = ld.groups()
# only emit a new marker if the line number in
# the metadata is "new".
if line != cur_line or col != cur_col:
if _interleave.lineinfo:
mfmt = 'Marker %s, Line %s, column %s'
mark_line = mfmt % (marker, line, col)
ln = fmt.format(cs['marker'], col_span,
clean(mark_line))
new_lines.append(ln)
if _interleave.python:
# TODO:
# +1 for decorator, this probably needs
# the same thing doing as for the
# error messages where the decorator
# is scanned for, its not always +1!
lidx = int(line) - (firstlineno + 1)
source_line = src_code[lidx + 1]
ln = fmt.format(cs['python'], col_span,
clean(source_line))
new_lines.append(ln)
return line, col
for l in sliced_lines[1:]:
# Drop LLVM debug call entries
if dbg_value.match(l):
continue
# if requested generate interleaving of markers or python from
# metadata
if _interleave.lineinfo or _interleave.python:
updated_lineinfo = metadata_interleave(l, new_lines)
if updated_lineinfo is not None:
cur_line, cur_col = updated_lineinfo
# Highlight other LLVM features if requested, HTML BGCOLOR
# property is set by this.
if _highlight.incref and nrt_incref.search(l):
colour = cs['incref']
elif _highlight.decref and nrt_decref.search(l):
colour = cs['decref']
elif _highlight.meminfo and nrt_meminfo.search(l):
colour = cs['meminfo']
elif _highlight.raises and ll_raise.search(l):
# search for raise as its more specific than exit
colour = cs['raise']
elif _highlight.returns and ll_return.search(l):
colour = cs['return']
elif _highlight.llvm_intrin_calls and ll_intrin_calls.search(l):
colour = cs['llvm_intrin_calls']
elif _highlight.function_calls and ll_function_call.search(l):
colour = cs['function_calls']
else:
colour = cs['default']
# Use the default coloring as a flag to force printing if a
# special token print was requested AND LLVM ir stripping is
# required
if colour is not cs['default'] or not strip_ir:
for x in wrap(clean(l)):
new_lines.append(fmt.format(colour, col_span, x))
# add in the port line at the end of the block if it was present
# (this was built right at the top of the parse)
if port_line:
new_lines.append('<tr>{}</tr>'.format(port_line))
# If there was data, create a table, else don't!
dat = ''.join(new_lines)
if dat:
tab = (('<table id="%s" BORDER="1" CELLBORDER="0" '
'CELLPADDING="0" CELLSPACING="0">%s</table>') % (idc,
dat))
label = '<{}>'.format(tab)
else:
label = ''
# finally, add a replacement node for the original with a new marked
# up label.
f.node(name, label=label)
# Parse the edge data
if 'edges' in jzon: # might be a single block, no edges
for edge in jzon['edges']:
gvid = edge['_gvid']
tp = edge.get('tailport', None)
edge_ids[gvid] = (edge['head'], edge['tail'], tp)
# Write in the edge wiring with respect to the new nodes:ports.
for gvid, edge in edge_ids.items():
tail = node_ids[edge[1]]
head = node_ids[edge[0]]
port = edge[2]
if port is not None:
tail += ':%s' % port
f.edge(tail, head)
# Add a key to the graph if requested.
if show_key:
key_tab = []
for k, v in cs.items():
key_tab.append(('<tr><td BGCOLOR="{}" BORDER="0" ALIGN="center"'
'>{}</td></tr>').format(v, k))
# The first < and last > are DOT syntax, rest is DOT HTML.
f.node("Key", label=('<<table BORDER="1" CELLBORDER="1" '
'CELLPADDING="2" CELLSPACING="1"><tr><td BORDER="0">'
'Key:</td></tr>{}</table>>').format(''.join(key_tab)))
# Render if required
if filename is not None or view is not None:
f.render(filename=filename, view=view, format=render_format)
# Else pipe out a SVG
return f.pipe(format='svg')
def display(self, filename=None, format='pdf', view=False):
"""
Plot the CFG. In IPython notebook, the return image object can be
inlined.
The *filename* option can be set to a specific path for the rendered
output to write to. If *view* option is True, the plot is opened by
the system default application for the image format (PDF). *format* can
be any valid format string accepted by graphviz, default is 'pdf'.
"""
rawbyt = self.pretty_printer(filename=filename, view=view,
render_format=format, **self.kwargs)
return rawbyt.decode('utf-8')
def _repr_svg_(self):
return self.pretty_printer(**self.kwargs).decode('utf-8')
def __repr__(self):
return self.dot
class CodeLibrary(metaclass=ABCMeta):
"""
An interface for bundling LLVM code together and compiling it.
It is tied to a *codegen* instance (e.g. JITCPUCodegen) that will
determine how the LLVM code is transformed and linked together.
"""
_finalized = False
_object_caching_enabled = False
_disable_inspection = False
def __init__(self, codegen: "CPUCodegen", name: str):
self._codegen = codegen
self._name = name
ptc_name = f"{self.__class__.__name__}({self._name!r})"
self._recorded_timings = PassTimingsCollection(ptc_name)
# Track names of the dynamic globals
self._dynamic_globals = []
@property
def has_dynamic_globals(self):
self._ensure_finalized()
return len(self._dynamic_globals) > 0
@property
def recorded_timings(self):
return self._recorded_timings
@property
def codegen(self):
"""
The codegen object owning this library.
"""
return self._codegen
@property
def name(self):
return self._name
def __repr__(self):
return "<Library %r at 0x%x>" % (self.name, id(self))
def _raise_if_finalized(self):
if self._finalized:
raise RuntimeError("operation impossible on finalized object %r"
% (self,))
def _ensure_finalized(self):
if not self._finalized:
self.finalize()
def create_ir_module(self, name):
"""
Create an LLVM IR module for use by this library.
"""
self._raise_if_finalized()
ir_module = self._codegen._create_empty_module(name)
return ir_module
@abstractmethod
def add_linking_library(self, library):
"""
Add a library for linking into this library, without losing
the original library.
"""
@abstractmethod
def add_ir_module(self, ir_module):
"""
Add an LLVM IR module's contents to this library.
"""
@abstractmethod
def finalize(self):
"""
Finalize the library. After this call, nothing can be added anymore.
Finalization involves various stages of code optimization and
linking.
"""
@abstractmethod
def get_function(self, name):
"""
Return the function named ``name``.
"""
@abstractmethod
def get_llvm_str(self):
"""
Get the human-readable form of the LLVM module.
"""
@abstractmethod
def get_asm_str(self):
"""
Get the human-readable assembly.
"""
#
# Object cache hooks and serialization
#
def enable_object_caching(self):
self._object_caching_enabled = True
self._compiled_object = None
self._compiled = False
def _get_compiled_object(self):
if not self._object_caching_enabled:
raise ValueError("object caching not enabled in %s" % (self,))
if self._compiled_object is None:
raise RuntimeError("no compiled object yet for %s" % (self,))
return self._compiled_object
def _set_compiled_object(self, value):
if not self._object_caching_enabled:
raise ValueError("object caching not enabled in %s" % (self,))
if self._compiled:
raise ValueError("library already compiled: %s" % (self,))
self._compiled_object = value
self._disable_inspection = True
class CPUCodeLibrary(CodeLibrary):
def __init__(self, codegen, name):
super().__init__(codegen, name)
self._linking_libraries = [] # maintain insertion order
self._final_module = ll.parse_assembly(
str(self._codegen._create_empty_module(self.name)))
self._final_module.name = cgutils.normalize_ir_text(self.name)
self._shared_module = None
def _optimize_functions(self, ll_module):
"""
Internal: run function-level optimizations inside *ll_module*.
"""
# Enforce data layout to enable layout-specific optimizations
ll_module.data_layout = self._codegen._data_layout
with self._codegen._function_pass_manager(ll_module) as fpm:
# Run function-level optimizations to reduce memory usage and improve
# module-level optimization.
for func in ll_module.functions:
k = f"Function passes on {func.name!r}"
with self._recorded_timings.record(k):
fpm.initialize()
fpm.run(func)
fpm.finalize()
def _optimize_final_module(self):
"""
Internal: optimize this library's final module.
"""
mpm_cheap = self._codegen._module_pass_manager(loop_vectorize=self._codegen._loopvect,
slp_vectorize=False,
opt=self._codegen._opt_level,
cost="cheap")
mpm_full = self._codegen._module_pass_manager()
cheap_name = "Module passes (cheap optimization for refprune)"
with self._recorded_timings.record(cheap_name):
# A cheaper optimisation pass is run first to try and get as many
# refops into the same function as possible via inlining
mpm_cheap.run(self._final_module)
# Refop pruning is then run on the heavily inlined function
if not config.LLVM_REFPRUNE_PASS:
self._final_module = remove_redundant_nrt_refct(self._final_module)
full_name = "Module passes (full optimization)"
with self._recorded_timings.record(full_name):
# The full optimisation suite is then run on the refop pruned IR
mpm_full.run(self._final_module)
def _get_module_for_linking(self):
"""
Internal: get a LLVM module suitable for linking multiple times
into another library. Exported functions are made "linkonce_odr"
to allow for multiple definitions, inlining, and removal of
unused exports.
See discussion in https://github.com/numba/numba/pull/890
"""
self._ensure_finalized()
if self._shared_module is not None:
return self._shared_module
mod = self._final_module
to_fix = []
nfuncs = 0
for fn in mod.functions:
nfuncs += 1
if not fn.is_declaration and fn.linkage == ll.Linkage.external:
to_fix.append(fn.name)
if nfuncs == 0:
# This is an issue which can occur if loading a module
# from an object file and trying to link with it, so detect it
# here to make debugging easier.
raise RuntimeError("library unfit for linking: "
"no available functions in %s"
% (self,))
if to_fix:
mod = mod.clone()
for name in to_fix:
# NOTE: this will mark the symbol WEAK if serialized
# to an ELF file
mod.get_function(name).linkage = 'linkonce_odr'
self._shared_module = mod
return mod
def add_linking_library(self, library):
library._ensure_finalized()
self._linking_libraries.append(library)
def add_ir_module(self, ir_module):
self._raise_if_finalized()
assert isinstance(ir_module, llvmir.Module)
ir = cgutils.normalize_ir_text(str(ir_module))
ll_module = ll.parse_assembly(ir)
ll_module.name = ir_module.name
ll_module.verify()
self.add_llvm_module(ll_module)
def add_llvm_module(self, ll_module):
self._optimize_functions(ll_module)
# TODO: we shouldn't need to recreate the LLVM module object
if not config.LLVM_REFPRUNE_PASS:
ll_module = remove_redundant_nrt_refct(ll_module)
self._final_module.link_in(ll_module)
def finalize(self):
require_global_compiler_lock()
# Report any LLVM-related problems to the user
self._codegen._check_llvm_bugs()
self._raise_if_finalized()
if config.DUMP_FUNC_OPT:
dump("FUNCTION OPTIMIZED DUMP %s" % self.name,
self.get_llvm_str(), 'llvm')
# Link libraries for shared code
seen = set()
for library in self._linking_libraries:
if library not in seen:
seen.add(library)
self._final_module.link_in(
library._get_module_for_linking(), preserve=True,
)
# Optimize the module after all dependences are linked in above,
# to allow for inlining.
self._optimize_final_module()
self._final_module.verify()
self._finalize_final_module()
def _finalize_dynamic_globals(self):
# Scan for dynamic globals
for gv in self._final_module.global_variables:
if gv.name.startswith('numba.dynamic.globals'):
self._dynamic_globals.append(gv.name)
def _verify_declare_only_symbols(self):
# Verify that no declare-only function compiled by numba.
for fn in self._final_module.functions:
# We will only check for symbol name starting with '_ZN5numba'
if fn.is_declaration and fn.name.startswith('_ZN5numba'):
msg = 'Symbol {} not linked properly'
raise AssertionError(msg.format(fn.name))
def _finalize_final_module(self):
"""
Make the underlying LLVM module ready to use.
"""
self._finalize_dynamic_globals()
self._verify_declare_only_symbols()
# Remember this on the module, for the object cache hooks
self._final_module.__library = weakref.proxy(self)
# It seems add_module() must be done only here and not before
# linking in other modules, otherwise get_pointer_to_function()
# could fail.
cleanup = self._codegen._add_module(self._final_module)
if cleanup:
weakref.finalize(self, cleanup)
self._finalize_specific()
self._finalized = True
if config.DUMP_OPTIMIZED:
dump("OPTIMIZED DUMP %s" % self.name, self.get_llvm_str(), 'llvm')
if config.DUMP_ASSEMBLY:
dump("ASSEMBLY %s" % self.name, self.get_asm_str(), 'asm')
def get_defined_functions(self):
"""
Get all functions defined in the library. The library must have
been finalized.
"""
mod = self._final_module
for fn in mod.functions:
if not fn.is_declaration:
yield fn
def get_function(self, name):
return self._final_module.get_function(name)
def _sentry_cache_disable_inspection(self):
if self._disable_inspection:
warnings.warn('Inspection disabled for cached code. '
'Invalid result is returned.')
def get_llvm_str(self):
self._sentry_cache_disable_inspection()
return str(self._final_module)
def get_asm_str(self):
self._sentry_cache_disable_inspection()
return str(self._codegen._tm.emit_assembly(self._final_module))
def get_function_cfg(self, name, py_func=None, **kwargs):
"""
Get control-flow graph of the LLVM function
"""
self._sentry_cache_disable_inspection()
return _CFG(self, name, py_func, **kwargs)
def get_disasm_cfg(self, mangled_name):
"""
Get the CFG of the disassembly of the ELF object at symbol mangled_name.
Requires python package: r2pipe
Requires radare2 binary on $PATH.
Notebook rendering requires python package: graphviz
Optionally requires a compiler toolchain (via pycc) to link the ELF to
get better disassembly results.
"""
elf = self._get_compiled_object()
return disassemble_elf_to_cfg(elf, mangled_name)
@classmethod
def _dump_elf(cls, buf):
"""
Dump the symbol table of an ELF file.
Needs pyelftools (https://github.com/eliben/pyelftools)
"""
from elftools.elf.elffile import ELFFile
from elftools.elf import descriptions
from io import BytesIO
f = ELFFile(BytesIO(buf))
print("ELF file:")
for sec in f.iter_sections():
if sec['sh_type'] == 'SHT_SYMTAB':
symbols = sorted(sec.iter_symbols(), key=lambda sym: sym.name)
print(" symbols:")
for sym in symbols:
if not sym.name:
continue
print(" - %r: size=%d, value=0x%x, type=%s, bind=%s"
% (sym.name.decode(),
sym['st_size'],
sym['st_value'],
descriptions.describe_symbol_type(sym['st_info']['type']),
descriptions.describe_symbol_bind(sym['st_info']['bind']),
))
print()
@classmethod
def _object_compiled_hook(cls, ll_module, buf):
"""
`ll_module` was compiled into object code `buf`.
"""
try:
self = ll_module.__library
except AttributeError:
return
if self._object_caching_enabled:
self._compiled = True
self._compiled_object = buf
@classmethod
def _object_getbuffer_hook(cls, ll_module):
"""
Return a cached object code for `ll_module`.
"""
try:
self = ll_module.__library
except AttributeError:
return
if self._object_caching_enabled and self._compiled_object:
buf = self._compiled_object
self._compiled_object = None
return buf
def serialize_using_bitcode(self):
"""
Serialize this library using its bitcode as the cached representation.
"""
self._ensure_finalized()
return (self.name, 'bitcode', self._final_module.as_bitcode())
def serialize_using_object_code(self):
"""
Serialize this library using its object code as the cached
representation. We also include its bitcode for further inlining
with other libraries.
"""
self._ensure_finalized()
data = (self._get_compiled_object(),
self._get_module_for_linking().as_bitcode())
return (self.name, 'object', data)
@classmethod
def _unserialize(cls, codegen, state):
name, kind, data = state
self = codegen.create_library(name)
assert isinstance(self, cls)
if kind == 'bitcode':
# No need to re-run optimizations, just make the module ready
self._final_module = ll.parse_bitcode(data)
self._finalize_final_module()
return self
elif kind == 'object':
object_code, shared_bitcode = data
self.enable_object_caching()
self._set_compiled_object(object_code)
self._shared_module = ll.parse_bitcode(shared_bitcode)
self._finalize_final_module()
# Load symbols from cache
self._codegen._engine._load_defined_symbols(self._shared_module)
return self
else:
raise ValueError("unsupported serialization kind %r" % (kind,))
class AOTCodeLibrary(CPUCodeLibrary):
def emit_native_object(self):
"""
Return this library as a native object (a bytestring) -- for example
ELF under Linux.
This function implicitly calls .finalize().
"""
self._ensure_finalized()
return self._codegen._tm.emit_object(self._final_module)
def emit_bitcode(self):
"""
Return this library as LLVM bitcode (a bytestring).
This function implicitly calls .finalize().
"""
self._ensure_finalized()
return self._final_module.as_bitcode()
def _finalize_specific(self):
pass
class JITCodeLibrary(CPUCodeLibrary):
def get_pointer_to_function(self, name):
"""
Generate native code for function named *name* and return a pointer
to the start of the function (as an integer).
This function implicitly calls .finalize().
Returns
-------
pointer : int
- zero (null) if no symbol of *name* is defined by this code
library.
- non-zero if the symbol is defined.
"""
self._ensure_finalized()
ee = self._codegen._engine
if not ee.is_symbol_defined(name):
return 0