source: proto/Compiler/pablo.py @ 772

Last change on this file since 772 was 772, checked in by cameron, 8 years ago

Fix total carry count for @any_carry.

File size: 12.5 KB
Line 
1#
2# Pablo.py - parallel bitstream to bitblock
3#  2nd generation compiler
4#
5# Copyright 2010, Robert D. Cameron
6# All rights reserved.
7#
8import ast, copy, sys
9import Cgen
10
11
12# HELPER functions for AST recognition/construction
13
14def is_Advance_Call(fncall):   # extracted from old py2bitexpr.py
15        if isinstance(fncall.func, ast.Name): iscall = fncall.func.id == 'Advance'
16        elif isinstance(fncall.func, ast.Attribute) and isinstance(fncall.func.value, ast.Name):
17                 iscall = fncall.func.value.id == 'bitutil' and fncall.func.attr == 'Advance'
18        return iscall and len(fncall.args) == 1 and fncall.kwargs == None and fncall.starargs == None
19
20def is_ScanThru_Call(fncall):  # extracted from old py2bitexpr.py
21        if isinstance(fncall.func, ast.Name): iscall = fncall.func.id == 'ScanThru'
22        elif isinstance(fncall.func, ast.Attribute) and isinstance(fncall.func.value, ast.Name):
23                 iscall = fncall.func.value.id == 'bitutil' and fncall.func.attr == 'ScanThru'
24        return iscall and len(fncall.args) == 2 and fncall.kwargs == None and fncall.starargs == None
25
26def is_simd_not(e):
27  return isinstance(e, ast.Call) and isinstance(e.func, ast.Name) and e.func.id == 'simd_not'
28
29def mkQname(obj, field):
30  return ast.Attribute(ast.Name(obj, ast.Load()), field, ast.Load())
31
32def mkCall(fn_name, args):
33  if isinstance(fn_name, str): fn_name = ast.Name(fn_name, ast.Load())
34  return ast.Call(fn_name, args, [], None, None)
35
36def mkCallStmt(fn_name, args):
37  if isinstance(fn_name, str): fn_name = ast.Name(fn_name, ast.Load())
38  return ast.Expr(ast.Call(fn_name, args, [], None, None))
39
40#
41# Reducing AugAssign
42#
43class AugAssignRemoval(ast.NodeTransformer):
44  def xfrm(self, t):
45    return self.generic_visit(t)
46  def visit_AugAssign(self, e):
47    self.generic_visit(e)
48    return ast.Assign([e.target], ast.BinOp(e.target, e.op, e.value))
49
50#
51# Introducing BitBlock logical operations
52#
53class Bitwise_to_SIMD(ast.NodeTransformer):
54  """
55  Make the following substitutions:
56     x & y => simd_and(x, y)
57     x & ~y => simd_andc(x, y)
58     x | y => simd_or(x, y)
59     x ^ y => simd_xor(x, y)
60     ~x    => simd_not(x)
61     0     => simd_const_1(0)
62     -1    => simd_const_1(1)
63     if x: => if bitblock_has_bit(x):
64  while x: => while bitblock_has_bit(x):
65  >>> ast_show(Bitwise_to_SIMD().xfrm(ast.parse("pfx = bit0 & bit1; sfx = bit0 &~ bit1")))
66 
67  pfx = simd_and(bit0, bit1)
68  sfx = simd_and(bit0, simd_not(bit1))
69  >>>
70  """
71  def xfrm(self, t):
72    return self.generic_visit(t)
73  def visit_UnaryOp(self, t):
74    self.generic_visit(t)
75    if isinstance(t.op, ast.Invert):
76      return mkCall('simd_not', [t.operand])
77    else: return t
78  def visit_BinOp(self, t):
79    self.generic_visit(t)
80    if isinstance(t.op, ast.BitOr):
81      return mkCall('simd_or', [t.left, t.right])
82    elif isinstance(t.op, ast.BitAnd):
83      if is_simd_not(t.right): return mkCall('simd_andc', [t.left, t.right.args[0]])
84      elif is_simd_not(t.left): return mkCall('simd_andc', [t.right, t.left.args[0]])
85      else: return mkCall('simd_and', [t.left, t.right])
86    elif isinstance(t.op, ast.BitXor):
87      return mkCall('simd_xor', [t.left, t.right])
88    else: return t
89  def visit_Num(self, numnode):
90    n = numnode.n
91    if n == 0: return mkCall('simd_const_1', [numnode])
92    elif n == -1: return mkCall('simd_const_1', [ast.Num(1)])
93    else: return numnode
94  def visit_If(self, ifNode):
95    self.generic_visit(ifNode)
96    ifNode.test = mkCall('bitblock_has_bit', [ifNode.test])
97    return ifNode
98  def visit_While(self, whileNode):
99    self.generic_visit(whileNode)
100    whileNode.test = mkCall('bitblock_has_bit', [whileNode.test])
101    return whileNode
102  def visit_Subscript(self, numnode):
103    return numnode  # no recursive modifications of index expressions
104
105
106#
107#  Generating BitBlock declarations for Local Variables
108#
109#
110class LocalVars(ast.NodeVisitor):
111  def visit_Name(self, nm):
112    if isinstance(nm.ctx, ast.Param):
113      self.params.append(nm.id)
114    if isinstance(nm.ctx, ast.Store):
115      if nm.id not in self.stores: self.stores.append(nm.id)
116  def get(self, node): 
117    self.params=[]
118    self.stores=[]
119    self.generic_visit(node)
120    return [v for v in self.stores if not v in self.params]
121
122MAX_LINE_LENGTH = 80
123
124def BitBlock_decls_from_vars(varlist):
125  global MAX_LINE_LENGTH
126  decls = "  BitBlock"
127  pending = ""
128  linelgth = 10
129  for v in varlist:
130    if linelgth + len(v) + 2 <= MAX_LINE_LENGTH:
131      decls += pending + " " + v
132      linelgth += len(pending + v) + 1
133    else:
134      decls += ";\n  BitBlock " + v
135      linelgth = 11 + len(v)
136    pending = ","
137  decls += ";\n"
138  return decls
139
140def BitBlock_decls_of_fn(fndef):
141  return BitBlock_decls_from_vars(LocalVars().get(fndef))
142
143def BitBlock_header_of_fn(fndef):
144  Ccode = "static inline void " + fndef.name + "("
145  pending = ""
146  for arg in fndef.args.args:
147    if isinstance(arg, ast.Name):
148      Ccode += pending + arg.id.upper()[0] + arg.id[1:] + " & " + arg.id
149      pending = ", "
150  Ccode += ")"
151  return Ccode
152
153
154
155#
156#  Stream Initialization Statement Extraction
157#
158#  streamvar = 1 ==> streamvar = sisd_from_int(1) initially.
159class StreamInitializations(ast.NodeTransformer):
160  def xfrm(self, node):
161    self.stream_stmts = []
162    self.loop_post_inits = []
163    self.generic_visit(node)
164    return Cgen.py2C().gen(self.stream_stmts)
165  def visit_Assign(self, node):
166    if isinstance(node.value, ast.Num):
167      if node.value.n == 0: return node
168      elif node.value.n == -1: return node
169      else: 
170        stream_init = copy.deepcopy(node)
171        stream_init.value = mkCall('sisd_from_int', [node.value])
172        loop_init = copy.deepcopy(node)
173        loop_init.value.n = 0
174        self.stream_stmts.append(stream_init)
175        self.loop_post_inits.append(loop_init)
176        return None
177    else: return node
178  def visit_FunctionDef(self, node):
179    self.generic_visit(node)
180    node.body = node.body + self.loop_post_inits
181    return node
182
183
184#
185# Carry Introduction Transformation
186#
187
188class CarryCounter(ast.NodeVisitor):
189  def visit_Call(self, callnode):
190    self.generic_visit(callnode)
191    if is_Advance_Call(callnode) or is_ScanThru_Call(callnode): 
192      self.carry_count += 1
193  def visit_BinOp(self, exprnode):
194    self.generic_visit(exprnode)
195    if isinstance(exprnode.op, ast.Sub):
196      self.carry_count += 1
197    if isinstance(exprnode.op, ast.Add):
198      self.carry_count += 1
199  def count(self, nodeToVisit):
200    self.carry_count = 0
201    self.generic_visit(nodeToVisit)
202    return self.carry_count
203
204
205def Carry_decl_of_fn(fndef):
206  carry_count = CarryCounter().count(fndef)
207  if carry_count == 0: return ""
208  else: return "  CarryDeclare(carryQ, %i);\n" % carry_count
209
210                   
211class CarryIntro(ast.NodeTransformer):
212  def __init__(self, carryvar="carryQ", mode = "ci_co"):
213    self.carryvar = ast.Name(carryvar, ast.Load())
214    self.mode = mode
215  def xfrm_fndef(self, fndef):
216    self.current_carry = 0
217    carry_count = CarryCounter().count(fndef)
218    if carry_count == 0: return fndef
219    self.generic_visit(fndef)
220#   
221#    fndef.body.insert(0, mkCallStmt('CarryDeclare', [self.carryvar, ast.Num(carry_count)]))
222    return fndef
223  def generic_xfrm(self, node):
224    self.current_carry = 0
225    carry_count = CarryCounter().count(node)
226    if carry_count == 0: return node
227    self.generic_visit(node)
228    return node
229  def visit_Call(self, callnode):
230    self.generic_visit(callnode)
231    if is_Advance_Call(callnode):
232      rtn = "BitBlock_advance_%s" % self.mode
233      c = mkCall(rtn, [callnode.args[0], self.carryvar, ast.Num(self.current_carry)])
234      self.current_carry += 1
235      return c
236    elif is_ScanThru_Call(callnode): 
237      rtn = "BitBlock_scanthru_%s" % self.mode
238      c = mkCall(rtn, [callnode.args[0], callnode.args[1], self.carryvar, ast.Num(self.current_carry)])
239      self.current_carry += 1
240      return c
241    else: return callnode
242  def visit_BinOp(self, exprnode):
243    self.generic_visit(exprnode)
244    if isinstance(exprnode.op, ast.Sub):
245      rtn = "BitBlock_sub_%s" % self.mode
246      c = mkCall(rtn, [exprnode.left, exprnode.right, self.carryvar, ast.Num(self.current_carry)])
247      self.current_carry += 1
248      return c
249    elif isinstance(exprnode.op, ast.Add):
250      rtn = "BitBlock_add_%s" % self.mode
251      c = mkCall(rtn, [exprnode.left, exprnode.right, self.carryvar, ast.Num(self.current_carry)])
252      self.current_carry += 1
253      return c
254    else: return exprnode
255  def visit_If(self, ifNode):
256    carry_base = self.current_carry
257    carries = CarryCounter().count(ifNode)
258    self.generic_visit(ifNode)
259    if carries == 0 or self.mode == "co": return ifNode
260    carry_arglist = [self.carryvar, ast.Num(carry_base), ast.Num(carries)]
261    new_test = ast.BoolOp(ast.Or(), [ifNode.test, mkCall('CarryTest', carry_arglist)])
262    new_else_part = [mkCallStmt('CarryDequeueEnqueue', carry_arglist)]
263    return ast.If(new_test, ifNode.body, new_else_part)
264  def visit_While(self, whileNode):
265    carry_base = self.current_carry
266    carries = CarryCounter().count(whileNode)
267    if carries == 0: return whileNode
268    carry_arglist = [self.carryvar, ast.Num(carry_base), ast.Num(carries)]
269    local_carryvar = 'sub'+self.carryvar.id
270    inner_while = CarryIntro(local_carryvar, 'co').generic_xfrm(copy.deepcopy(whileNode))
271    self.generic_visit(whileNode)
272    local_decl = mkCallStmt('CarryDeclare', [ast.Name(local_carryvar, ast.Load()), ast.Num(carries)])
273    inner_while.body.insert(0, local_decl)
274    final_combine = mkCallStmt('CarryCombine', [self.carryvar, ast.Name(local_carryvar, ast.Load()), ast.Num(carry_base), ast.Num(carries)])
275    inner_while.body.append(final_combine)
276    if self.mode == "co": new_test = whileNode.test
277    else: new_test = ast.BoolOp(ast.Or(), [whileNode.test, mkCall('CarryTest', carry_arglist)])
278    else_part = [mkCallStmt('CarryDequeueEnqueue', carry_arglist)]
279    return ast.If(new_test, whileNode.body + [inner_while], else_part)
280
281class StreamStructGen(ast.NodeVisitor):
282  """
283  Given a BitStreamSet subclass, generate the equivalent C struct.
284  >>> obj = ast.parse(r'''
285  ... class S1(BitStreamSet):
286  ...   a1 = 0
287  ...   a2 = 0
288  ...   a3 = 0
289  ...
290  ... class S2(BitStreamSet):
291  ...   x1 = 0
292  ...   x2 = 0
293  ... ''')
294  >>> print StreamStructGen().gen(obj)
295  struct S1 {
296    BitBlock a1;
297    BitBlock a2;
298    BitBlock a3;
299  }
300 
301  struct S2 {
302    BitBlock x1;
303    BitBlock x2;
304  }
305  """
306  def __init__(self):
307    pass
308  def gen(self, tree):
309    self.Ccode=""
310    self.generic_visit(tree)
311    return self.Ccode
312  def visit_ClassDef(self, node):
313#    self.Ccode += "typedef struct {\n"
314    self.Ccode += "struct {\n"
315    for stmt in node.body:
316      if isinstance(stmt, ast.Assign):
317        for v in stmt.targets:
318          if isinstance(v, ast.Name):
319            self.Ccode += "  BitBlock " + v.id + ";\n"
320    self.Ccode += "} " + node.name + ";\n\n"
321 
322class StreamFunctionDecl(ast.NodeVisitor):
323  def __init__(self):
324    pass
325  def gen(self, tree):
326    self.Ccode=""
327    self.generic_visit(tree)
328    return self.Ccode
329  def visit_FunctionDef(self, node):
330    self.Ccode += "static inline void " + node.name + "("
331    pending = ""
332    for arg in node.args.args:
333      if isinstance(arg, ast.Name):
334        self.Ccode += pending + arg.id.upper()[0] + arg.id[1:] + " & " + arg.id
335        pending = ", "
336    self.Ccode += ");\n"
337
338
339
340#  Translate a function
341#
342
343class FunctionXlator(ast.NodeVisitor):
344  def xlat(self, node):
345    self.Ccode=""
346    self.generic_visit(node)
347    return self.Ccode
348  def visit_FunctionDef(self, fndef):
349    AugAssignRemoval().xfrm(fndef)
350    Bitwise_to_SIMD().xfrm(fndef)
351    self.Ccode += BitBlock_header_of_fn(fndef) + " {\n"
352    self.Ccode += BitBlock_decls_of_fn(fndef)
353    CarryIntro().xfrm_fndef(fndef)
354    self.Ccode += Cgen.py2C().gen(fndef.body)
355    self.Ccode += "\n}\n"
356
357def main(infilename, outfile = sys.stdout):
358  t = ast.parse(file(infilename).read())
359  outfile.write(StreamStructGen().gen(t))
360  outfile.write(FunctionXlator().xlat(t))
361
362#
363#
364#  Routines for compatibility with the old compiler/template.
365#  Quick and dirty hacks for now - Dec. 2010.
366#
367def gen_declarations(main_module, main_fn):
368  Cdecls = StreamStructGen().gen(main_module)
369  Cdecls += BitBlock_decls_of_fn(main_fn)
370  Cdecls += Carry_decl_of_fn(main_fn)
371  return Cdecls
372
373def stream_stmts(main_fn):
374  return StreamInitializations().xfrm(main_fn)
375
376def block_stmts(main_fn):
377  AugAssignRemoval().xfrm(main_fn)
378  Bitwise_to_SIMD().xfrm(main_fn)
379  CarryIntro().xfrm_fndef(main_fn)
380  return Cgen.py2C().gen(main_fn.body)
381
382def any_carry_expr(carryvar, carry_count):
383  carry_arglist = [ast.Name(carryvar, ast.Load()), ast.Num(0), ast.Num(carry_count)] 
384  return Cgen.py2C().gen(mkCall('CarryTest', carry_arglist))
385
386if __name__ == "__main__":
387                import doctest
388                doctest.testmod()
389
390
Note: See TracBrowser for help on using the repository browser.