~ chicken-core (master) /batch-driver.scm
Trap1;;;; batch-driver.scm - Driver procedure for the compiler
2;
3; Copyright (c) 2008-2022, The CHICKEN Team
4; Copyright (c) 2000-2007, Felix L. Winkelmann
5; All rights reserved.
6;
7; Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following
8; conditions are met:
9;
10; Redistributions of source code must retain the above copyright notice, this list of conditions and the following
11; disclaimer.
12; Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following
13; disclaimer in the documentation and/or other materials provided with the distribution.
14; Neither the name of the author nor the names of its contributors may be used to endorse or promote
15; products derived from this software without specific prior written permission.
16;
17; THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
18; OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
19; AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR
20; CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
21; CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
22; SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23; THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
24; OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
25; POSSIBILITY OF SUCH DAMAGE.
26
27
28(declare
29 (unit batch-driver)
30 (uses extras data-structures pathname expand
31 support compiler-syntax compiler optimizer internal
32 ;; TODO: Backend should be configurable
33 scrutinizer lfa2 c-platform c-backend user-pass))
34
35(module chicken.compiler.batch-driver
36 (compile-source-file)
37
38(import scheme
39 chicken.base
40 chicken.file
41 chicken.fixnum
42 chicken.format
43 chicken.gc
44 chicken.internal
45 chicken.load
46 chicken.pathname
47 chicken.platform
48 chicken.pretty-print
49 chicken.process-context
50 chicken.process-context.posix
51 chicken.string
52 chicken.syntax
53 chicken.port
54 chicken.time
55 chicken.condition
56 chicken.compiler.support
57 chicken.compiler.compiler-syntax
58 chicken.compiler.core
59 chicken.compiler.optimizer
60 chicken.compiler.scrutinizer
61 chicken.compiler.lfa2
62 chicken.compiler.c-platform
63 chicken.compiler.c-backend
64 chicken.compiler.user-pass)
65
66(include "tweaks")
67(include "mini-srfi-1.scm")
68
69(define-constant funny-message-timeout 60000)
70
71;;; Emit collected information from various statistics about the program
72
73(define (print-program-statistics db)
74 (receive
75 (size osize kvars kprocs globs sites entries) (compute-database-statistics db)
76 (when (debugging 's "program statistics:")
77 (printf "; program size: \t~s \toriginal program size: \t~s\n" size osize)
78 (printf "; variables with known values: \t~s\n" kvars)
79 (printf "; known procedures: \t~s\n" kprocs)
80 (printf "; global variables: \t~s\n" globs)
81 (printf "; known call sites: \t~s\n" sites)
82 (printf "; database entries: \t~s\n" entries) ) ) )
83
84;;; Initialize analysis database:
85;;
86;; - Simply marks the symbols directly in the plist.
87;; - Does nothing after the first invocation, but we leave it this way to
88;; have the option to add default entries for each new db.
89
90(define initialize-analysis-database
91 (let ((initial #t))
92 (lambda ()
93 (when initial
94 (for-each
95 (lambda (s)
96 (mark-variable s '##compiler#intrinsic 'standard))
97 standard-bindings)
98 (for-each
99 (lambda (s)
100 (mark-variable s '##compiler#intrinsic 'extended))
101 extended-bindings)
102 (for-each
103 (lambda (s)
104 (mark-variable s '##compiler#intrinsic 'internal))
105 internal-bindings))
106 (set! initial #f))))
107
108;;; Display analysis database:
109
110(define display-analysis-database
111 (let ((names '((captured . cpt) (assigned . set) (boxed . box) (global . glo)
112 (assigned-locally . stl)
113 (contractable . con) (standard-binding . stb) (simple . sim)
114 (inlinable . inl)
115 (collapsable . col) (removable . rem) (constant . con)
116 (inline-target . ilt) (inline-transient . itr)
117 (undefined . und) (replacing . rpg) (unused . uud) (extended-binding . xtb)
118 (inline-export . ilx) (hidden-refs . hrf)
119 (value-ref . vvf)
120 (customizable . cst) (has-unused-parameters . hup) (boxed-rest . bxr) ) )
121 (omit #f))
122 (lambda (db)
123 (unless omit
124 (set! omit
125 (append default-standard-bindings
126 default-extended-bindings
127 internal-bindings) ) )
128 (hash-table-for-each
129 (lambda (sym plist)
130 (let ((val #f)
131 (lval #f)
132 (pvals #f)
133 (csites '())
134 (refs '())
135 (derived-rvars '()))
136 (unless (memq sym omit)
137 (write sym)
138 (let loop ((es plist))
139 (if (pair? es)
140 (begin
141 (case (caar es)
142 ((captured assigned boxed global contractable standard-binding assigned-locally
143 collapsable removable undefined replacing unused simple inlinable inline-export
144 has-unused-parameters extended-binding customizable constant boxed-rest hidden-refs)
145 (printf "\t~a" (cdr (assq (caar es) names))) )
146 ((unknown)
147 (set! val 'unknown) )
148 ((value)
149 (unless (eq? val 'unknown) (set! val (cdar es))) )
150 ((local-value)
151 (unless (eq? val 'unknown) (set! lval (cdar es))) )
152 ((potential-values)
153 (set! pvals (cdar es)))
154 ((replacable home contains contained-in use-expr closure-size rest-parameter
155 captured-variables explicit-rest rest-cdr rest-null? consed-rest-arg)
156 (printf "\t~a=~s" (caar es) (cdar es)) )
157 ((derived-rest-vars)
158 (set! derived-rvars (cdar es)))
159 ((references)
160 (set! refs (cdar es)) )
161 ((call-sites)
162 (set! csites (cdar es)) )
163 (else (bomb "Illegal property" (car es))) )
164 (loop (cdr es)) ) ) )
165 (when (pair? refs) (printf "\trefs=~s" (length refs)))
166 (when (pair? derived-rvars) (printf "\tdrvars=~s" (length derived-rvars)))
167 (when (pair? csites) (printf "\tcss=~s" (length csites)))
168 (cond [(and val (not (eq? val 'unknown)))
169 (printf "\tval=~s" (cons (node-class val) (node-parameters val))) ]
170 [(and lval (not (eq? val 'unknown)))
171 (printf "\tlval=~s" (cons (node-class lval) (node-parameters lval)))])
172 (when (pair? pvals)
173 (for-each
174 (lambda (pval)
175 (printf "\tpval=~s" (cons (node-class pval) (node-parameters pval))))
176 pvals))
177 (newline) ) ) )
178 db) ) ) )
179
180;;; Compile a complete source file:
181
182(define (compile-source-file filename user-supplied-options . options)
183 (define (option-arg p)
184 (if (null? (cdr p))
185 (quit-compiling "missing argument to `-~A' option" (car p))
186 (let ([arg (cadr p)])
187 (if (symbol? arg)
188 (quit-compiling "invalid argument to `~A' option" arg)
189 arg) ) ) )
190 (initialize-compiler)
191 (set! explicit-use-flag (memq 'explicit-use options))
192 (set! emit-debug-info (memq 'debug-info options))
193 (when (memq 'module-registration options)
194 (set! compile-module-registration 'yes))
195 (when (memq 'no-module-registration options)
196 (set! compile-module-registration 'no))
197 (when (memq 'static options)
198 (set! static-extensions #t)
199 (register-feature! 'chicken-compile-static))
200 (let* ((dynamic (memq 'dynamic options))
201 (unit (memq 'unit options))
202 (init-forms `((##core#declare
203 ,@(append
204 default-declarations
205 (if emit-debug-info
206 '((uses debugger-client))
207 '())
208 (if explicit-use-flag
209 '()
210 `((uses ,@default-units)))
211 (if (and static-extensions
212 (not dynamic)
213 (not unit)
214 (not explicit-use-flag)
215 (or (not compile-module-registration)
216 (eq? compile-module-registration 'yes)))
217 '((uses eval-modules))
218 '())))))
219 (import-forms `((import-for-syntax ,@default-syntax-imports)
220 ,@(if explicit-use-flag
221 '()
222 `((import-syntax ,@default-imports)))))
223 (cleanup-forms '(((chicken.base#implicit-exit-handler))))
224 (outfile (cond ((memq 'output-file options)
225 => (lambda (node)
226 (let ((oname (option-arg node)))
227 (if (symbol? oname)
228 (symbol->string oname)
229 oname) ) ) )
230 ((memq 'to-stdout options) #f)
231 (else (make-pathname #f (if filename (pathname-file filename) "out") "c")) ) )
232 ;; Create a temporary file to receive the C code, so that it
233 ;; can atomically be renamed to the actual output file after
234 ;; the C generation.
235 (tmp-outfile (and outfile
236 (conc outfile ".tmp." (current-process-id) (current-seconds))))
237 (opasses (default-optimization-passes))
238 (time0 #f)
239 (time-breakdown #f)
240 (forms '())
241 (inline-output-file #f)
242 (profile (or (memq 'profile options)
243 (memq 'accumulate-profile options)
244 (memq 'profile-name options)))
245 (profile-name
246 (and-let* ((pn (memq 'profile-name options))) (cadr pn)))
247 (hsize (memq 'heap-size options))
248 (kwstyle (memq 'keyword-style options))
249 (a-only (memq 'analyze-only options))
250 (do-scrutinize #t)
251 (do-lfa2 (memq 'lfa2 options))
252 (dumpnodes #f)
253 (start-time #f)
254 (upap #f)
255 (ssize (or (memq 'nursery options) (memq 'stack-size options)))
256 (module-name
257 (and-let* ((m (memq 'module options)))
258 (option-arg m))))
259
260 (define (cputime) (current-process-milliseconds))
261
262 (define (dribble fstr . args)
263 (debugging 'p (apply sprintf fstr args)))
264
265 (define (print-header mode dbgmode)
266 (debugging 'p "pass" mode)
267 (and (memq dbgmode debugging-chicken)
268 (begin
269 (printf "[~a]~%" mode)
270 #t) ) )
271
272 (define (print-node mode dbgmode n)
273 (when (print-header mode dbgmode)
274 (if dumpnodes
275 (dump-nodes n)
276 (pretty-print (build-expression-tree n)) ) ) )
277
278 (define (print-db mode dbgmode db pass)
279 (when (print-header mode dbgmode)
280 (printf "(iteration ~s)~%" pass)
281 (display-analysis-database db) ) )
282
283 (define (print-expr mode dbgmode xs)
284 (when (print-header mode dbgmode)
285 (for-each
286 (lambda (x)
287 (pretty-print x)
288 (newline))
289 xs) ) )
290
291 (define (string-trim str)
292 (let loop ((front 0)
293 (back (string-length str)))
294 (cond ((= front back) "")
295 ((char-whitespace? (string-ref str front))
296 (loop (add1 front) back))
297 ((char-whitespace? (string-ref str (sub1 back)))
298 (loop front (sub1 back)))
299 (else (substring str front back)))))
300
301 (define (string->extension-name str)
302 (let ((str (string-trim str)))
303 (if (and (positive? (string-length str))
304 (char=? #\( (string-ref str 0)))
305 (handle-exceptions ex
306 (##sys#error "invalid import specification" str)
307 (with-input-from-string str read))
308 (string->symbol str))))
309
310 (define (arg-val str)
311 (let* ((len (string-length str))
312 (len1 (- len 1)) )
313 (or (if (< len 2)
314 (string->number str)
315 (case (string-ref str len1)
316 ((#\m #\M) (* (string->number (substring str 0 len1)) (* 1024 1024)))
317 ((#\k #\K) (* (string->number (substring str 0 len1)) 1024))
318 (else (string->number str)) ) )
319 (quit-compiling "invalid numeric argument ~S" str) ) ) )
320
321 (define (collect-options opt)
322 (let loop ([opts options])
323 (cond [(memq opt opts) => (lambda (p) (cons (option-arg p) (loop (cddr p))))]
324 [else '()] ) ) )
325
326 (define (begin-time)
327 (when time-breakdown (set! time0 (cputime))) )
328
329 (define (end-time pass)
330 (when time-breakdown
331 (printf "milliseconds needed for ~a: \t~s~%"
332 pass
333 (inexact->exact (round (- (cputime) time0)) ) )))
334
335 (define (analyze pass node . args)
336 (let-optionals args ((no 0) (contf #t))
337 (let ((db (analyze-expression node)))
338 (when upap
339 (upap pass db node
340 (cut db-get db <> <>)
341 (cut db-put! db <> <> <>)
342 no contf) )
343 db) ) )
344
345 (define (chop-separator str)
346 (let ((len (sub1 (string-length str))))
347 (if (and (> len 0)
348 (memq (string-ref str len) '(#\\ #\/)))
349 (substring str 0 len)
350 str) ) )
351
352 (when unit
353 (set! unit-name (string->symbol (option-arg unit))))
354 (when (or unit-name dynamic)
355 (set! standalone-executable #f))
356 (when (memq 'ignore-repository options)
357 (set! ##sys#dload-disabled #t)
358 (repository-path #f))
359 (set! enable-specialization (memq 'specialize options))
360 (set! debugging-chicken
361 (append-map
362 (lambda (do)
363 (map (lambda (c) (string->symbol (string c)))
364 (string->list do) ) )
365 (collect-options 'debug) ) )
366 (when (memq 'h debugging-chicken)
367 (print-debug-options)
368 (exit))
369 (set! dumpnodes (memq '|D| debugging-chicken))
370 (set! import-libraries
371 (map (lambda (il)
372 (cons (string->symbol il)
373 (string-append il ".import.scm")))
374 (collect-options 'emit-import-library)))
375 (when (and (memq 'emit-all-import-libraries options)
376 (not a-only))
377 (set! all-import-libraries #t))
378 (when enable-specialization
379 (set! do-scrutinize #t))
380 (when (memq 't debugging-chicken) (##sys#start-timer))
381 (when (memq 'b debugging-chicken) (set! time-breakdown #t))
382 (when (memq 'raw options)
383 (set! explicit-use-flag #t)
384 (set! init-forms '())
385 (set! import-forms '())
386 (set! cleanup-forms '()))
387 (when (memq 'no-lambda-info options)
388 (set! emit-closure-info #f) )
389 (when (memq 'no-compiler-syntax options)
390 (set! compiler-syntax-enabled #f))
391 (when (memq 'local options)
392 (set! local-definitions #t))
393 (when (memq 'inline-global options)
394 (set! enable-inline-files #t)
395 (set! inline-locally #t))
396 (when (memq 'verbose options)
397 (set! verbose-mode #t)
398 (set! ##sys#notices-enabled #t))
399 (when (memq 'strict-types options)
400 (set! strict-variable-types #t)
401 (set! enable-specialization #t))
402 (when (memq 'no-warnings options)
403 (dribble "Warnings are disabled")
404 (set! ##sys#warnings-enabled #f)
405 (set! do-scrutinize #f)) ; saves some processing time
406 (when (memq 'optimize-leaf-routines options) (set! optimize-leaf-routines #t))
407 (when (memq 'unsafe options)
408 (set! unsafe #t) )
409 (when (memq 'setup-mode options)
410 (set! ##sys#setup-mode #t))
411 (when (memq 'regenerate-import-libraries options)
412 (set! preserve-unchanged-import-libraries #f))
413 (when (memq 'disable-interrupts options) (set! insert-timer-checks #f))
414 (when (memq 'fixnum-arithmetic options) (set! number-type 'fixnum))
415 (when (memq 'block options) (set! block-compilation #t))
416 (when (memq 'emit-external-prototypes-first options)
417 (set! external-protos-first #t))
418 (when (memq 'inline options) (set! inline-locally #t))
419 (and-let* ((elf (memq 'emit-link-file options)))
420 (set! emit-link-file (option-arg elf)))
421 (and-let* ((ifile (memq 'emit-inline-file options)))
422 (set! inline-locally #t) ; otherwise this option makes no sense
423 (set! local-definitions #t)
424 (set! inline-output-file (option-arg ifile)))
425 (and-let* ((tfile (memq 'emit-types-file options)))
426 (set! types-output-file (option-arg tfile)))
427 (and-let* ([inlimit (memq 'inline-limit options)])
428 (set! inline-max-size
429 (let ([arg (option-arg inlimit)])
430 (or (string->number arg)
431 (quit-compiling
432 "invalid argument to `-inline-limit' option: `~A'" arg) ) ) ) )
433 (and-let* ((ulimit (memq 'unroll-limit options)))
434 (set! unroll-limit
435 (let ((arg (option-arg ulimit)))
436 (or (string->number arg)
437 (quit-compiling
438 "invalid argument to `-unroll-limit' option: `~A'" arg) ) ) ) )
439 (when (memq 'case-insensitive options)
440 (dribble "Identifiers and symbols are case insensitive")
441 (register-feature! 'case-insensitive)
442 (case-sensitive #f) )
443 (when kwstyle
444 (let ([val (option-arg kwstyle)])
445 (cond [(string=? "prefix" val) (keyword-style #:prefix)]
446 [(string=? "none" val) (keyword-style #:none)]
447 [(string=? "suffix" val) (keyword-style #:suffix)]
448 [else (quit-compiling
449 "invalid argument to `-keyword-style' option")] ) ) )
450 (when (memq 'no-parentheses-synonyms options)
451 (dribble "Disabled support for parentheses synonyms")
452 (parentheses-synonyms #f) )
453 (when (memq 'r7rs-syntax options)
454 (dribble "Disabled the CHICKEN extensions to R7RS syntax")
455 (case-sensitive #f)
456 (keyword-style #:none)
457 (parentheses-synonyms #f))
458 (set! ##sys#read-error-with-line-number #t)
459 (set! ##sys#include-pathnames
460 (append (map chop-separator (collect-options 'include-path))
461 ##sys#include-pathnames) )
462 (when (and outfile filename (string=? outfile filename))
463 (quit-compiling "source- and output-filename are the same") )
464 (when (memq 'keep-shadowed-macros options)
465 (set! undefine-shadowed-macros #f) )
466 (when (memq 'no-argc-checks options)
467 (set! no-argc-checks #t) )
468 (when (memq 'no-bound-checks options)
469 (set! no-bound-checks #t) )
470 (when (memq 'no-procedure-checks options)
471 (set! no-procedure-checks #t) )
472 (when (memq 'no-procedure-checks-for-toplevel-bindings options)
473 (set! no-global-procedure-checks #t) )
474 (when (memq 'no-procedure-checks-for-usual-bindings options)
475 (for-each
476 (lambda (v)
477 (mark-variable v '##compiler#always-bound-to-procedure)
478 (mark-variable v '##compiler#always-bound) )
479 default-standard-bindings)
480 (for-each
481 (lambda (v)
482 (mark-variable v '##compiler#always-bound-to-procedure)
483 (mark-variable v '##compiler#always-bound) )
484 default-extended-bindings) )
485 (when (memq 'p debugging-chicken) (load-verbose #t))
486
487 ;; Handle feature options:
488 (for-each
489 register-feature!
490 (append-map (cut string-split <> ", ") (collect-options 'feature)))
491 (for-each
492 unregister-feature!
493 (append-map (cut string-split <> ",") (collect-options 'no-feature)))
494
495 ;; Load extensions:
496 (set! ##sys#features (cons #:compiler-extension ##sys#features))
497 (let ([extends (collect-options 'extend)])
498 (dribble "Loading compiler extensions...")
499 (for-each
500 (lambda (e)
501 (let ((f (##sys#resolve-include-filename e #f #t #f)))
502 (when (not f) (quit-compiling "cannot load extension: ~a" e))
503 (load f)))
504 extends) )
505 (set! ##sys#features (delete #:compiler-extension ##sys#features eq?))
506 (set! ##sys#features (cons '#:compiling ##sys#features))
507 (set! upap (user-post-analysis-pass))
508
509 ;; Handle units added with the "-uses" flag.
510 (let ((uses (append-map
511 (lambda (u) (map string->symbol (string-split u ", ")))
512 (collect-options 'uses))))
513 (unless (null? uses)
514 (set! init-forms
515 (append init-forms `((##core#declare (uses . ,uses)))))))
516
517 ;; Mark linked libraries so they will be compiled as unit dependencies.
518 (let ((link (append-map
519 (lambda (l) (map string->symbol (string-split l ", ")))
520 (collect-options 'link))))
521 (set! linked-libraries (lset-union/eq? linked-libraries link)))
522
523 ;; Append required extensions to imports:
524 (set! import-forms
525 (append
526 import-forms
527 (map (lambda (r) `(import ,(string->extension-name r)))
528 (collect-options 'require-extension))))
529
530 (when (memq 'compile-syntax options)
531 (set! ##sys#enable-runtime-macros #t) )
532 (set! target-heap-size
533 (and hsize
534 (arg-val (option-arg hsize))))
535 (set! target-stack-size
536 (and ssize
537 (arg-val (option-arg ssize))))
538 (set! emit-trace-info (not (memq 'no-trace options)))
539 (set! disable-stack-overflow-checking (memq 'disable-stack-overflow-checks options))
540 (set! bootstrap-mode (feature? #:chicken-bootstrap))
541 (when (memq 'm debugging-chicken) (set-gc-report! #t))
542 (cond ((memq 'no-usual-integrations options)
543 (set! do-scrutinize #f))
544 (else
545 (set! standard-bindings default-standard-bindings)
546 (set! extended-bindings default-extended-bindings) ))
547 (dribble "debugging info: ~A"
548 (if emit-trace-info
549 "calltrace"
550 "none") )
551 (when profile
552 (let ((acc (eq? 'accumulate-profile (car profile))))
553 (when (and acc (not profile-name))
554 (quit-compiling
555 "you need to specify -profile-name if using accumulated profiling runs"))
556 (set! emit-profile #t)
557 (set! profiled-procedures 'all)
558 (set! init-forms
559 (append
560 init-forms
561 default-profiling-declarations
562 (if acc
563 '((set! ##sys#profile-append-mode #t))
564 '() ) ) )
565 (dribble "generating ~aprofiled code" (if acc "accumulative " "")) ))
566
567 ;;XXX hardcoded "modules.db" is bad (also used in chicken-install.scm)
568 (load-identifier-database "modules.db")
569
570 (cond ((memq 'version options)
571 (print-version #t)
572 (newline) )
573 ((or (memq 'help options) (memq '-help options) (memq 'h options) (memq '-h options))
574 (print-usage))
575 ((memq 'release options)
576 (display (chicken-version))
577 (newline) )
578 ((not filename)
579 (print-version #t)
580 (display "\nEnter `chicken -help' for information on how to use the compiler,\n")
581 (display "or try `csc' for a more convenient interface.\n")
582 (display "\nRun `csi' to start the interactive interpreter.\n"))
583 (else
584
585 ;; Display header:
586 (dribble "compiling `~a' ..." filename)
587 (debugging 'r "options" options)
588 (debugging 'r "debugging options" debugging-chicken)
589 (debugging 'r "target heap size" target-heap-size)
590 (debugging 'r "target stack size" target-stack-size)
591 (set! start-time (cputime))
592
593 ;; Read toplevel expressions:
594 (set! ##sys#line-number-database (make-vector line-number-database-size '()))
595 (let ([prelude (collect-options 'prelude)]
596 [postlude (collect-options 'postlude)]
597 [files (append
598 (collect-options 'prologue)
599 (list filename)
600 (collect-options 'epilogue) ) ] )
601
602 (let ([proc (user-read-pass)])
603 (cond [proc
604 (dribble "User read pass...")
605 (set! forms (proc prelude files postlude)) ]
606 [else
607 (do ([files files (cdr files)])
608 ((null? files)
609 (set! forms
610 (append (map string->expr prelude)
611 (reverse forms)
612 (map string->expr postlude) ) ) )
613 (let* ((f (car files))
614 (in (check-and-open-input-file f)) )
615 (fluid-let ((##sys#current-source-filename f))
616 (let loop ()
617 (let ((x (chicken.syntax#read-with-source-info in))) ; OBSOLETE - after bootstrapping we can get rid of this explicit namespacing
618
619 (cond ((eof-object? x)
620 (close-checked-input-file in f) )
621 (else
622 (set! forms (cons x forms))
623 (loop)))))))) ] ) ) )
624
625 ;; Start compilation passes:
626 (let ([proc (user-preprocessor-pass)])
627 (when proc
628 (dribble "User preprocessing pass...")
629 (set! forms (map proc forms))))
630
631 (print-expr "source" '|1| forms)
632 (begin-time)
633 ;; Canonicalize s-expressions
634 (let* ((init0 (map canonicalize-expression init-forms))
635 (exps0 (map (lambda (x)
636 (fluid-let ((##sys#current-source-filename filename))
637 (canonicalize-expression x)))
638 (let ((forms (append import-forms forms)))
639 (if (not module-name)
640 forms
641 `((##core#module
642 ,(string->symbol module-name) ()
643 ,@forms))))))
644 (uses0 (map (lambda (u)
645 (canonicalize-expression `(##core#require ,u)))
646 (##sys#fast-reverse used-libraries)))
647 (exps (append
648 (map (lambda (ic) `(set! ,(cdr ic) ',(car ic))) immutable-constants)
649 init0
650 uses0
651 (if unit-name `((##core#provide ,unit-name)) '())
652 (if emit-profile
653 (profiling-prelude-exps (and (not unit-name)
654 (or profile-name #t)))
655 '() )
656 exps0
657 (if standalone-executable
658 cleanup-forms
659 '((##core#undefined))))))
660
661 (unless (null? import-libraries)
662 (quit-compiling
663 "No module definition found for import libraries to emit: ~A"
664 ;; ~S would be confusing: separate with a comma
665 (string-intersperse
666 (map (lambda (il) (->string (car il)))
667 import-libraries) ", ")))
668
669 (when (pair? compiler-syntax-statistics)
670 (with-debugging-output
671 'S
672 (lambda ()
673 (print "applied compiler syntax:")
674 (for-each
675 (lambda (cs) (printf " ~a\t\t~a~%" (car cs) (cdr cs)))
676 compiler-syntax-statistics))))
677 (when (debugging '|N| "real name table:")
678 (display-real-name-table) )
679 (when (debugging 'n "line number database:")
680 (##sys#display-line-number-database) )
681
682 (set! ##sys#line-number-database line-number-database-2)
683 (set! line-number-database-2 #f)
684
685 (end-time "canonicalization")
686 (print-expr "canonicalized" '|2| exps)
687
688 (when (memq 'check-syntax options) (exit))
689
690 ;; User-defined pass (s-expressions)
691 (let ([proc (user-pass)])
692 (when proc
693 (dribble "User pass...")
694 (begin-time)
695 (set! exps (map proc exps))
696 (end-time "user pass") ) )
697
698 ;; Convert s-expressions to node tree
699 (let ((node0 (build-toplevel-procedure
700 (build-node-graph
701 (canonicalize-begin-body exps))))
702 (db #f))
703 (print-node "initial node tree" '|T| node0)
704 (initialize-analysis-database)
705
706 ;; collect requirements and load inline files
707 (let ((extensions required-extensions))
708 (when enable-inline-files
709 (for-each
710 (lambda (id)
711 (and-let* ((ifile (##sys#resolve-include-filename
712 (symbol->string id) '(".inline") #t #f)))
713 (dribble "Loading inline file ~a ..." ifile)
714 (load-inline-file ifile)))
715 extensions))
716 (let ((ifs (collect-options 'consult-inline-file)))
717 (unless (null? ifs)
718 (set! inline-locally #t)
719 (for-each
720 (lambda (ilf)
721 (dribble "Loading inline file ~a ..." ilf)
722 (load-inline-file ilf) )
723 ifs)))
724 ;; Perform scrutiny and optionally specialization
725 (when (or do-scrutinize enable-specialization)
726 ;;XXX hardcoded database file name
727 (unless (memq 'ignore-repository options)
728 (unless (load-type-database "types.db"
729 enable-specialization)
730 (quit-compiling
731 "default type-database `types.db' not found")))
732 (for-each
733 (lambda (fn)
734 (or (load-type-database fn enable-specialization #f)
735 (quit-compiling "type-database `~a' not found" fn)))
736 (collect-options 'consult-types-file))
737 (for-each
738 (lambda (id)
739 (load-type-database
740 (make-pathname #f (symbol->string id) "types")
741 enable-specialization))
742 extensions)
743 (begin-time)
744 (set! first-analysis #f)
745 (set! db (analyze 'scrutiny node0))
746 (print-db "analysis" '|0| db 0)
747 (end-time "pre-analysis (scrutiny)")
748 (begin-time)
749 (debugging 'p "performing scrutiny")
750 (scrutinize node0 db
751 do-scrutinize enable-specialization
752 strict-variable-types block-compilation)
753 (end-time "scrutiny")
754 (when enable-specialization
755 (print-node "specialization" '|P| node0))
756 (set! first-analysis #t) ) )
757
758 ;; TODO: Move this so that we don't need to export these
759 (set! ##sys#line-number-database #f)
760 (set! constant-table #f)
761 (set! inline-table #f)
762 ;; Analyze toplevel assignments
763 (unless unsafe
764 (scan-toplevel-assignments (first (node-subexpressions node0))) )
765
766 (begin-time)
767 ;; Convert to CPS
768 (let ([node1 (perform-cps-conversion node0)])
769 (end-time "cps conversion")
770 (print-node "cps" '|3| node1)
771
772 ;; Optimization loop:
773 (let loop ((i 1)
774 (node2 node1)
775 (progress #t))
776 (begin-time)
777 ;; Analyze node tree for optimization
778 (let ([db (analyze 'opt node2 i progress)])
779 (when first-analysis
780 (when (memq 'u debugging-chicken)
781 (dump-undefined-globals db))
782 (when (memq 'd debugging-chicken)
783 (dump-defined-globals db))
784 (when (memq 'v debugging-chicken)
785 (dump-global-refs db))
786 ;; do this here, because we must make sure we have a db
787 (and-let* ((tfile (or (and (eq? types-output-file #t)
788 (pathname-replace-extension filename "types"))
789 (and (string? types-output-file)
790 types-output-file))))
791 (dribble "generating type file `~a' ..." tfile)
792 (emit-types-file filename tfile db block-compilation)))
793 (set! first-analysis #f)
794 (end-time "analysis")
795 (print-db "analysis" '|4| db i)
796
797 (when (memq 's debugging-chicken)
798 (print-program-statistics db))
799
800 ;; Optimize (once)
801 (cond (progress
802 (debugging 'p "optimization pass" i)
803 (begin-time)
804 (receive (node2 progress-flag)
805 (perform-high-level-optimizations
806 node2 db block-compilation
807 inline-locally inline-max-size
808 unroll-limit
809 inline-substitutions-enabled)
810 (end-time "optimization")
811 (print-node "optimized-iteration" '|5| node2)
812 (cond (progress-flag
813 (loop (add1 i) node2 #t))
814 ((not inline-substitutions-enabled)
815 (debugging 'p "rewritings enabled")
816 (set! inline-substitutions-enabled #t)
817 (loop (add1 i) node2 #t) )
818 (optimize-leaf-routines
819 (begin-time)
820 (let ([db (analyze 'leaf node2)])
821 (end-time "analysis")
822 (begin-time)
823 (let ((progress
824 (transform-direct-lambdas! node2 db)))
825 (end-time "leaf routine optimization")
826 (loop (add1 i)
827 node2
828 progress) ) ) )
829 (else
830 (loop (add1 i) node2 #f)) ) ) )
831
832 (else
833 ;; Secondary flow-analysis
834 (when do-lfa2
835 (begin-time)
836 (debugging 'p "doing lfa2")
837 (let ((floatvars (perform-secondary-flow-analysis node2 db)))
838 (end-time "secondary flow analysis")
839 (unless (null? floatvars)
840 (begin-time)
841 (debugging 'p "doing unboxing")
842 (set! node2 (perform-unboxing node2 floatvars)))
843 (end-time "unboxing")))
844 (print-node "optimized" '|7| node2)
845 ;; inlining into a file with interrupts enabled would
846 ;; change semantics
847 (when (and inline-output-file insert-timer-checks)
848 (let ((f inline-output-file))
849 (dribble "generating global inline file `~a' ..." f)
850 (emit-global-inline-file
851 filename f db block-compilation
852 inline-max-size
853 (map foreign-stub-id foreign-lambda-stubs)) ) )
854 (begin-time)
855 ;; Closure conversion
856 (set! node2 (perform-closure-conversion node2 db))
857 (end-time "closure conversion")
858 (print-db "final-analysis" '|8| db i)
859 (when (and ##sys#warnings-enabled
860 (> (- (cputime) start-time) funny-message-timeout))
861 (display "(don't worry - still compiling...)\n") )
862 (print-node "closure-converted" '|9| node2)
863 (when a-only (exit 0))
864 (begin-time)
865 ;; Preparation
866 (receive (node literals lliterals lambda-table dbg-info)
867 (prepare-for-code-generation node2 db)
868 (end-time "preparation")
869 (begin-time)
870
871 ;; generate link file
872 (when emit-link-file
873 (let ((exts required-extensions))
874 (dribble "generating link file `~a' ..." emit-link-file)
875 (with-output-to-file emit-link-file (cut pp exts))))
876
877 ;; Code generation
878 (let ((out (if tmp-outfile
879 (open-output-file tmp-outfile)
880 (current-output-port))) )
881 (when tmp-outfile
882 (dribble "generating `~A' ..." tmp-outfile))
883 (generate-code literals lliterals lambda-table out filename
884 user-supplied-options dynamic db dbg-info)
885 (when tmp-outfile
886 (close-output-port out)
887 (rename-file tmp-outfile outfile #t)))
888 (end-time "code generation")
889 (when (memq 't debugging-chicken)
890 (##sys#display-times (##sys#stop-timer)))
891 (compiler-cleanup-hook)
892 (dribble "compilation finished.") ) ) ) ) ) ) ) ) ) ) ) )
893)