157
|
1 # IR-Structures:
|
171
|
2 from .instruction import *
|
|
3 from .basicblock import BasicBlock
|
157
|
4
|
155
|
5 class Module:
|
170
|
6 """ Main container for a piece of code. """
|
155
|
7 def __init__(self, name):
|
|
8 self.name = name
|
172
|
9 self.funcs = []
|
205
|
10 self.variables = []
|
|
11
|
158
|
12 def __repr__(self):
|
170
|
13 return 'IR-module [{0}]'.format(self.name)
|
205
|
14
|
155
|
15 def getInstructions(self):
|
171
|
16 ins = []
|
172
|
17 for bb in self.BasicBlocks:
|
171
|
18 ins += bb.Instructions
|
|
19 return ins
|
155
|
20 Instructions = property(getInstructions)
|
205
|
21
|
171
|
22 def getBBs(self):
|
172
|
23 bbs = []
|
|
24 for f in self.Functions:
|
|
25 bbs += f.BasicBlocks
|
|
26 return bbs
|
205
|
27
|
171
|
28 BasicBlocks = property(getBBs)
|
172
|
29 def addFunc(self, f):
|
|
30 self.funcs.append(f)
|
205
|
31 addFunction = addFunc
|
|
32
|
|
33 def addVariable(self, v):
|
|
34 self.variables.append(v)
|
|
35
|
|
36 def getVariables(self):
|
|
37 return self.variables
|
|
38 Variables = property(getVariables)
|
|
39
|
|
40 def getFunctions(self):
|
172
|
41 return self.funcs
|
205
|
42 Functions = property(getFunctions)
|
|
43
|
230
|
44 def findFunction(self, name):
|
|
45 for f in self.funcs:
|
|
46 if f.name == name:
|
|
47 return f
|
|
48 raise KeyError(name)
|
|
49
|
170
|
50 def dump(self):
|
|
51 print(self)
|
205
|
52 for v in self.Variables:
|
|
53 print(' ', v)
|
172
|
54 for fn in self.Functions:
|
|
55 print(fn)
|
|
56 for bb in fn.BasicBlocks:
|
|
57 print(' ', bb)
|
|
58 for ins in bb.Instructions:
|
|
59 print(' ', ins)
|
205
|
60
|
171
|
61 def dumpgv(self, outf):
|
|
62 outf.write('digraph G \n{\n')
|
173
|
63 for f in self.Functions:
|
174
|
64 outf.write('{0} [label="{1}" shape=box3d]\n'.format(id(f), f))
|
173
|
65 for bb in f.BasicBlocks:
|
|
66 contents = str(bb) + '\n'
|
|
67 contents += '\n'.join([str(i) for i in bb.Instructions])
|
174
|
68 outf.write('{0} [shape=note label="{1}"];\n'.format(id(bb), contents))
|
173
|
69 for successor in bb.Successors:
|
|
70 outf.write('"{0}" -> "{1}"\n'.format(id(bb), id(successor)))
|
177
|
71 # Draw dags if any:
|
|
72 if hasattr(bb, 'dag'):
|
|
73 outf.write('{0} -> {1}\n'.format(id(bb), id(bb.dag)))
|
|
74 bb.dag.dumpgv(outf)
|
|
75
|
173
|
76 outf.write('"{0}" -> "{1}" [label="entry"]\n'.format(id(f), id(f.entry)))
|
171
|
77 outf.write('}\n')
|
155
|
78
|
171
|
79 # Analysis functions:
|
|
80 def check(self):
|
239
|
81 """ Perform sanity check on module """
|
|
82 for i in self.Instructions:
|
171
|
83 for t in i.defs:
|
|
84 assert type(t) is Value, "def must be Value, not {0}".format(type(t))
|
|
85 for t in i.uses:
|
174
|
86 assert type(t) is Use, "use must be Value, not {0}".format(type(t))
|
239
|
87 for f in self.Functions:
|
|
88 f.check()
|
|
89
|
171
|
90
|