-
Notifications
You must be signed in to change notification settings - Fork 5
/
codegen_c_generic.py
5277 lines (4922 loc) · 243 KB
/
codegen_c_generic.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
########################################################################
#
# Code generation module for the coNCePTuaL language:
# Virtual base class for all C-based backends
#
# By Scott Pakin <[email protected]>
#
# ----------------------------------------------------------------------
#
#
# Copyright (C) 2003, Triad National Security, LLC
# All rights reserved.
#
# Copyright (2003). Triad National Security, LLC. This software
# was produced under U.S. Government contract 89233218CNA000001 for
# Los Alamos National Laboratory (LANL), which is operated by Los
# Alamos National Security, LLC (Triad) for the U.S. Department
# of Energy. The U.S. Government has rights to use, reproduce,
# and distribute this software. NEITHER THE GOVERNMENT NOR TRIAD
# MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR ASSUMES ANY LIABILITY
# FOR THE USE OF THIS SOFTWARE. If software is modified to produce
# derivative works, such modified software should be clearly marked,
# so as not to confuse it with the version available from LANL.
#
# Additionally, redistribution and use in source and binary forms,
# with or without modification, are permitted provided that the
# following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer
# in the documentation and/or other materials provided with the
# distribution.
#
# * Neither the name of Triad National Security, LLC, Los Alamos
# National Laboratory, the U.S. Government, nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY TRIAD AND CONTRIBUTORS "AS IS" AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL TRIAD OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
# OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
# OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
# BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#
########################################################################
import sys
import re
import string
import time
import types
import os
import tempfile
from ncptl_ast import AST
from ncptl_error import NCPTL_Error
from ncptl_variables import Variables
from ncptl_config import ncptl_config
class NCPTL_CodeGen:
thisfile = globals()["__file__"]
trivial_nodes = [
"top_level_stmt_list",
"header_decl_list",
"header_decl",
"simple_stmt",
"source_task",
"target_tasks",
"touching_type",
"byte_count",
"restricted_ident",
"rel_expr",
"rel_primary_expr",
"expr",
"primary_expr",
"item_count"]
#---------------------#
# Exported functions #
# (called from the #
# compiler front end) #
#---------------------#
def __init__(self, options=None):
"Initialize the generic C code generation module."
# Define a suffix for ncptl_int constants. This is critical
# when calling stdarg functions such as ncptl_func_min().
self.ncptl_int_suffix = ncptl_config["NCPTL_INT_SUFFIX"]
# Initialize the mappings from coNCePTuaL operators to C operators.
self.binops = {'op_land' : '&&',
'op_lor' : '||',
'op_eq' : '==',
'op_lt' : '<',
'op_gt' : '>',
'op_le' : '<=',
'op_ge' : '>=',
'op_ne' : '!=',
'op_plus' : '+',
'op_minus' : '-',
'op_or' : '|',
'op_xor' : '^',
'op_mult' : '*',
'op_div' : '/',
'op_and' : '&'}
self.unops = {'op_neg' : '-',
'op_pos' : '+',
'op_not' : '~'}
# Create a placeholder error object. Currently, this isn't used.
self.errmsg = NCPTL_Error()
# Define a set of variables to export to user programs. These
# variables are updated automatically at run time.
self.exported_vars = {}
for name, description in Variables.variables.items():
self.exported_vars["var_%s" % name] = ("ncptl_int", description)
# Define a set of command-line parameters that need to be
# maintained outside of the run-time library
self.base_global_parameters = []
# Define a set of command-line parameters for the backend itself.
self.cmdline_options = []
# Enable a derived backend to indicate that the eventnames[]
# array should be defined in the generated code.
self.define_eventnames = 0
# Set some default compilation parameters.
self.compilation_parameters = {}
exec_prefix = self.get_param("exec_prefix", "")
prefix = self.get_param("prefix", "")
includedir = self.get_param("includedir", "")
includedir = string.replace(includedir, "${exec_prefix}", exec_prefix)
includedir = string.replace(includedir, "${prefix}", prefix)
if includedir:
self.set_param("CPPFLAGS", "prepend", "-I%s" % includedir)
libdir = self.get_param("libdir", "")
libdir = string.replace(libdir, "${exec_prefix}", exec_prefix)
libdir = string.replace(libdir, "${prefix}", prefix)
if libdir:
self.set_param("LDFLAGS", "prepend", "-L%s" % libdir)
self.set_param("LIBS", "prepend", "-lncptl")
# Point each method name in the trivial_nodes list to the
# n_trivial_node method.
for mname in self.trivial_nodes:
setattr(self, "n_" + mname, self.n_trivial_node)
def generate(self, ast, filesource='<stdin>', filetarget="-", sourcecode=None):
"Compile an AST into a list of lines of C code."
self.filesource = filesource # Input file
self.sourcecode = sourcecode # coNCePTuaL source code
self.codestack = [] # Stack of unprocessed metadata
self.global_declarations = [] # Extra global variable declarations
self.backend_declarations = [] # Declarations from BACKEND DECLARES statements
self.init_elements = [] # Code to initialize the element list
self.arbitrary_code = [] # Blocks of arbitrary EV_CODE statements
self.extra_func_decls = [] # Additional functions to declare
self.referenced_vars = {} # Variables to store in the EV_CODE struct
self.referenced_exported_vars = {} # Exported variables that need to be updated
self.stores_restores_vars = 0 # 1=program STORES or RESTORES COUNTERS
self.events_used = {} # Set of EV_* events actually used
self.program_uses_log_file = 0 # 1=program references log data; 0=it doesn't
self.program_uses_touching = 0 # 1=need to touch data somewhere
self.program_uses_randomness = 0 # 2=need to choose and broadcast a seed; 1=choose only; 0=no randomness
self.program_uses_range_lists = 0 # 1=generate helper code for sequences
self.program_uses_string2int = 0 # 1=generate a function to hash a string to an ncptl_int
self.logcolumn = 0 # Current column in the log file
self.nextvarnum = 0 # Next sequential variable number
self.for_each_placeholder = "FOR_EACH_placeholder_%s" % repr(time.time()) # String unlikely to appear in a user program
self.global_parameters = self.base_global_parameters
self.errmsg = NCPTL_Error(filesource)
# Walk the AST in postorder fashion.
self.postorder_traversal(ast)
if len(self.codestack) != 1:
self.errmsg.error_internal("Code stack contains %s" % str(self.codestack[0:-1]))
return self.codestack[0]
def compile_only(self, progfilename, codelines, outfilename, verbose, keepints):
"Compile a list of lines of C code into a .o file."
return self.do_compile(progfilename, codelines, outfilename, verbose, keepints, link=0)
def compile_and_link(self, progfilename, codelines, outfilename, verbose, keepints):
"Compile a list of lines of C code into an executable file."
return self.do_compile(progfilename, codelines, outfilename, verbose, keepints, link=1)
#-----------------------#
# Utility functions #
# (non-code-generating) #
#-----------------------#
def show_help(self):
"Output a help message."
backend_match = re.match(r'(\w+)', self.backend_name)
if not backend_match:
self.errmsg.error_internal('Unable to parse backend_name "%s"' % self.backend_name)
print "Usage: %s [OPTION...]" % backend_match.group(1)
for opt, optdesc in self.cmdline_options:
print " %-31.31s %s" % (opt, optdesc)
print
print "Help options:"
print " --help Show this help message"
def set_param(self, varname, disposition, value):
"""
Specify how a compilation parameter is to be modified.
Modifications are listed in FIFO order so that child
backends can override parent backends.
"""
if not self.compilation_parameters.has_key(varname):
self.compilation_parameters[varname] = []
self.compilation_parameters[varname].append((disposition, value))
def get_param(self, varname, defaultval=""):
"""
Look up variable VARNAME's value in the environment and
return it if it's there. If not, look in the coNCePTuaL
configuration file and, if the value is still not found,
use DEFAULTVAL. Then, modify the value as specified by
COMPILATION_PARAMETERS, which is a list of pairs, the
first element of which is one of \"replace\",
\"prepend\", or \"append\", and the second element of
which is a string that will modify the value as
specified.
"""
# Determine an initial value to use.
if os.environ.has_key(varname):
# Environment variables override all backend modifications.
return os.environ[varname]
elif ncptl_config.has_key(varname):
value = ncptl_config[varname]
else:
value = defaultval
# Modify the value as specified by any derived backends.
if self.compilation_parameters.has_key(varname):
for disposition, selfvalue in self.compilation_parameters[varname]:
if disposition == "prepend":
value = selfvalue + " " + value
elif disposition == "append":
value = value + " " + selfvalue
elif disposition == "replace":
value = selfvalue
# Return the modified string.
return value
def push(self, value, stack=None):
"Push a value onto the code (and metadata) stack or a given stack."
if stack != None:
stack.append(value)
else:
self.codestack.append(value)
def pushmany(self, values, stack=None):
"Push an array of values onto the code (and metadata) stack or a given stack."
if stack != None:
stack.extend(values)
else:
self.codestack.extend(values)
def pop(self, stack=None):
"Pop a value from the code (and metadata) stack or a given stack."
if stack:
value = stack[-1]
del(stack[-1])
else:
value = self.codestack[-1]
del(self.codestack[-1])
return value
def newvar(self, prefix="ivar", suffix=""):
"Return the name of a new variable that we can use internally."
stringnum = ""
self.nextvarnum = self.nextvarnum + 1
num = self.nextvarnum
while num > 0:
quot, rem = divmod(num-1, 26)
stringnum = "abcdefghijklmnopqrstuvwxyz"[rem] + stringnum
num = quot
if suffix:
return prefix + "_" + stringnum + "_" + suffix
else:
return prefix + "_" + stringnum
def push_marker(self, stack=None):
'''
Push a marker symbol onto the stack in preparation for a
call to combine_to_marker.
'''
self.push("#MARKER#", stack)
def combine_to_marker(self, stack=None):
'''
Pop values from the code (and metadata) stack until we
encounter a marker, then push the popped values as an array.
'''
poppedvals = []
while 1:
value = self.pop(stack)
if value == "#MARKER#":
break
else:
poppedvals.append(value)
poppedvals.reverse()
self.push(poppedvals, stack)
def wrap_stack(self, leftcode, rightcode, stack=None):
"Wrap the contents of a stack head within two blocks of code."
if not stack:
stack = self.init_elements
stack[-1][0:0] = leftcode
stack[-1].extend(rightcode)
def invoke_hook(self, hookname, localvars, before=None, after=None,
alternatepy=None, alternate=None, invoke_on=None):
"""
Invoke a hook method if it exists, passing it a dictionary
of the current scope's local variables. The hook function
should return a list of code lines suitable for passing to
self.pushmany. This list will have BEFORE prepended and
AFTER appended. If the HOOKNAME method does not exist,
evaluate ALTERNATEPY. If ALTERNATEPY is not defined,
return ALTERNATE. The hook is invoked on SELF unless
INVOKE_ON is specified in which case that class or object
is used instead.
"""
if not before:
before = []
if not after:
after = []
if not alternate:
alternate = []
if invoke_on:
hookmethod = getattr(invoke_on, hookname, None)
hookargs = (self, localvars)
else:
hookmethod = getattr(self, hookname, None)
hookargs = (localvars,)
if hookmethod:
hookoutput = apply(hookmethod, hookargs)
if hookoutput:
return before + hookoutput + after
else:
return []
elif alternatepy:
return alternatepy(localvars)
else:
return alternate
def do_compile(self, progfilename, codelines, outfilename, verbose=0, keepints=0, link=1):
"""
Compile and optionally link a list of lines of C code into
an object file or executable file.
"""
exe_ext = self.get_param("EXEEXT", "")
if exe_ext:
exe_ext = "." + exe_ext
obj_ext = self.get_param("OBJEXT", "o")
if obj_ext:
obj_ext = "." + obj_ext
intermediates = []
# Determine names for our output and intermediate files.
if progfilename == "<command line>" or progfilename == "<stdin>":
progfilename = "a.out.ncptl"
if outfilename == "-":
outfilename = os.path.splitext(progfilename)[0]
if link:
outfilename = outfilename + exe_ext
else:
outfilename = outfilename + obj_ext
if keepints:
# If we plan to keep the .c file, derive it's name from outfilename.
if (link and exe_ext) or (not link and obj_ext):
infilename = os.path.splitext(outfilename)[0]
else:
infilename = os.path.splitext(outfilename + ".bogus")[0]
infilename = infilename + ".c"
else:
# If we plan to discard the .c file then give it a unique name.
tempfile.tempdir = os.path.split(outfilename)[0]
tempfile.template = re.sub(r'\W+', "_", self.backend_name + "_" + str(os.getpid()))
while 1:
fbase = tempfile.mktemp()
try:
os.stat(fbase + ".c")
if link:
os.stat(fbase + obj_ext)
except:
break
infilename = fbase + ".c"
intermediates.append(infilename)
# Determine the compiler and compiler flags to use.
CC = self.get_param("CC", "cc")
CPPFLAGS = self.get_param("CPPFLAGS")
CFLAGS = self.get_param("CFLAGS")
LDFLAGS = self.get_param("LDFLAGS")
LIBS = self.get_param("LIBS")
# Define a shell command that invokes the C compiler.
if link:
compile_string = ("%s %s %s %s %s %s -o %s" %
(CC, CPPFLAGS, CFLAGS, infilename, LDFLAGS, LIBS, outfilename))
objfilename = os.path.splitext(infilename)[0] + obj_ext
intermediates.append(objfilename)
else:
compile_string = ("%s %s %s -c %s -o %s" %
(CC, CPPFLAGS, CFLAGS, infilename, outfilename))
# Copy CODELINES to a .c file.
try:
infile = open(infilename, "w")
for oneline in codelines:
if string.find(oneline, "ncptl_log_open") != -1:
# Add an extra log-file prologue comment showing
# the ncptl command line.
ncptl_command = []
for arg in sys.argv:
clean_arg = arg
clean_arg = string.replace(clean_arg, "\\", "\\\\")
clean_arg = string.replace(clean_arg, '"', '\\"')
if string.find(clean_arg, " ") != -1:
clean_arg = string.replace(clean_arg, "'", "\\'")
clean_arg = "'%s'" % clean_arg
ncptl_command.append(clean_arg)
ncptl_command = string.join(ncptl_command, " ")
infile.write('ncptl_log_add_comment ("Front-end compilation command line", "%s");\n' % ncptl_command)
# Add an extra log-file prologue comment showing
# COMPILE_STRING.
clean_compile_string = string.replace(compile_string, "\\", "\\\\")
clean_compile_string = string.replace(clean_compile_string, '"', '\\"')
infile.write('ncptl_log_add_comment ("Back-end compilation command line", "%s");\n' % clean_compile_string)
infile.write("%s\n" % oneline)
infile.close()
except IOError, (errno, strerror):
self.errmsg.error_fatal("Unable to produce %s (%s)" % (infilename, strerror),
filename=self.backend_name)
# Indent the .c file for aesthetic purposes.
indentcmd = self.get_param("INDENT", "no")
if indentcmd != "no" and keepints:
os.environ["VERSION_CONTROL"] = "simple"
os.environ["SIMPLE_BACKUP_SUFFIX"] = ".BAK"
indent_string = "%s %s" % (indentcmd, infilename)
if verbose:
sys.stderr.write("%s\n" % indent_string)
if os.system(indent_string) != 0:
self.errmsg.warning("The indentation command exited abnormally; continuing regardless")
try:
os.remove(infilename + ".BAK")
except OSError:
pass
# Compile and optionally link the .c file, then optionally
# delete it. If we're linking then also optionally delete the
# .o file.
if verbose:
sys.stderr.write("%s\n" % compile_string)
if os.system(compile_string) != 0:
self.errmsg.error_fatal("The C compiler exited abnormally; aborting coNCePTuaL")
for deletable in intermediates:
if os.path.isfile(deletable):
if keepints:
if verbose:
sys.stderr.write("# Not deleting %s ...\n" % deletable)
else:
if verbose:
sys.stderr.write("# Deleting %s ...\n" % deletable)
try:
os.unlink(deletable)
except OSError, errmsg:
sys.stderr.write("# --> %s\n" % errmsg)
if verbose:
sys.stderr.write("# Files generated: %s\n" % outfilename)
return outfilename
def postorder_traversal(self, node):
"Perform a postorder traversal of an abstract syntax tree."
for kid in node.kids:
self.postorder_traversal(kid)
try:
func = getattr(self, "n_" + node.type)
func(node)
except AttributeError:
self.errmsg.error_internal('I don\'t know how to process nodes of type "%s"' % node.type)
def tasks_to_text(self, task_tuple):
"Return a pretty-printed version of a task tuple."
if task_tuple[0] == "task_expr":
return "TASK %s" % task_tuple[1]
elif task_tuple[0] == "task_restricted":
return "TASKS %s SUCH THAT %s" % (task_tuple[1], task_tuple[2])
elif task_tuple[0] == "all_others":
return "ALL OTHER TASKS"
elif task_tuple[0] == "task_all":
if task_tuple[1] == None:
return "ALL TASKS"
else:
return "ALL TASKS %s" % task_tuple[1]
elif task_tuple[0] == "let_task":
return "TASK GROUP %s" % task_tuple[1]
else:
self.errmsg.error_internal('I don\'t know how to process tasks of type "%s"' % task_tuple[0])
def clean_comments(self, comment_str):
'Replace "/*" with "/_*" and "*/" with "*_/" so as not to confuse C.'
return string.replace(string.replace(comment_str, "/*", "/_*"), "*/", "*_/")
def unquote_string(self, conc_str):
'''
Replace "\\<char>" with "<char>" in a given string to convert a
string specified in a coNCePTuaL program to a C string.
'''
c_chars = []
orig_num_chars = len(conc_str)
c = 1
while c < orig_num_chars-1:
if conc_str[c] == '\\':
c = c + 1
nextchar = conc_str[c]
if nextchar == 'n':
c_chars.append("\n")
else:
c_chars.append(nextchar)
else:
c_chars.append(conc_str[c])
c = c + 1
return string.join(c_chars, "")
def range_list_wrapper(self, rangelist):
"""
Return header and trailer code that repeats a statement for
each element in a list of sets.
"""
# Acquire our parameters and preprocess the range list.
self.program_uses_range_lists = 1
orig_rangelist = rangelist
rangelist = []
for orig_range in orig_rangelist:
# Canonicalize each entry into a tuple of {initial
# value(s), final value} to avoid special cases later on.
# Ordinary list
if orig_range[1] == None:
for singleton in orig_range[0]:
rangelist.append(([singleton], singleton))
else:
rangelist.append(orig_range)
# Begin a new scope.
wrapper_code = []
self.push_marker(wrapper_code)
self.push("{", wrapper_code)
# Figure out the pattern used in each range in RANGELIST and
# convert each range to an element of a C struct.
ni_1 = "1" + self.ncptl_int_suffix
self.code_declare_var("LOOPBOUNDS",
name="loopbounds[%d]" % len(rangelist),
comment="List of range descriptions",
stack=wrapper_code)
self.code_declare_var(name="rangenum",
comment="Current offset into loopbounds[]",
stack=wrapper_code)
self.code_declare_var(name="initial_vals",
arraysize=max(map(lambda r: len(r[0]),
rangelist)),
comment="Cache of the initial, enumerated values",
stack=wrapper_code)
self.code_declare_var(name="final_val",
comment="Cache of the final value",
stack=wrapper_code)
loopindex = 0
for enumvals, finalval in rangelist:
prefix = "loopbounds[%d]" % loopindex
self.push("", wrapper_code)
loopindex = loopindex + 1
self.push(" /* Write range %d's loop bounds, \"next\" function, and termination function to %s. */" % (loopindex-1, prefix), wrapper_code)
if finalval == "list_comp":
# List comprehension
self.push("%s.list_comp = %s;" % (prefix, enumvals), wrapper_code)
enumvals = ["0" + self.ncptl_int_suffix]
finalval = "ncptl_queue_length(%s.list_comp)-%s" % (prefix, ni_1)
else:
# Not a list comprehension
self.push("%s.list_comp = NULL;" % prefix, wrapper_code)
for i in range(0, len(enumvals)):
self.push("initial_vals[%d] = %s;" % (i, enumvals[i]),
wrapper_code)
self.pushmany([
"final_val = %s;" % finalval,
"%s.integral = 1;" % prefix,
"%s.u.i.startval = initial_vals[0];" % prefix,
"%s.u.i.endval = final_val;" % prefix],
wrapper_code)
if len(enumvals) == 1:
if enumvals[0] == finalval:
# Constant value: Generate a one-trip loop.
self.pushmany([
"%s.comparator = CONC_LEQ;" % prefix,
"%s.increment = CONC_ADD;" % prefix,
"%s.u.i.incval = %s;" % (prefix, ni_1)],
wrapper_code)
else:
# Two element range: Increment is second minus first.
self.pushmany([
"%s.comparator = initial_vals[0]<=final_val ? CONC_LEQ : CONC_GEQ;" %
prefix,
"%s.increment = CONC_ADD;" % prefix,
"%s.u.i.incval = initial_vals[0]<=final_val ? %s : -%s;" %
(prefix, ni_1, ni_1)],
wrapper_code)
elif len(enumvals) == 2:
# Two initial elements dictate an arithmetic progression.
self.pushmany([
" /* Arithmetic progression */",
"%s.comparator = initial_vals[0]<=initial_vals[1] ? CONC_LEQ : CONC_GEQ;" %
prefix,
"%s.increment = CONC_ADD;" % prefix,
"%s.u.i.incval = initial_vals[1]-initial_vals[0];" % prefix,
"if (!%s.u.i.incval)" % prefix,
"%s.u.i.incval = %s; /* Handle {x,x,x,...,x} case (constant value) */" %
(prefix, ni_1)],
wrapper_code)
else:
# Range containing a few initial elements: Find the pattern.
# First, look for an arithmetic progression.
conditionals = []
for e in range(len(enumvals)-2):
self.push("initial_vals[%d]-initial_vals[%d]==initial_vals[%d]-initial_vals[%d]" %
(e+1, e, e+2, e+1),
conditionals)
self.pushmany([
"if (%s) {" % string.join(conditionals, " && "),
" /* Arithmetic progression */",
"%s.comparator = initial_vals[0]<=initial_vals[1] ? CONC_LEQ : CONC_GEQ;" %
prefix,
"%s.increment = CONC_ADD;" % prefix,
"%s.u.i.incval = initial_vals[1]-initial_vals[0];" % prefix,
"if (!%s.u.i.incval)" % prefix,
"%s.u.i.incval = %s; /* Handle {x,x,x,...,x} case (constant value) */" %
(prefix, ni_1),
"}"],
wrapper_code)
# Second, look for an increasing geometric progression.
conditionals = []
for e in range(len(enumvals)-1):
self.push("initial_vals[%d]" % e, conditionals)
self.push("initial_vals[0]<initial_vals[1]", conditionals)
for e in range(len(enumvals)-1):
self.push("initial_vals[%d]*(initial_vals[%d]/initial_vals[%d])==initial_vals[%d]" %
(e, e+1, e, e+1),
conditionals)
for e in range(len(enumvals)-2):
self.push("initial_vals[%d]/initial_vals[%d]==initial_vals[%d]/initial_vals[%d]" %
(e+1, e, e+2, e+1),
conditionals)
self.pushmany([
"else",
"if (%s) {" % string.join(conditionals, " && "),
" /* Geometric progression (increasing, integral multiplier) */",
"%s.comparator = CONC_LEQ;" % prefix,
"%s.increment = CONC_MULT;" % prefix,
"%s.u.i.incval = initial_vals[1]/initial_vals[0];" % prefix,
"}"],
wrapper_code)
# Third, look for a decreasing geometric progression.
conditionals = []
for e in range(1, len(enumvals)):
self.push("initial_vals[%d]" % e, conditionals)
self.push("initial_vals[0]>initial_vals[1]", conditionals)
for e in range(len(enumvals)-1):
self.push("initial_vals[%d]*(initial_vals[%d]/initial_vals[%d])==initial_vals[%d]" %
(e+1, e, e+1, e),
conditionals)
for e in range(len(enumvals)-2):
self.push("initial_vals[%d]/initial_vals[%d]==initial_vals[%d]/initial_vals[%d]" %
(e, e+1, e+1, e+2),
conditionals)
self.pushmany([
"else",
"if (%s) {" % string.join(conditionals, " && "),
" /* Geometric progression (decreasing, integral multiplier) */",
"%s.comparator = CONC_GEQ;" % prefix,
"%s.increment = CONC_DIV;" % prefix,
"%s.u.i.incval = initial_vals[0]/initial_vals[1];" % prefix,
"}"],
wrapper_code)
# Fourth, look for a geometric progression that
# increases by a non-integral multiplier.
conditionals = []
for e in range(len(enumvals)-1):
self.push("initial_vals[%d]" % e, conditionals)
self.pushmany([
"else",
"if (%s) {" % string.join(conditionals, " && ")],
wrapper_code)
self.code_declare_var(type="double", name="initial_vals_d",
arraysize=len(enumvals),
comment="Cache of the initial, enumerated values, but in floating-point context",
stack=wrapper_code)
self.code_declare_var(type="double", name="avg_factor",
comment="Average multiplier for terms in the sequence",
stack=wrapper_code)
for i in range(0, len(enumvals)):
self.push("initial_vals_d[%d] = %s;" %
(i, self.code_make_expression_fp(enumvals[i],
floating_context=1)),
wrapper_code)
self.pushmany([
"avg_factor = (%s) / %d.0;" %
(string.join(map(lambda e: "initial_vals_d[%d]/initial_vals_d[%d]" % (e+1, e),
range(0, len(enumvals)-1)),
" + "),
len(enumvals)-1),
"if (%s) {" %
string.join(map(lambda e: "CONC_DBL2INT(initial_vals_d[%d]*avg_factor)==initial_vals[%d]" %
(e, e+1),
range(0, len(enumvals)-1)),
" && "),
" /* Geometric progression (decreasing or non-integral multiplier) */",
"%s.comparator = initial_vals[0]<initial_vals[1] ? CONC_LEQ : CONC_GEQ;" % prefix,
"%s.integral = 0;" % prefix,
"%s.increment = CONC_MULT;" % prefix,
"%s.u.d.startval = initial_vals_d[0];" % prefix,
"%s.u.d.endval = %s;" %
(prefix, self.code_make_expression_fp(finalval, floating_context=1)),
"%s.u.d.incval = avg_factor;" % prefix,
"}"],
wrapper_code)
# Finally, issue an error message. This code is
# repeated because of the extra level of nesting
# required for the floating-point geometric
# progression case.
no_pattern_error = 'ncptl_fatal ("Unable to find an arithmetic or geometric pattern to {%s..., %s}", %s);' % \
('%" NICS ", ' * len(enumvals), '%" NICS "',
string.join(map(lambda e: "initial_vals[%d]" % e,
range(0, len(enumvals))),
", ") + ", final_val")
self.pushmany([
"else",
no_pattern_error,
"}",
"else",
no_pattern_error],
wrapper_code)
# For each range in LOOPBOUNDS iterate over each element
# within that range.
self.pushmany([
"",
" /* Now that we've defined all of our ranges we iterate over each range",
" * and each element within each range. */",
"for (rangenum=0%s; rangenum<%d; rangenum++) {" % (self.ncptl_int_suffix, len(rangelist))],
wrapper_code)
self.code_declare_var("LOOPBOUNDS *", name="thisrange",
rhs="&loopbounds[rangenum]",
comment="Current range",
stack=wrapper_code)
self.pushmany([
"if (conc_seq_nonempty (thisrange))",
"for (conc_seq_init (thisrange);",
"conc_seq_continue (thisrange);",
"conc_seq_next (thisrange)) {"],
wrapper_code)
self.combine_to_marker(wrapper_code)
# Generate cleanup code.
cleanup_code = ["}", "}"]
list_comp_indices = []
for i in range(len(rangelist)):
if rangelist[i][1] == "list_comp":
list_comp_indices.append(i)
if list_comp_indices != []:
self.push("", cleanup_code)
self.push(" /* Free the memory allocated for storing list-comprehension values. */", cleanup_code)
for idx in list_comp_indices:
self.pushmany(["ncptl_queue_empty(loopbounds[%d].list_comp);" % idx,
"ncptl_free(loopbounds[%d].list_comp);" % idx],
stack=cleanup_code)
self.push("}", cleanup_code)
return (wrapper_code[0], cleanup_code)
def search_stack_for_task_group(self, varname):
"Walk the code stack for the definition of a task-group variable."
groupname = re.sub(r'^var_', "var_GROUP ", varname)
for pos in range(len(self.codestack)):
try:
stackvar, stackvalue = self.codestack[-pos]
if stackvar == groupname:
return stackvalue
except:
pass
self.errmsg.error_internal("Failed to find a definition of %s" % varname)
def task_group_to_task(self, taskgroup):
"Convert a task-group tuple to a task tuple plus a possible variable rename."
groupname, tasktype, varname, taskexpr = taskgroup[1:5]
renamefrom = None
renameto = None
if taskexpr and varname and varname[:4] == "var_":
if groupname != varname and re.search(r'\b' + groupname + r'\b', taskexpr):
# The group name already appears in the task
# expression. We'll need to rename it later.
renamefrom = groupname
renameto = self.newvar(suffix=varname[4:])
taskexpr = re.sub(r'\b' + renamefrom + r'\b', renameto, taskexpr)
tasktuple = [tasktype, groupname,
re.sub(r'\b' + varname + r'\b', groupname, taskexpr)] + list(taskgroup[5:])
else:
tasktuple = taskgroup[2:]
return [tuple(tasktuple), renamefrom, renameto]
def find_child_ident_nodes(self, node):
"Return a list of all ident nodes beneath a given node."
if node.type == "ident":
return [node]
identlist = []
for kid in node.kids:
identlist.extend(self.find_child_ident_nodes(kid))
return identlist
def find_variables_defined(self, node):
"Return a list of all variables defined by a given node."
var_nodes = self.find_child_ident_nodes(node)
try:
# If we have a reference to a list-comprehension
# expression node, pretend that it's a child of ours.
var_nodes.extend(self.find_child_ident_nodes(node.sem["lc_expr_node"]))
except KeyError:
pass
defined_nodes = filter(lambda n: n.sem.has_key("definition"), var_nodes)
return map(lambda v: "var_" + v.attr, defined_nodes)
def find_variables_used(self, node):
"Return a list of all variables used but not defined by a given node and not predefined."
variables_used = {}
var_nodes = self.find_child_ident_nodes(node)
try:
# If we have a reference to a list-comprehension
# expression node, pretend that it's a child of ours.
var_nodes.extend(self.find_child_ident_nodes(node.sem["lc_expr_node"]))
except KeyError:
pass
defined_nodes = filter(lambda n: n.sem.has_key("definition"), var_nodes)
for used_node in var_nodes:
varname = used_node.attr
try:
varnode = used_node.sem["varscope"][varname]
if varnode not in defined_nodes:
variables_used["var_" + varname] = 1
except KeyError:
# Predefined variable
pass
variables_used = variables_used.keys()
return variables_used
def replace_list_comp_placeholders(self, expr):
"Replace the first instance of placeholder text in extra_func_decls[]."
placeholder_re = re.compile(re.escape(self.for_each_placeholder))
for declnum in range(len(self.extra_func_decls)-1, -1, -1):
decl = self.extra_func_decls[declnum]
totalchanges = 0
for i in range(len(decl)):
decl[i], numchanges = placeholder_re.subn(expr, decl[i])
totalchanges += numchanges
if totalchanges > 0:
self.extra_func_decls[declnum] = decl
return
self.errmsg.error_internal("Failed to replace %s with %s" % (repr(self.for_each_placeholder), repr(expr)))
#------------------------------#
# Utility functions #
# (code-generating, generic C) #
#------------------------------#
def code_begin_source_scope(self, source_task, stack=None):
"Begin a new scope if source_task includes our task's rank."
# Convert task groups to ordinary tasks.
if source_task[0] == "let_task":
source_task, renamefrom, renameto = self.task_group_to_task(source_task)
if renamefrom != None:
self.push("{", stack)
self.code_declare_var(name=renameto, rhs=renamefrom, stack=stack)
# Determine if the calling rank is a source task.
if source_task[0] == "task_all":
self.push("{ /* %s */" % self.tasks_to_text(source_task), stack)
if source_task[1]:
self.push("ncptl_int %s = virtrank;" % source_task[1], stack)
elif source_task[0] == "task_expr":
self.push("if ((%s) == virtrank) { /* %s */" %
(source_task[1], self.tasks_to_text(source_task)),
stack)
elif source_task[0] == "task_restricted":
self.pushmany([
"{",
"ncptl_int %s = virtrank;" % source_task[1],
"if (%s) { /* %s */" % (source_task[2], self.tasks_to_text(source_task))],
stack)
else:
self.errmsg.error_internal('unknown source task type "%s"' % source_task[0])
self.push(" /* The current coNCePTuaL statement applies to our task. */", stack)
def code_end_source_scope(self, source_task, stack=None):
"End the scope(s) created by code_begin_source_scope."
if source_task[0] == "let_task":
source_task, renamefrom, renameto = self.task_group_to_task(source_task)
else:
renamefrom = None
if source_task[0] == "task_all":
self.push("}", stack)
elif source_task[0] == "task_expr":
self.push("}", stack)
elif source_task[0] == "task_restricted":
self.push("}", stack)
self.push("}", stack)
elif source_task[0] == "let_task":
self.code_end_source_scope(source_task[2:], stack)
else:
self.errmsg.error_internal('unknown source task type "%s"' % source_task[0])
if renamefrom != None:
self.push("}", stack)
def code_begin_target_loop(self, source_task, target_tasks, stack=None):
"Loop over all tasks, seeing if our task receives from each in turn."
# Convert source task groups to ordinary tasks.
if source_task[0] == "let_task":
source_task, srenamefrom, srenameto = self.task_group_to_task(source_task)
if srenamefrom != None:
self.push("{", stack)
self.code_declare_var(name=srenameto, rhs=srenamefrom, stack=stack)
# Iterate over all potential source tasks.
sourcevar = self.newvar(suffix="task")
if source_task[0] == "task_all":
if source_task[1]:
rankvar = source_task[1]
else:
rankvar = self.newvar(suffix="loop")
self.pushmany([
"{",
"ncptl_int %s;" % rankvar,
" /* Loop over all tasks to see which will send to us. */",
"for (%s=0; %s<var_num_tasks; %s++) {" % (rankvar, rankvar, rankvar)],
stack)
elif source_task[0] == "task_expr":
# Caveat: rankvar is being assigned an expression, not a variable.
rankvar = source_task[1]
self.push("if ((%s)>=0 && (%s)<var_num_tasks) {" % (rankvar, rankvar),
stack)
elif source_task[0] == "task_restricted":
rankvar = source_task[1]
self.pushmany([
"{",
"ncptl_int %s;" % rankvar,
" /* Loop over all tasks to see which will send to us. */",
"for (%s=0; %s<var_num_tasks; %s++)" % (rankvar, rankvar, rankvar),
"if (%s) {" % source_task[2]],
stack)
else:
self.errmsg.error_internal('unknown source task type "%s"' % source_task[0])
self.pushmany([
" /* %s now represents one of the tasks that will send to us. */" % rankvar,
"ncptl_int %s = %s;" % (sourcevar, rankvar)],
stack)
# Convert target task groups to ordinary tasks.
if target_tasks[0] == "let_task":
target_tasks, trenamefrom, trenameto = self.task_group_to_task(target_tasks)
if trenamefrom != None:
self.code_declare_var(name=trenameto, rhs=trenamefrom, stack=stack)
# Create a scope for the target task(s).
if target_tasks[0] == "all_others":
self.push("if (virtrank != %s) {" % rankvar, stack)