Debian Codegraph @

rpython/translator/c/genc.py

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 from __future__ import print_function
2
3 import contextlib
4 import py
5 import sys, os
6 from rpython.rlib import exports
7 from rpython.rtyper.lltypesystem.lltype import getfunctionptr
8 from rpython.rtyper.lltypesystem import lltype
9 from rpython.tool import runsubprocess
10 from rpython.tool.nullpath import NullPyPathLocal
11 from rpython.tool.udir import udir
12 from rpython.translator.c import gc
13 from rpython.translator.c.database import LowLevelDatabase
14 from rpython.translator.c.extfunc import pre_include_code_lines
15 from rpython.translator.c.support import log
16 from rpython.translator.gensupp import uniquemodulename, NameManager
17 from rpython.translator.tool.cbuild import ExternalCompilationInfo
18
19
20 _CYGWIN = sys.platform == 'cygwin'
21
22 _CPYTHON_RE = py.std.re.compile('^Python 2.[567]')
23
24 def get_recent_cpython_executable():
25
26 if sys.platform == 'win32':
27 python = sys.executable.replace('\\', '/')
28 else:
29 python = sys.executable
30 # Is there a command 'python' that runs python 2.5-2.7?
31 # If there is, then we can use it instead of sys.executable
32 returncode, stdout, stderr = runsubprocess.run_subprocess(
33 "python", "-V")
34 if _CPYTHON_RE.match(stdout) or _CPYTHON_RE.match(stderr):
35 python = 'python'
36 return python
37
38
39 class CCompilerDriver(object):
40 def __init__(self, platform, cfiles, eci, outputfilename=None,
41 profbased=False):
42 # XXX config might contain additional link and compile options.
43 # We need to fish for it somehow.
44 self.platform = platform
45 self.cfiles = cfiles
46 self.eci = eci
47 self.outputfilename = outputfilename
48 # self.profbased = profbased
49
50 def _build(self, eci=ExternalCompilationInfo(), shared=False):
51 outputfilename = self.outputfilename
52 if shared:
53 if outputfilename:
54 basename = outputfilename
55 else:
56 basename = self.cfiles[0].purebasename
57 outputfilename = 'lib' + basename
58 return self.platform.compile(self.cfiles, self.eci.merge(eci),
59 outputfilename=outputfilename,
60 standalone=not shared)
61
62 class CBuilder(object):
63 c_source_filename = None
64 _compiled = False
65 modulename = None
66 split = False
67
68 def __init__(self, translator, entrypoint, config, gcpolicy=None,
69 gchooks=None, secondary_entrypoints=()):
70 self.translator = translator
71 self.entrypoint = entrypoint
72 self.entrypoint_name = getattr(self.entrypoint, 'func_name', None)
73 self.originalentrypoint = entrypoint
74 self.config = config
75 self.gcpolicy = gcpolicy # for tests only, e.g. rpython/memory/
76 self.gchooks = gchooks
77 self.eci = self.get_eci()
78 self.secondary_entrypoints = secondary_entrypoints
79
80 def get_eci(self):
81 pypy_include_dir = py.path.local(__file__).join('..')
82 include_dirs = [pypy_include_dir]
83 if self.config.translation.reverse_debugger:
84 include_dirs.append(pypy_include_dir.join('..', 'revdb'))
85 return ExternalCompilationInfo(include_dirs=include_dirs)
86
87 def build_database(self):
88 translator = self.translator
89
90 gcpolicyclass = self.get_gcpolicyclass()
91
92 exctransformer = translator.getexceptiontransformer()
93 db = LowLevelDatabase(translator, standalone=self.standalone,
94 gcpolicyclass=gcpolicyclass,
95 gchooks=self.gchooks,
96 exctransformer=exctransformer,
97 thread_enabled=self.config.translation.thread,
98 sandbox=self.config.translation.sandbox,
99 split_gc_address_space=
100 self.config.translation.split_gc_address_space,
101 reverse_debugger=
102 self.config.translation.reverse_debugger)
103 self.db = db
104
105 # give the gc a chance to register interest in the start-up functions it
106 # need (we call this for its side-effects of db.get())
107 list(db.gcpolicy.gc_startup_code())
108
109 # build entrypoint and eventually other things to expose
110 pf = self.getentrypointptr()
111 if isinstance(pf, list):
112 for one_pf in pf:
113 db.get(one_pf)
114 self.c_entrypoint_name = None
115 else:
116 pfname = db.get(pf)
117
118 for func, _ in self.secondary_entrypoints:
119 bk = translator.annotator.bookkeeper
120 db.get(getfunctionptr(bk.getdesc(func).getuniquegraph()))
121
122 self.c_entrypoint_name = pfname
123
124 if self.config.translation.reverse_debugger:
125 from rpython.translator.revdb import gencsupp
126 gencsupp.prepare_database(db)
127
128 for obj in exports.EXPORTS_obj2name.keys():
129 db.getcontainernode(obj)
130 exports.clear()
131
132 for ll_func in db.translator._call_at_startup:
133 db.get(ll_func)
134
135 db.complete()
136
137 self.collect_compilation_info(db)
138 return db
139
140 have___thread = None
141
142 def merge_eci(self, *ecis):
143 self.eci = self.eci.merge(*ecis)
144
145 def collect_compilation_info(self, db):
146 # we need a concrete gcpolicy to do this
147 self.merge_eci(db.gcpolicy.compilation_info())
148
149 all = []
150 for node in self.db.globalcontainers():
151 eci = node.compilation_info()
152 if eci:
153 all.append(eci)
154 for node in self.db.getstructdeflist():
155 try:
156 all.append(node.STRUCT._hints['eci'])
157 except (AttributeError, KeyError):
158 pass
159 self.merge_eci(*all)
160
161 def get_gcpolicyclass(self):
162 if self.gcpolicy is None:
163 name = self.config.translation.gctransformer
164 if name == "framework":
165 name = "%s+%s" % (name, self.config.translation.gcrootfinder)
166 return gc.name_to_gcpolicy[name]
167 return self.gcpolicy
168
169 # use generate_source(defines=DEBUG_DEFINES) to force the #definition
170 # of the macros that enable debugging assertions
171 DEBUG_DEFINES = {'RPY_ASSERT': 1,
172 'RPY_LL_ASSERT': 1,
173 'RPY_REVDB_PRINT_ALL': 1}
174
175 def generate_source(self, db=None, defines={}, exe_name=None):
176 assert self.c_source_filename is None
177 if db is None:
178 db = self.build_database()
179 pf = self.getentrypointptr()
180 if self.modulename is None:
181 self.modulename = uniquemodulename('testing')
182 modulename = self.modulename
183 targetdir = udir.ensure(modulename, dir=1)
184 if self.config.translation.dont_write_c_files:
185 targetdir = NullPyPathLocal(targetdir)
186
187 self.targetdir = targetdir
188 defines = defines.copy()
189 if self.config.translation.countmallocs:
190 defines['COUNT_OP_MALLOCS'] = 1
191 if self.config.translation.countfieldaccess:
192 defines['RPY_COUNT_FIELDACCESS'] = 1
193 if self.config.translation.sandbox:
194 defines['RPY_SANDBOXED'] = 1
195 if self.config.translation.reverse_debugger:
196 defines['RPY_REVERSE_DEBUGGER'] = 1
197 if self.config.translation.rpython_translate:
198 defines['RPY_TRANSLATE'] = 1
199 if CBuilder.have___thread is None:
200 CBuilder.have___thread = self.translator.platform.check___thread()
201 if not self.standalone:
202 assert not self.config.translation.instrument
203 else:
204 defines['PYPY_STANDALONE'] = db.get(pf)
205 if self.config.translation.instrument:
206 defines['PYPY_INSTRUMENT'] = 1
207 if CBuilder.have___thread:
208 if not self.config.translation.no__thread:
209 defines['USE___THREAD'] = 1
210 if self.config.translation.shared:
211 defines['PYPY_MAIN_FUNCTION'] = "pypy_main_startup"
212 self.eci, cfile, extra, headers_to_precompile = \
213 gen_source(db, modulename, targetdir,
214 self.eci, defines=defines, split=self.split)
215 self.c_source_filename = py.path.local(cfile)
216 self.extrafiles = self.eventually_copy(extra)
217 self.gen_makefile(targetdir, exe_name=exe_name,
218 headers_to_precompile=headers_to_precompile)
219 return cfile
220
221 def eventually_copy(self, cfiles):
222 extrafiles = []
223 for fn in cfiles:
224 fn = py.path.local(fn)
225 if not fn.relto(udir):
226 newname = self.targetdir.join(fn.basename)
227 if newname.check(exists=True):
228 raise ValueError(
229 "Cannot have two different separate_module_sources "
230 "with the same basename, please rename one: %s" % fn.basename)
231 fn.copy(newname)
232 fn = newname
233 extrafiles.append(fn)
234 return extrafiles
235
236
237 class CStandaloneBuilder(CBuilder):
238 standalone = True
239 split = True
240 executable_name = None
241 shared_library_name = None
242 _entrypoint_wrapper = None
243 make_entrypoint_wrapper = True # for tests
244
245
246 def getentrypointptr(self):
247 # XXX check that the entrypoint has the correct
248 # signature: list-of-strings -> int
249 if not self.make_entrypoint_wrapper:
250 bk = self.translator.annotator.bookkeeper
251 return getfunctionptr(bk.getdesc(self.entrypoint).getuniquegraph())
252 if self._entrypoint_wrapper is not None:
253 return self._entrypoint_wrapper
254 #
255 from rpython.annotator import model as annmodel
256 from rpython.rtyper.lltypesystem import rffi
257 from rpython.rtyper.annlowlevel import MixLevelHelperAnnotator
258 from rpython.rtyper.llannotation import lltype_to_annotation
259 entrypoint = self.entrypoint
260 #
261 def entrypoint_wrapper(argc, argv):
262 """This is a wrapper that takes "Signed argc" and "char **argv"
263 like the C main function, and puts them inside an RPython list
264 of strings before invoking the real entrypoint() function.
265 """
266 list = [""] * argc
267 i = 0
268 while i < argc:
269 list[i] = rffi.charp2str(argv[i])
270 i += 1
271 return entrypoint(list)
272 #
273 mix = MixLevelHelperAnnotator(self.translator.rtyper)
274 args_s = [annmodel.SomeInteger(),
275 lltype_to_annotation(rffi.CCHARPP)]
276 s_result = annmodel.SomeInteger()
277 graph = mix.getgraph(entrypoint_wrapper, args_s, s_result)
278 mix.finish()
279 res = getfunctionptr(graph)
280 self._entrypoint_wrapper = res
281 return res
282
283 def cmdexec(self, args='', env=None, err=False, expect_crash=False, exe=None):
284 assert self._compiled
285 if sys.platform == 'win32':
286 #Prevent opening a dialog box
287 import ctypes
288 winapi = ctypes.windll.kernel32
289 SetErrorMode = winapi.SetErrorMode
290 SetErrorMode.argtypes=[ctypes.c_int]
291
292 SEM_FAILCRITICALERRORS = 1
293 SEM_NOGPFAULTERRORBOX = 2
294 SEM_NOOPENFILEERRORBOX = 0x8000
295 flags = SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX \
296 | SEM_NOOPENFILEERRORBOX
297 #Since there is no GetErrorMode, do a double Set
298 old_mode = SetErrorMode(flags)
299 SetErrorMode(old_mode | flags)
300 if env is None:
301 envrepr = ''
302 else:
303 envrepr = ' [env=%r]' % (env,)
304 env.update(os.environ)
305 if exe is None:
306 exe = self.executable_name
307 log.cmdexec('%s %s%s' % (exe, args, envrepr))
308 res = self.translator.platform.execute(exe, args, env=env)
309 if sys.platform == 'win32':
310 SetErrorMode(old_mode)
311 if res.returncode != 0:
312 if expect_crash:
313 if type(expect_crash) is int and expect_crash != res.returncode:
314 raise Exception("Returned %d, but expected %d" % (
315 res.returncode, expect_crash))
316 return res.out, res.err
317 print(res.err, file=sys.stderr)
318 raise Exception("Returned %d" % (res.returncode,))
319 if expect_crash:
320 raise Exception("Program did not crash!")
321 if err:
322 return res.out, res.err
323 return res.out
324
325 def compile(self, exe_name=None):
326 assert self.c_source_filename
327 assert not self._compiled
328
329 shared = self.config.translation.shared
330
331 extra_opts = []
332 if self.config.translation.profopt:
333 extra_opts += ["profopt"]
334 if self.config.translation.make_jobs != 1:
335 extra_opts += ['-j', str(self.config.translation.make_jobs)]
336 if self.config.translation.lldebug:
337 extra_opts += ["lldebug"]
338 elif self.config.translation.lldebug0:
339 extra_opts += ["lldebug0"]
340 self.translator.platform.execute_makefile(self.targetdir,
341 extra_opts)
342 self._compiled = True
343 return self.executable_name
344
345 def gen_makefile(self, targetdir, exe_name=None, headers_to_precompile=[]):
346 module_files = self.eventually_copy(self.eci.separate_module_files)
347 self.eci.separate_module_files = []
348 self.eci.compile_extra += ('-DPYPY_MAKEFILE',)
349 cfiles = [self.c_source_filename] + self.extrafiles + list(module_files)
350 if exe_name is not None:
351 exe_name = targetdir.join(exe_name)
352 mk = self.translator.platform.gen_makefile(
353 cfiles, self.eci,
354 path=targetdir, exe_name=exe_name,
355 headers_to_precompile=headers_to_precompile,
356 no_precompile_cfiles = module_files,
357 shared=self.config.translation.shared,
358 profopt = self.config.translation.profopt,
359 config=self.config)
360
361 if exe_name is None:
362 short = targetdir.basename
363 exe_name = targetdir.join(short)
364
365 rules = [
366 ('debug', '', '$(MAKE) CFLAGS="$(DEBUGFLAGS) -DRPY_ASSERT" debug_target'),
367 ('debug_exc', '', '$(MAKE) CFLAGS="$(DEBUGFLAGS) -DRPY_ASSERT -DDO_LOG_EXC" debug_target'),
368 ('debug_mem', '', '$(MAKE) CFLAGS="$(DEBUGFLAGS) -DRPY_ASSERT -DPYPY_USE_TRIVIAL_MALLOC" debug_target'),
369 ('llsafer', '', '$(MAKE) CFLAGS="-O2 -DRPY_LL_ASSERT" $(DEFAULT_TARGET)'),
370 ('lldebug', '', '$(MAKE) CFLAGS="$(DEBUGFLAGS) -DRPY_ASSERT -DRPY_LL_ASSERT" debug_target'),
371 ('profile', '', '$(MAKE) CFLAGS="-g -O1 -pg $(CFLAGS) -fno-omit-frame-pointer" LDFLAGS="-pg $(LDFLAGS)" $(DEFAULT_TARGET)'),
372 ]
373
374 # added a new target for profopt, because it requires extra args to
375 # compile successfully when -shared is used as an argument
376 # Also made a difference between translating with shared or not,
377 # because this affects profopt's target
378
379 if self.config.translation.profopt:
380 if self.config.translation.profoptargs is None:
381 raise Exception("No profoptargs specified, neither in the command line, nor in the target. If the target is not PyPy, please specify profoptargs")
382
383 # Set the correct PGO params based on OS and CC
384 profopt_gen_flag = ""
385 profopt_use_flag = ""
386 profopt_merger = ""
387 profopt_file = ""
388 llvm_profdata = ""
389
390 cc = self.translator.platform.cc
391
392 # Locate llvm-profdata
393 if "clang" in cc:
394 clang_bin = cc
395 path = os.environ.get("PATH").split(":")
396 profdata_found = False
397
398 # Try to find it in $PATH (Darwin and Linux)
399 for dir in path:
400 bin = "%s/llvm-profdata" % dir
401 if os.path.isfile(bin):
402 llvm_profdata = bin
403 profdata_found = True
404 break
405
406 # If not found, try to find it where clang is actually installed (Darwin and Linux)
407 if not profdata_found:
408 # If the full path is not given, find where clang is located
409 if not os.path.isfile(clang_bin):
410 for dir in path:
411 bin = "%s/%s" % (dir, cc)
412 if os.path.isfile(bin):
413 clang_bin = bin
414 break
415 # Some systems install clang elsewhere as a symlink to the real path,
416 # which is where the related llvm tools are located.
417 if os.path.islink(clang_bin):
418 clang_bin = os.path.realpath(clang_bin) # the real clang binary
419 # llvm-profdata must be in the same directory as clang
420 llvm_profdata = "%s/llvm-profdata" % os.path.dirname(clang_bin)
421 profdata_found = os.path.isfile(llvm_profdata)
422
423 # If not found, and Darwin is used, try to find it in the development environment
424 # More: https://apple.stackexchange.com/questions/197053/
425 if not profdata_found and sys.platform == 'darwin':
426 code = os.system("/usr/bin/xcrun -find llvm-profdata 2>/dev/null")
427 if code == 0:
428 llvm_profdata = "/usr/bin/xcrun llvm-profdata"
429 profdata_found = True
430
431 # If everything failed, throw Exception, sorry
432 if not profdata_found:
433 raise Exception(
434 "Error: Cannot perform profopt build because llvm-profdata was not found in PATH. "
435 "Please add it to PATH and run the translation again.")
436
437 # Set the PGO flags
438 if "clang" in cc:
439 # Any changes made here should be reflected in the GCC+Darwin case below
440 coverage_flag = '--coverage'
441 profopt_gen_flag = "-fprofile-instr-generate"
442 profopt_use_flag = "-fprofile-instr-use=code.profclangd"
443 profopt_merger = "%s merge -output=code.profclangd *.profclangr" % llvm_profdata
444 profopt_file = 'LLVM_PROFILE_FILE="code-%p.profclangr"'
445 elif "gcc" in cc:
446 if sys.platform == 'darwin':
447 coverage_flag = '--coverage'
448 profopt_gen_flag = "-fprofile-instr-generate"
449 profopt_use_flag = "-fprofile-instr-use=code.profclangd"
450 profopt_merger = "%s merge -output=code.profclangd *.profclangr" % llvm_profdata
451 profopt_file = 'LLVM_PROFILE_FILE="code-%p.profclangr"'
452 else:
453 coverage_flag = '-lgcov'
454 profopt_gen_flag = "-fprofile-generate"
455 profopt_use_flag = "-fprofile-use -fprofile-correction"
456 profopt_merger = "true"
457 profopt_file = ""
458
459 if self.config.translation.shared:
460 mk.rule('$(PROFOPT_TARGET)',
461 '$(TARGET) main.o',
462 ['$(CC_LINK) $(LDFLAGS_LINK) main.o -L. -l$(SHARED_IMPORT_LIB) -o $@ $(RPATH_FLAGS) %s' % coverage_flag,
463 '$(MAKE) postcompile BIN=$(PROFOPT_TARGET)'
464 ]
465 )
466 else:
467 mk.definition('PROFOPT_TARGET', '$(TARGET)')
468
469 rules.append(
470 ('profopt', '', [
471 '$(MAKE) CFLAGS="%s -fPIC $(CFLAGS)" LDFLAGS="%s $(LDFLAGS)" $(PROFOPT_TARGET)' % (profopt_gen_flag, profopt_gen_flag),
472 '%s %s %s ' % (profopt_file, exe_name, self.config.translation.profoptargs),
473 '%s' % (profopt_merger),
474 '$(MAKE) clean_noprof',
475 '$(MAKE) CFLAGS="%s -fPIC $(CFLAGS)" LDFLAGS="%s $(LDFLAGS)" $(PROFOPT_TARGET)' % (profopt_use_flag, profopt_use_flag),
476 ]))
477
478 for rule in rules:
479 mk.rule(*rule)
480
481 if self.translator.platform.name == 'msvc':
482 mk.rule('lldebug0','', '$(MAKE) CFLAGS="$(DEBUGFLAGS) -Od -DMAX_STACK_SIZE=8192000 -DRPY_ASSERT -DRPY_LL_ASSERT" debug_target'),
483 wildcards = '..\*.obj ..\*.pdb ..\*.lib ..\*.dll ..\*.manifest ..\*.exp *.pch'
484 cmd = r'del /s %s $(DEFAULT_TARGET) $(TARGET) $(ASMFILES)' % wildcards
485 mk.rule('clean', '', cmd + ' *.gc?? ..\module_cache\*.gc??')
486 mk.rule('clean_noprof', '', cmd)
487 else:
488 mk.rule('lldebug0','', '$(MAKE) CFLAGS="$(DEBUGFLAGS) -O0 -DMAX_STACK_SIZE=8192000 -DRPY_ASSERT -DRPY_LL_ASSERT" debug_target'),
489 mk.rule('clean', '', 'rm -f $(OBJECTS) $(DEFAULT_TARGET) $(TARGET) $(ASMFILES) $(PRECOMPILEDHEADERS) *.gc?? ../module_cache/*.gc??')
490 mk.rule('clean_noprof', '', 'rm -f $(OBJECTS) $(DEFAULT_TARGET) $(TARGET) $(ASMFILES)')
491
492 if self.config.translation.gcrootfinder == 'asmgcc':
493 raise AssertionError("asmgcc not supported any more")
494 else:
495 if self.translator.platform.name == 'msvc':
496 mk.definition('DEBUGFLAGS', '-MD -Zi')
497 else:
498 if self.config.translation.shared:
499 mk.definition('DEBUGFLAGS', '-O1 -g -fPIC')
500 else:
501 mk.definition('DEBUGFLAGS', '-O1 -g')
502 if self.translator.platform.name == 'msvc':
503 mk.rule('debug_target', '$(DEFAULT_TARGET) $(WTARGET)', 'rem')
504 else:
505 mk.rule('debug_target', '$(DEFAULT_TARGET)', '#')
506 mk.write()
507 #self.translator.platform,
508 # ,
509 # self.eci, profbased=self.getprofbased()
510 self.executable_name = mk.exe_name
511 if self.config.translation.shared:
512 self.shared_library_name = mk.so_name
513 if sys.platform == 'win32':
514 self.executable_name_w = mk.wtarget_name
515
516 # ____________________________________________________________
517
518 SPLIT_CRITERIA = 65535 # support VC++ 7.2
519 #SPLIT_CRITERIA = 32767 # enable to support VC++ 6.0
520
521 MARKER = '/*/*/' # provide an easy way to split after generating
522
523 class SourceGenerator:
524 one_source_file = True
525
526 def __init__(self, database):
527 self.database = database
528 self.extrafiles = []
529 self.headers_to_precompile = []
530 self.path = None
531 self.namespace = NameManager()
532
533 def set_strategy(self, path, split=True):
534 all_nodes = list(self.database.globalcontainers())
535 # split off non-function nodes. We don't try to optimize these, yet.
536 funcnodes = []
537 othernodes = []
538 for node in all_nodes:
539 if node.nodekind == 'func':
540 funcnodes.append(node)
541 else:
542 othernodes.append(node)
543 if split:
544 self.one_source_file = False
545 self.funcnodes = funcnodes
546 self.othernodes = othernodes
547 self.path = path
548
549 def uniquecname(self, name):
550 assert name.endswith('.c')
551 return self.namespace.uniquename(name[:-2]) + '.c'
552
553 def makefile(self, name):
554 log.writing(name)
555 filepath = self.path.join(name)
556 if name.endswith('.c'):
557 self.extrafiles.append(filepath)
558 if name.endswith('.h'):
559 self.headers_to_precompile.append(filepath)
560 return filepath.open('w')
561
562 def getextrafiles(self):
563 return self.extrafiles
564
565 def getothernodes(self):
566 return self.othernodes[:]
567
568 def getbasecfilefornode(self, node, basecname):
569 # For FuncNode instances, use the python source filename (relative to
570 # the top directory):
571 def invent_nice_name(g):
572 # Lookup the filename from the function.
573 # However, not all FunctionGraph objs actually have a "func":
574 if hasattr(g, 'func'):
575 if g.filename.endswith('.py'):
576 localpath = py.path.local(g.filename)
577 pypkgpath = localpath.pypkgpath()
578 if pypkgpath:
579 relpypath = localpath.relto(pypkgpath.dirname)
580 assert relpypath, ("%r should be relative to %r" %
581 (localpath, pypkgpath.dirname))
582 if len(relpypath.split(os.path.sep)) > 2:
583 # pypy detail to agregate the c files by directory,
584 # since the enormous number of files was causing
585 # memory issues linking on win32
586 return os.path.split(relpypath)[0] + '.c'
587 return relpypath.replace('.py', '.c')
588 return None
589 if hasattr(node.obj, 'graph'):
590 # Regular RPython functions
591 name = invent_nice_name(node.obj.graph)
592 if name is not None:
593 return name
594 elif node._funccodegen_owner is not None:
595 # Data nodes that belong to a known function
596 graph = getattr(node._funccodegen_owner, 'graph', None)
597 name = invent_nice_name(graph)
598 if name is not None:
599 return "data_" + name
600 return basecname
601
602 def splitnodesimpl(self, basecname, nodes, nextra, nbetween,
603 split_criteria=SPLIT_CRITERIA):
604 # Gather nodes by some criteria:
605 nodes_by_base_cfile = {}
606 for node in nodes:
607 c_filename = self.getbasecfilefornode(node, basecname)
608 if c_filename in nodes_by_base_cfile:
609 nodes_by_base_cfile[c_filename].append(node)
610 else:
611 nodes_by_base_cfile[c_filename] = [node]
612
613 # produce a sequence of nodes, grouped into files
614 # which have no more than SPLIT_CRITERIA lines
615 for basecname in sorted(nodes_by_base_cfile):
616 iternodes = iter(nodes_by_base_cfile[basecname])
617 done = [False]
618 def subiter():
619 used = nextra
620 for node in iternodes:
621 impl = '\n'.join(list(node.implementation())).split('\n')
622 if not impl:
623 continue
624 cost = len(impl) + nbetween
625 yield node, impl
626 del impl
627 if used + cost > split_criteria:
628 # split if criteria met, unless we would produce nothing.
629 raise StopIteration
630 used += cost
631 done[0] = True
632 while not done[0]:
633 yield self.uniquecname(basecname), subiter()
634
635 @contextlib.contextmanager
636 def write_on_included_file(self, f, name):
637 fi = self.makefile(name)
638 print('#include "%s"' % name, file=f)
639 yield fi
640 fi.close()
641
642 @contextlib.contextmanager
643 def write_on_maybe_separate_source(self, f, name):
644 print('/* %s */' % name, file=f)
645 if self.one_source_file:
646 yield f
647 else:
648 fi = self.makefile(name)
649 yield fi
650 fi.close()
651
652 def gen_readable_parts_of_source(self, f):
653 split_criteria_big = SPLIT_CRITERIA
654 if py.std.sys.platform != "win32":
655 if self.database.gcpolicy.need_no_typeptr():
656 pass # XXX gcc uses toooooons of memory???
657 else:
658 split_criteria_big = SPLIT_CRITERIA * 4
659
660 #
661 # All declarations
662 #
663 with self.write_on_included_file(f, 'structdef.h') as fi:
664 gen_structdef(fi, self.database)
665 with self.write_on_included_file(f, 'forwarddecl.h') as fi:
666 gen_forwarddecl(fi, self.database)
667 with self.write_on_included_file(f, 'preimpl.h') as fi:
668 gen_preimpl(fi, self.database)
669
670 #
671 # Implementation of functions and global structures and arrays
672 #
673 print(file=f)
674 print('/***********************************************************/', file=f)
675 print('/*** Implementations ***/', file=f)
676 print(file=f)
677
678 print('#define PYPY_FILE_NAME "%s"' % os.path.basename(f.name), file=f)
679 print('#include "src/g_include.h"', file=f)
680 if self.database.reverse_debugger:
681 print('#include "revdb_def.h"', file=f)
682 print(file=f)
683
684 nextralines = 11 + 1
685 for name, nodeiter in self.splitnodesimpl('nonfuncnodes.c',
686 self.othernodes,
687 nextralines, 1):
688 with self.write_on_maybe_separate_source(f, name) as fc:
689 if fc is not f:
690 print('/***********************************************************/', file=fc)
691 print('/*** Non-function Implementations ***/', file=fc)
692 print(file=fc)
693 print('#include "singleheader.h"', file=fc)
694 print('#include "src/g_include.h"', file=fc)
695 print(file=fc)
696 print(MARKER, file=fc)
697 for node, impl in nodeiter:
698 print('\n'.join(impl), file=fc)
699 print(MARKER, file=fc)
700 print('/***********************************************************/', file=fc)
701
702 nextralines = 12
•703 IS_32_BIT = sys.maxint == 2**31-1
704 for name, nodeiter in self.splitnodesimpl('implement.c',
705 self.funcnodes,
706 nextralines, 1,
707 split_criteria_big):
708 with self.write_on_maybe_separate_source(f, name) as fc:
709 if fc is not f:
710 print('/***********************************************************/', file=fc)
711 print('/*** Implementations ***/', file=fc)
712 print(file=fc)
713 print('#include "singleheader.h"', file=fc)
714 print('#define PYPY_FILE_NAME "%s"' % name, file=fc)
715 print('#include "src/g_include.h"', file=fc)
716 if self.database.reverse_debugger:
717 print('#include "revdb_def.h"', file=fc)
718 print(file=fc)
•719 if IS_32_BIT:
720 print('#if defined __GNUC__ && __GNUC__ >= 14', file=fc)
721 print('#pragma GCC diagnostic warning "-Wincompatible-pointer-types"', file=fc)
722 print('#endif', file=fc)
723 print(MARKER, file=fc)
724 for node, impl in nodeiter:
725 print('\n'.join(impl), file=fc)
726 print(MARKER, file=fc)
727 print('/***********************************************************/', file=fc)
728 print(file=f)
729 if self.database.all_field_names is not None:
730 gen_fieldstats(f, self)
731
732
733 def gen_structdef(f, database):
734 structdeflist = database.getstructdeflist()
735 print('/***********************************************************/', file=f)
736 print('/*** Structure definitions ***/', file=f)
737 print(file=f)
738 print("#ifndef _PYPY_STRUCTDEF_H", file=f)
739 print("#define _PYPY_STRUCTDEF_H", file=f)
740 for node in structdeflist:
741 if hasattr(node, 'forward_decl'):
742 if node.forward_decl:
743 print(node.forward_decl, file=f)
744 elif node.name is not None:
745 print('%s %s;' % (node.typetag, node.name), file=f)
746 print(file=f)
747 for node in structdeflist:
748 for line in node.definition():
749 print(line, file=f)
750 gen_threadlocal_structdef(f, database)
751 print("#endif", file=f)
752
753 def gen_threadlocal_structdef(f, database):
754 from rpython.translator.c.support import cdecl
755 print(file=f)
756 bk = database.translator.annotator.bookkeeper
757 fields = list(bk.thread_local_fields)
758 fields.sort(key=lambda field: field.fieldname)
759 for field in fields:
760 print('#define RPY_TLOFS_%s offsetof(' % field.fieldname +
761 'struct pypy_threadlocal_s, %s)' % field.fieldname, file=f)
762 if fields:
763 print('#define RPY_TLOFSFIRST RPY_TLOFS_%s' % fields[0].fieldname, file=f)
764 else:
765 print('#define RPY_TLOFSFIRST sizeof(struct pypy_threadlocal_s)', file=f)
766 print('struct pypy_threadlocal_s {', file=f)
767 print('\tint ready;', file=f)
768 print('\tchar *stack_end;', file=f)
769 print('\tstruct pypy_threadlocal_s *prev, *next;', file=f)
770 # note: if the four fixed fields above are changed, you need
771 # to adapt threadlocal.c's linkedlist_head declaration too
772 for field in fields:
773 typename = database.gettype(field.FIELDTYPE)
774 print('\t%s;' % cdecl(typename, field.fieldname), file=f)
775 print('};', file=f)
776 print(file=f)
777
778 def gen_forwarddecl(f, database):
779 print('/***********************************************************/', file=f)
780 print('/*** Forward declarations ***/', file=f)
781 print(file=f)
782 print("#ifndef _PYPY_FORWARDDECL_H", file=f)
783 print("#define _PYPY_FORWARDDECL_H", file=f)
784 for node in database.globalcontainers():
785 for line in node.forward_declaration():
786 print(line, file=f)
787 print("#endif", file=f)
788
789 def gen_preimpl(f, database):
790 f.write('#ifndef _PY_PREIMPL_H\n#define _PY_PREIMPL_H\n')
791 if database.translator is None or database.translator.rtyper is None:
792 return
793 preimplementationlines = pre_include_code_lines(
794 database, database.translator.rtyper)
795 for line in preimplementationlines:
796 print(line, file=f)
797 f.write('#endif /* _PY_PREIMPL_H */\n')
798
799 def gen_startupcode(f, database):
800 # generate the start-up code and put it into a function
801 print('void RPython_StartupCode(void) {', file=f)
802
803 for line in database.gcpolicy.gc_startup_code():
804 print("\t" + line, file=f)
805
806 # put float infinities in global constants, we should not have so many of them for now to make
807 # a table+loop preferable
808 for dest, value in database.late_initializations:
809 print("\t%s = %s;" % (dest, value), file=f)
810
811 for node in database.containerlist:
812 lines = list(node.startupcode())
813 if lines:
814 for line in lines:
815 print('\t'+line, file=f)
816
817 for ll_init in database.translator._call_at_startup:
818 print('\t%s();\t/* call_at_startup */' % (database.get(ll_init),), file=f)
819
820 print('}', file=f)
821
822 def commondefs(defines):
823 from rpython.rlib.rarithmetic import LONG_BIT, LONGLONG_BIT
824 defines['PYPY_LONG_BIT'] = LONG_BIT
825 defines['PYPY_LONGLONG_BIT'] = LONGLONG_BIT
826
827 def add_extra_files(database, eci):
828 srcdir = py.path.local(__file__).join('..', 'src')
829 files = [
830 srcdir / 'entrypoint.c', # ifdef PYPY_STANDALONE
831 srcdir / 'mem.c',
832 srcdir / 'exception.c',
833 srcdir / 'rtyper.c', # ifdef HAVE_RTYPER
834 srcdir / 'support.c',
835 srcdir / 'profiling.c',
836 srcdir / 'debug_print.c',
837 srcdir / 'debug_traceback.c', # ifdef HAVE_RTYPER
838 srcdir / 'asm.c',
839 srcdir / 'instrument.c',
840 srcdir / 'int.c',
841 srcdir / 'stack.c',
842 srcdir / 'threadlocal.c',
843 ]
844 if _CYGWIN:
845 files.append(srcdir / 'cygwin_wait.c')
846 if database.reverse_debugger:
847 from rpython.translator.revdb import gencsupp
848 files += gencsupp.extra_files()
849 return eci.merge(ExternalCompilationInfo(separate_module_files=files))
850
851
852 def gen_source(database, modulename, targetdir,
853 eci, defines={}, split=False):
854 if isinstance(targetdir, str):
855 targetdir = py.path.local(targetdir)
856
857 filename = targetdir.join(modulename + '.c')
858 f = filename.open('w')
859 incfilename = targetdir.join('common_header.h')
860 fi = incfilename.open('w')
861 fi.write('#ifndef _PY_COMMON_HEADER_H\n#define _PY_COMMON_HEADER_H\n')
862
863 #
864 # Header
865 #
866 print('#include "common_header.h"', file=f)
867 print(file=f)
868 commondefs(defines)
869 for key, value in defines.items():
870 print('#define %s %s' % (key, value), file=fi)
871
872 eci.write_c_header(fi)
873 print('#include "src/g_prerequisite.h"', file=fi)
874 fi.write('#endif /* _PY_COMMON_HEADER_H*/\n')
875
876 fi.close()
877
878 #
879 # 1) All declarations
880 # 2) Implementation of functions and global structures and arrays
881 #
882 sg = SourceGenerator(database)
883 sg.set_strategy(targetdir, split)
884 sg.gen_readable_parts_of_source(f)
885 headers_to_precompile = sg.headers_to_precompile[:]
886 headers_to_precompile.insert(0, incfilename)
887
888 gen_startupcode(f, database)
889 f.close()
890
891 if 'PYPY_INSTRUMENT' in defines:
892 fi = incfilename.open('a')
893 n = database.instrument_ncounter
894 print("#define PYPY_INSTRUMENT_NCOUNTER %d" % n, file=fi)
895 fi.close()
896 if database.reverse_debugger:
897 from rpython.translator.revdb import gencsupp
898 gencsupp.write_revdb_def_file(database, targetdir.join('revdb_def.h'))
899
900 eci = add_extra_files(database, eci)
901 eci = eci.convert_sources_to_files()
902
903 # create singleheader.h, which combines common_header.h, structdef.h,
904 # forwarddecl.h and preimpl.h
905 singleheader = targetdir.join('singleheader.h')
906 with singleheader.open("w") as fs:
907 for fn in "common_header structdef forwarddecl preimpl".split():
908 fs.write("/*************** content of %s.h ***************/\n\n" % fn)
909 with targetdir.join(fn + ".h").open("r") as f:
910 fs.write(f.read())
911 fs.write("\n\n")
912 headers_to_precompile.insert(0, singleheader)
913
914 return eci, filename, sg.getextrafiles(), headers_to_precompile
915
916 def gen_fieldstats(f, sg):
917 with sg.write_on_maybe_separate_source(f, 'fieldstats.c') as fc:
918 print('#include "singleheader.h"', file=fc)
919 print('#include "src/g_include.h"', file=fc)
920 print("struct rpy_access_stats_type0 rpy_access_stats = {", file=fc)
921 print(", ".join(["0"] * len(sg.database.all_field_names) * 2), file=fc)
922 print("};", file=fc)
923 print("", file=fc)
924 print("void _pypy_print_field_stats() {", file=fc)
925 print('\tPYPY_DEBUG_START("stats-fields", 0);', file=fc)
926 print('\tif (PYPY_HAVE_DEBUG_PRINTS) {', file=fc)
927 for kind in "read", "write":
928 for fieldname in sorted(sg.database.all_field_names):
929 print('\t\tfprintf(PYPY_DEBUG_FILE, "%s %s %%ld\\n", rpy_access_stats.%s_%s);' % (
930 kind, fieldname, fieldname, kind), file=fc)
931 print('\t}', file=fc)
932 print('\tPYPY_DEBUG_STOP("stats-fields", 0);', file=fc)
933 print("}", file=fc)
934
935 # XXX hack, add something to structdef.h later
936 filepath = sg.path.join('structdef.h')
937 content = filepath.read().splitlines()
938 assert content[-1] == "#endif"
939 content = content[:-1]
940 content.append("struct rpy_access_stats_type0 {")
941 for fieldname in sorted(sg.database.all_field_names):
942 content.append("\tlong %s_read;" % fieldname)
943 content.append("\tlong %s_write;" % fieldname)
944 content.append("};")
945 # XXX should go to forwarddecl really
946 content.append("RPY_EXTERN struct rpy_access_stats_type0 rpy_access_stats;")
947 content.append("RPY_EXTERN void _pypy_print_field_stats();")
948 content.append("#endif")
949 filepath.write("\n".join(content))