-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathcompiler.lisp
7435 lines (7136 loc) · 289 KB
/
compiler.lisp
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
;;;;------------------------------------------------------------------
;;;;
;;;; Copyright (C) 2001,2000, 2002-2005,
;;;; Department of Computer Science, University of Tromso, Norway
;;;;
;;;; Description: A simple lisp compiler.
;;;; Author: Frode Vatvedt Fjeld <[email protected]>
;;;; Created at: Wed Oct 25 12:30:49 2000
;;;; Distribution: See the accompanying file COPYING.
;;;;
;;;; $Id: compiler.lisp,v 1.205 2008-04-27 19:07:33 ffjeld Exp $
;;;;
;;;;------------------------------------------------------------------
(in-package movitz)
(defvar *warn-function-change-p* t
"Emit a warning whenever a named function's code-vector changes size.")
(defvar *compiler-verbose-p* nil)
(defvar *compiler-do-optimize* t
"Apply the peephole optimizer to function code.")
(defvar *explain-peephole-optimizations* nil
"Emit some cryptic information about which peephole optimization
heuristics that fire. Used for debugging the optimizer.")
(defvar *compiler-use-cmov-p* nil
"Allow the compiler to emit CMOV instructions, making the code
incompatible with pre-pentium CPUs.")
(defvar *compiler-auto-stack-checks-p* t
"Make every compiled function check upon entry that the
stack-pointer is within bounds. Costs 3 code-bytes and a few cycles.")
(defvar *compiler-allow-transients* t
"Allow the compiler to keep function arguments solely in registers.
Hurst debugging, improves performance.")
(defvar *compiler-local-segment-prefix* '(:fs-override)
"Use these assembly-instruction prefixes when accessing the thread-local
run-time context.")
(defvar *compiler-global-segment-prefix* nil
"Use these assembly-instruction prefixes when accessing the global
run-time context.")
(defparameter *compiler-physical-segment-prefix* '(:gs-override)
"Use this instruction prefix when accessing a physical memory location (i.e. typically some memory-mapped hardware device).")
(defparameter *compiler-nonlocal-lispval-read-segment-prefix* '()
"Use this segment prefix when reading a lispval at (potentially)
non-local locations.")
(defparameter *compiler-nonlocal-lispval-write-segment-prefix* '(:es-override)
"Use this segment prefix when writing a lispval at (potentially)
non-local locations.")
(defparameter *compiler-use-cons-reader-segment-protocol-p* nil)
(defparameter *compiler-cons-read-segment-prefix* '(:gs-override)
"Use this segment prefix for CAR and CDR, when using cons-reader protocol.")
(defvar *compiler-allow-untagged-word-bits* 0
"Allow (temporary) untagged values of this bit-size to exist, because
the system ensures one way or another that there can be no pointers below
this size.")
(defvar *compiler-use-into-unbound-protocol* t
"Use #x7fffffff as the <unbound-value> and thereby the INTO
instruction for checking whether a value is the unbound value.")
(defvar *compiler-compile-eval-whens* t
"When encountering (eval-when (:compile-toplevel) <code>),
compile, using the host compiler, the code rather than just using eval.")
(defvar *compiler-compile-macro-expanders* t
"For macros of any kind, compile the macro-expanders using the host compiler.")
(defvar *compiler-do-type-inference* t
"Spend time and effort performing type inference and optimization.")
(defvar *compiler-produce-defensive-code* t
"Try to make code be extra cautious.")
(defvar *compiler-relink-recursive-funcall* t
"If true, also recursive function calls look up the function through the function name,
which enables tracing of recursive functions.")
(defvar *compiler-trust-user-type-declarations-p* t)
(defvar *compiling-function-name* nil)
(defvar muerte.cl:*compile-file-pathname* nil)
(defvar *extended-code-expanders*
(make-hash-table :test #'eq))
(defvar *extended-code-find-write-binding-and-type*
(make-hash-table :test #'eq))
(defparameter +enter-stack-frame-code+
'((:pushl :ebp)
(:movl :esp :ebp)
(:pushl :esi)))
(defun duplicatesp (list)
"Returns TRUE iff at least one object occurs more than once in LIST."
(if (null list)
nil
(or (member (car list) (cdr list))
(duplicatesp (cdr list)))))
(defun compute-call-extra-prefix (pc size)
(let* ((return-pointer-tag (ldb (byte 3 0)
(+ pc size))))
(cond
((or (= (tag :even-fixnum) return-pointer-tag)
(= (tag :odd-fixnum) return-pointer-tag))
;; Insert a NOP
'(#x90))
;;; ((= 3 return-pointer-tag)
;;; ;; Insert two NOPs, 3 -> 5
;;; '(#x90 #x90))
((= (tag :character) return-pointer-tag)
;; Insert three NOPs, 2 -> 5
'(#x90 #x90 #x90)
'(#x90)))))
(defun make-compiled-primitive (form environment top-level-p docstring)
"Primitive functions have no funobj, no stack-frame, and no implied
parameter/return value passing conventions."
(declare (ignore top-level-p docstring))
(let* ((env (make-local-movitz-environment environment nil))
(body-code (compiler-call #'compile-form
:form form
:funobj nil
:env env
:top-level-p nil
:result-mode :ignore))
;; (ignmore (format t "~{~S~%~}" body-code))
(resolved-code (finalize-code body-code nil nil)))
(multiple-value-bind (code-vector symtab)
(let ((asm-x86:*cpu-mode* :32-bit)
(asm:*instruction-compute-extra-prefix-map*
'((:call . compute-call-extra-prefix))))
(asm:assemble-proglist (translate-program resolved-code :muerte.cl :cl)
:symtab (list (cons :nil-value (image-nil-word *image*)))))
(values (make-movitz-vector (length code-vector)
:element-type 'code
:initial-contents code-vector)
symtab))))
(defun register-function-code-size (funobj)
(let* ((name (movitz-print (movitz-funobj-name funobj)))
(hash-name name)
(new-size (length (movitz-vector-symbolic-data (movitz-funobj-code-vector funobj)))))
(assert name)
(let ((old-size (gethash hash-name (function-code-sizes *image*))))
(cond
((not old-size))
((not *warn-function-change-p*))
((> new-size old-size)
(warn "~S grew from ~D to ~D bytes." name old-size new-size))
((< new-size old-size)
(warn "~S shrunk from ~D to ~D bytes" name old-size new-size))))
(setf (gethash hash-name (function-code-sizes *image*)) new-size))
funobj)
(defclass movitz-funobj-pass1 ()
((name
:initarg :name
:accessor movitz-funobj-name)
(lambda-list
:initarg :lambda-list
:accessor movitz-funobj-lambda-list)
(function-envs
:accessor function-envs)
(funobj-env
:initarg :funobj-env
:accessor funobj-env)
(extent
:initarg :extent
:initform :unused
:accessor movitz-funobj-extent)
(allocation
:initform nil
:accessor movitz-allocation)
(entry-protocol
:initform :default
:initarg :entry-protocol
:reader funobj-entry-protocol))
(:documentation "This class is used for funobjs during the first compiler pass.
Before the second pass, such objects will be change-class-ed to proper movitz-funobjs.
This way, we ensure that no undue side-effects on the funobj occur during pass 1."))
(defmethod print-object ((object movitz-funobj-pass1) stream)
(print-unreadable-object (object stream :type t :identity t)
(when (slot-boundp object 'name)
(write (movitz-funobj-name object) :stream stream)))
object)
(defun movitz-macro-expander-make-function (lambda-form &key name (type :unknown))
"Make a lambda-form that is a macro-expander into a proper function.
Gensym a name whose symbol-function is set to the macro-expander, and return that symbol."
(let ((function-name (gensym (format nil "~A-expander-~@[~A-~]" type name))))
(if *compiler-compile-macro-expanders*
(with-host-environment ()
(compile function-name lambda-form))
(setf (symbol-function function-name)
(coerce lambda-form 'function)))
function-name))
(defun make-compiled-funobj (name lambda-list declarations form env top-level-p &key funobj)
"Compiler entry-point for making a (lexically) top-level function."
(handler-bind (((or warning error)
(lambda (c)
(declare (ignore c))
(if (not (boundp 'muerte.cl:*compile-file-pathname*))
(format *error-output*
"~&;; While Movitz compiling ~S:" name)
(format *error-output*
"~&;; While Movitz compiling ~S in ~A:"
name muerte.cl:*compile-file-pathname*)))))
(with-retries-until-true (retry-funobj "Retry compilation of ~S." name)
(make-compiled-funobj-pass2
(make-compiled-funobj-pass1 name lambda-list declarations
form env top-level-p :funobj funobj)))))
(defun make-compiled-funobj-pass1 (name lambda-list declarations form env top-level-p
&key funobj)
"Per funobj (i.e. not necessarily top-level) entry-point for first-pass compilation.
If funobj is provided, its identity will be kept, but its type (and values) might change."
;; The ability to provide funobj's identity is important when a
;; function must be referenced before it can be compiled, e.g. for
;; mutually recursive (lexically bound) functions.
(multiple-value-bind (required-vars optional-vars rest-var key-vars aux-vars allow-p min max edx-var)
(decode-normal-lambda-list lambda-list)
(declare (ignore aux-vars allow-p min max))
;; There are several main branches through the function
;; compiler, and this is where we decide which one to take.
(funcall (cond
((let ((sub-form (cddr form)))
(and (consp (car sub-form))
(eq 'muerte::numargs-case (caar sub-form))))
'make-compiled-function-pass1-numarg-case)
((and (= 1 (length required-vars)) ; (x &optional y)
(= 1 (length optional-vars))
(movitz-constantp (nth-value 1 (decode-optional-formal (first optional-vars)))
env)
(null key-vars)
(not rest-var)
(not edx-var))
'make-compiled-function-pass1-1req1opt)
(t 'make-compiled-function-pass1))
name
lambda-list
declarations
form
env
top-level-p
funobj)))
(defun ensure-pass1-funobj (funobj class &rest init-args)
"If funobj is nil, return a fresh funobj of class.
Otherwise coerce funobj to class."
(apply #'reinitialize-instance
(if funobj
(change-class funobj class)
(make-instance class))
init-args))
(defun make-compiled-function-pass1-numarg-case (name lambda-list declarations form env top-level-p funobj)
(let* ((funobj (ensure-pass1-funobj funobj 'movitz-funobj-pass1
:entry-protocol :numargs-case
:name name
:lambda-list (movitz-read (lambda-list-simplify lambda-list))))
(funobj-env (make-local-movitz-environment env funobj :type 'funobj-env)))
(setf (funobj-env funobj) funobj-env
(function-envs funobj) nil)
(loop for (numargs lambda-list . clause-body) in (cdr (caddr form))
do (when (duplicatesp lambda-list)
(error "There are duplicates in lambda-list ~S." lambda-list))
(multiple-value-bind (clause-body clause-declarations)
(parse-declarations-and-body clause-body)
(let* ((function-env
(add-bindings-from-lambda-list lambda-list
(make-local-movitz-environment
funobj-env funobj
:type 'function-env
:declaration-context :funobj
:declarations
(append clause-declarations
declarations))))
(function-form (list* 'muerte.cl::block
(compute-function-block-name name)
clause-body)))
(multiple-value-bind (arg-init-code need-normalized-ecx-p)
(make-function-arguments-init funobj function-env)
(setf (extended-code function-env)
(append arg-init-code
(compiler-call #'compile-form
:form (make-special-funarg-shadowing function-env function-form)
:funobj funobj
:env function-env
:top-level-p top-level-p
:result-mode :function)))
(setf (need-normalized-ecx-p function-env) need-normalized-ecx-p))
(push (cons numargs function-env)
(function-envs funobj)))))
funobj))
(defun make-compiled-function-pass1-1req1opt (name lambda-list declarations form env top-level-p funobj)
"Returns funobj."
(when (duplicatesp lambda-list)
(error "There are duplicates in lambda-list ~S." lambda-list))
(let* ((funobj (ensure-pass1-funobj funobj 'movitz-funobj-pass1
:entry-protocol :1req1opt
:name name
:lambda-list (movitz-read (lambda-list-simplify lambda-list))))
(funobj-env (make-local-movitz-environment env funobj :type 'funobj-env))
(function-env (add-bindings-from-lambda-list
lambda-list
(make-local-movitz-environment funobj-env funobj
:type 'function-env
:need-normalized-ecx-p nil
:declaration-context :funobj
:declarations declarations)))
(optional-env (make-local-movitz-environment function-env funobj
:type 'function-env)))
(setf (funobj-env funobj) funobj-env)
;; (print-code 'arg-init-code arg-init-code)
(setf (extended-code optional-env)
(compiler-call #'compile-form
:form (optional-function-argument-init-form
(movitz-binding (first (optional-vars function-env)) function-env nil))
:funobj funobj
:env optional-env
:result-mode :ebx))
(setf (extended-code function-env)
(append #+ignore arg-init-code
(compiler-call #'compile-form
:form (make-special-funarg-shadowing function-env form)
:funobj funobj
:env function-env
:top-level-p top-level-p
:result-mode :function)))
(setf (function-envs funobj)
(list (cons 'muerte.cl::t function-env)
(cons :optional optional-env)))
funobj))
(defun make-compiled-function-pass1 (name lambda-list declarations form env top-level-p funobj)
"Returns funobj."
(when (duplicatesp lambda-list)
(error "There are duplicates in lambda-list ~S." lambda-list))
(let* ((funobj (ensure-pass1-funobj funobj 'movitz-funobj-pass1
:name name
:lambda-list (movitz-read (lambda-list-simplify lambda-list))))
(funobj-env (make-local-movitz-environment env funobj :type 'funobj-env))
(function-env (add-bindings-from-lambda-list
lambda-list
(make-local-movitz-environment funobj-env funobj
:type 'function-env
:declaration-context :funobj
:declarations declarations))))
(setf (funobj-env funobj) funobj-env
(function-envs funobj) (list (cons 'muerte.cl::t function-env)))
(multiple-value-bind (arg-init-code need-normalized-ecx-p)
(make-function-arguments-init funobj function-env)
(setf (need-normalized-ecx-p function-env) need-normalized-ecx-p)
(setf (extended-code function-env)
(append arg-init-code
(compiler-call #'compile-form
:form (make-special-funarg-shadowing function-env form)
:funobj funobj
:env function-env
:top-level-p top-level-p
:result-mode :function))))
funobj))
(defun make-compiled-funobj-pass2 (toplevel-funobj-pass1)
"This is the entry-poing for second pass compilation for each top-level funobj."
(check-type toplevel-funobj-pass1 movitz-funobj-pass1)
(let ((toplevel-funobj (change-class toplevel-funobj-pass1 'movitz-funobj)))
(multiple-value-bind (toplevel-funobj function-binding-usage)
(resolve-borrowed-bindings toplevel-funobj)
(complete-funobj
(layout-stack-frames
(analyze-bindings
(resolve-sub-functions toplevel-funobj function-binding-usage)))))))
(defstruct (type-analysis (:type list))
(thunks)
(binding-types)
(encoded-type
(multiple-value-list (type-specifier-encode nil)))
(declared-encoded-type
(multiple-value-list (type-specifier-encode t))))
(defun make-type-analysis-with-declaration (binding)
(let ((declared-type
(if (not (and *compiler-trust-user-type-declarations-p*
(movitz-env-get (binding-name binding) :variable-type
nil (binding-env binding) nil)))
(multiple-value-list (type-specifier-encode t))
(multiple-value-list
(type-specifier-encode (movitz-env-get (binding-name binding) :variable-type
t (binding-env binding) nil))))))
;; (warn "~S decl: ~A" binding (apply #'encoded-type-decode declared-type))
(make-type-analysis :declared-encoded-type declared-type)))
(defun analyze-bindings (toplevel-funobj)
"Figure out usage of bindings in a toplevel funobj.
Side-effects each binding's binding-store-type."
(if (not *compiler-do-type-inference*)
(labels
((analyze-code (code)
(dolist (instruction code)
(when (listp instruction)
(let ((binding
(find-written-binding-and-type instruction)))
(when binding
(setf (binding-store-type binding)
(multiple-value-list (type-specifier-encode t)))))
(analyze-code (instruction-sub-program instruction)))))
(analyze-funobj (funobj)
(loop for (nil . function-env) in (function-envs funobj)
do (analyze-code (extended-code function-env)))
(loop for function-binding in (sub-function-binding-usage funobj) by #'cddr
do (analyze-funobj (function-binding-funobj function-binding)))
funobj))
(analyze-funobj toplevel-funobj))
(let ((binding-usage (make-hash-table :test 'eq)))
(labels ((binding-resolved-p (binding)
(or (typep binding 'constant-object-binding)
(typep binding 'function-argument)
(let ((analysis (gethash binding binding-usage)))
(and analysis
(null (type-analysis-thunks analysis))))))
(binding-resolve (binding)
(cond
((not (bindingp binding))
binding)
((typep binding 'constant-object-binding)
(apply #'encoded-type-decode
(binding-store-type binding)))
((typep binding 'function-argument)
t)
((let ((analysis (gethash binding binding-usage)))
(assert (and (and analysis
(null (type-analysis-thunks analysis))))
(binding)
"Can't resolve unresolved binding ~S." binding)))
(*compiler-trust-user-type-declarations-p*
(let ((analysis (gethash binding binding-usage)))
(multiple-value-call #'encoded-type-decode
(apply #'encoded-types-and
(append (type-analysis-declared-encoded-type analysis)
(type-analysis-encoded-type analysis))))))
(t (let ((analysis (gethash binding binding-usage)))
(apply #'encoded-type-decode
(type-analysis-encoded-type analysis))))))
(type-is-t (type-specifier)
(or (eq type-specifier t)
(and (listp type-specifier)
(eq 'or (car type-specifier))
(some #'type-is-t (cdr type-specifier)))))
(analyze-store (binding type thunk thunk-args)
(assert (not (null type)) ()
"store-lexical with empty type.")
(assert (or (typep type 'binding)
(eql 1 (type-specifier-num-values type))) ()
"store-lexical with multiple-valued type: ~S for ~S" type binding)
#+ignore (warn "store ~S type ~S, thunk ~S" binding type thunk)
(let ((analysis (or (gethash binding binding-usage)
(setf (gethash binding binding-usage)
(make-type-analysis-with-declaration binding)))))
(cond
(thunk
(assert (some #'bindingp thunk-args))
(push (cons thunk thunk-args) (type-analysis-thunks analysis)))
((and (bindingp type)
(binding-eql type binding))
(break "got binding type")
nil)
(t (setf (type-analysis-encoded-type analysis)
(multiple-value-list
(multiple-value-call
#'encoded-types-or
(values-list (type-analysis-encoded-type analysis))
(type-specifier-encode type))))))))
(analyze-code (code)
#+ignore (print-code 'analyze code)
(dolist (instruction code)
(when (listp instruction)
(multiple-value-bind (store-binding store-type thunk thunk-args)
(find-written-binding-and-type instruction)
(when store-binding
#+ignore (warn "store: ~S binding ~S type ~S thunk ~S"
instruction store-binding store-type thunk)
(analyze-store store-binding store-type thunk thunk-args)))
(analyze-code (instruction-sub-program instruction)))))
(analyze-funobj (funobj)
(loop for (nil . function-env) in (function-envs funobj)
do (analyze-code (extended-code function-env)))
(loop for function-binding in (sub-function-binding-usage funobj) by #'cddr
do (analyze-funobj (function-binding-funobj function-binding)))
funobj))
;; 1. Examine each store to lexical bindings.
(analyze-funobj toplevel-funobj)
;; 2.
(flet ((resolve-thunks ()
(loop with more-thunks-p = t
repeat 20
while more-thunks-p
do (setf more-thunks-p nil)
(maphash (lambda (binding analysis)
(declare (ignore binding))
(setf (type-analysis-thunks analysis)
(loop for (thunk . thunk-args) in (type-analysis-thunks analysis)
if (not (every #'binding-resolved-p thunk-args))
collect (cons thunk thunk-args)
else
do #+ignore
(warn "because ~S=>~S->~S completing ~S: ~S and ~S"
thunk thunk-args
(mapcar #'binding-resolve thunk-args)
binding
(type-analysis-declared-encoded-type analysis)
(multiple-value-list
(multiple-value-call
#'encoded-types-or
(values-list
(type-analysis-encoded-type analysis))
(type-specifier-encode
(apply thunk (mapcar #'binding-resolve
thunk-args))))))
(setf (type-analysis-encoded-type analysis)
(multiple-value-list
(multiple-value-call
#'encoded-types-and
(values-list
(type-analysis-declared-encoded-type analysis))
(multiple-value-call
#'encoded-types-or
(values-list
(type-analysis-encoded-type analysis))
(type-specifier-encode
(apply thunk (mapcar #'binding-resolve
thunk-args)))))))
(setf more-thunks-p t))))
binding-usage))))
(resolve-thunks)
(when *compiler-trust-user-type-declarations-p*
;; For each unresolved binding, just use the declared type.
(maphash (lambda (binding analysis)
(declare (ignore binding))
(when (and (not (null (type-analysis-thunks analysis)))
(not (apply #'encoded-allp
(type-analysis-declared-encoded-type analysis))))
#+ignore
(warn "Trusting ~S, was ~S, because ~S [~S]"
binding
(type-analysis-encoded-type analysis)
(type-analysis-thunks analysis)
(loop for (thunk . thunk-args) in (type-analysis-thunks analysis)
collect (mapcar #'binding-resolved-p thunk-args)))
(setf (type-analysis-encoded-type analysis)
(type-analysis-declared-encoded-type analysis))
(setf (type-analysis-thunks analysis) nil))) ; Ignore remaining thunks.
binding-usage)
;; Try one more time to resolve thunks.
(resolve-thunks)))
#+ignore
(maphash (lambda (binding analysis)
(when (type-analysis-thunks analysis)
(warn "Unable to infer type for ~S: ~S" binding
(type-analysis-thunks analysis))))
binding-usage)
;; 3.
(maphash (lambda (binding analysis)
(setf (binding-store-type binding)
(cond
((and (not (null (type-analysis-thunks analysis)))
*compiler-trust-user-type-declarations-p*
(movitz-env-get (binding-name binding) :variable-type nil
(binding-env binding) nil))
(multiple-value-list
(type-specifier-encode (movitz-env-get (binding-name binding) :variable-type
t (binding-env binding) nil))))
((and *compiler-trust-user-type-declarations-p*
(movitz-env-get (binding-name binding) :variable-type nil
(binding-env binding) nil))
(multiple-value-list
(multiple-value-call #'encoded-types-and
(type-specifier-encode (movitz-env-get (binding-name binding) :variable-type
t (binding-env binding) nil))
(values-list (type-analysis-encoded-type analysis)))))
((not (null (type-analysis-thunks analysis)))
(multiple-value-list (type-specifier-encode t)))
(t (type-analysis-encoded-type analysis))))
#+ignore (warn "Finally: ~S" binding))
binding-usage))))
toplevel-funobj)
(defun resolve-borrowed-bindings (toplevel-funobj)
"For <funobj>'s code, for every non-local binding used we create
a borrowing-binding in the funobj-env. This process must be done
recursively, depth-first wrt. sub-functions. Also, return a plist
of all function-bindings seen."
(check-type toplevel-funobj movitz-funobj)
(let ((function-binding-usage ()))
(labels ((process-binding (funobj binding usages)
(when (typep binding 'function-binding)
(dolist (usage usages)
(pushnew usage
(getf (sub-function-binding-usage (function-binding-parent binding))
binding))
(pushnew usage (getf function-binding-usage binding))))
(cond
((typep binding 'constant-object-binding))
((not (eq funobj (binding-funobj binding)))
(let ((borrowing-binding
(or (find binding (borrowed-bindings funobj)
:key #'borrowed-binding-target)
(car (push (movitz-env-add-binding (funobj-env funobj)
(make-instance 'borrowed-binding
:name (binding-name binding)
:target-binding binding))
(borrowed-bindings funobj))))))
;; We don't want to borrow a forwarding-binding..
(when (typep (borrowed-binding-target borrowing-binding)
'forwarding-binding)
(change-class (borrowed-binding-target borrowing-binding)
'located-binding))
;;; (warn "binding ~S of ~S is not local to ~S, replacing with ~S of ~S."
;;; binding (binding-env binding) funobj
;;; borrowing-binding (binding-env borrowing-binding))
;;; (pushnew borrowing-binding
;;; (getf (binding-lended-p binding) :lended-to))
(dolist (usage usages)
(pushnew usage (borrowed-binding-usage borrowing-binding)))
borrowing-binding))
(t ; Binding is local to this funobj
(typecase binding
(forwarding-binding
(process-binding funobj (forwarding-binding-target binding) usages))
(t binding)))))
(resolve-sub-funobj (funobj sub-funobj)
(dolist (binding-we-lend (borrowed-bindings (resolve-funobj-borrowing sub-funobj)))
#+ignore
(warn "Lending from ~S to ~S: ~S <= ~S"
funobj sub-funobj
(borrowed-binding-target binding-we-lend)
binding-we-lend)
(process-binding funobj
(borrowed-binding-target binding-we-lend)
(borrowed-binding-usage binding-we-lend))))
(resolve-code (funobj code)
(dolist (instruction code)
(when (listp instruction)
(let ((store-binding (find-written-binding-and-type instruction)))
(when store-binding
(process-binding funobj store-binding '(:write))))
(dolist (load-binding (find-read-bindings instruction))
(process-binding funobj load-binding '(:read)))
(case (car instruction)
(:call-lexical
(process-binding funobj (second instruction) '(:call)))
(:stack-cons
(destructuring-bind (proto-cons dynamic-scope)
(cdr instruction)
(push proto-cons (dynamic-extent-scope-members dynamic-scope))))
(:load-lambda
(destructuring-bind (lambda-binding lambda-result-mode capture-env)
(cdr instruction)
(declare (ignore lambda-result-mode))
(assert (eq funobj (binding-funobj lambda-binding)) ()
"A non-local lambda doesn't make sense. There must be a bug.")
(let ((lambda-funobj (function-binding-funobj lambda-binding)))
(let ((dynamic-scope (find-dynamic-extent-scope capture-env)))
(when dynamic-scope
;; (warn "Adding ~S to ~S/~S" lambda-funobj dynamic-extent dynamic-scope)
(setf (movitz-funobj-extent lambda-funobj) :dynamic-extent
(movitz-allocation lambda-funobj) dynamic-scope)
(push lambda-funobj (dynamic-extent-scope-members dynamic-scope))
(process-binding funobj (base-binding dynamic-scope) '(:read))))
(resolve-sub-funobj funobj lambda-funobj)
(process-binding funobj lambda-binding '(:read))
;; This funobj is effectively using every binding that the lambda
;; is borrowing..
(map nil (lambda (borrowed-binding)
(process-binding funobj
(borrowed-binding-target borrowed-binding)
'(:read)))
(borrowed-bindings (function-binding-funobj lambda-binding))))))
(:local-function-init
(let ((function-binding (second instruction)))
(assert (eq funobj (binding-funobj function-binding)) ()
"Initialization of a non-local function doesn't make sense.")
(resolve-sub-funobj funobj (function-binding-funobj (second instruction)))
(map nil (lambda (borrowed-binding)
(process-binding funobj
(borrowed-binding-target borrowed-binding)
'(:read)))
(borrowed-bindings (function-binding-funobj (second instruction)))))))
(resolve-code funobj (instruction-sub-program instruction)))))
(resolve-funobj-borrowing (funobj)
(let ((funobj (change-class funobj 'movitz-funobj :borrowed-bindings nil)))
(loop for (nil . function-env) in (function-envs funobj)
do (resolve-code funobj (extended-code function-env)))
;; (warn "~S borrows ~S." funobj (borrowed-bindings funobj))
funobj)))
(values (resolve-funobj-borrowing toplevel-funobj)
function-binding-usage))))
(defun resolve-sub-functions (toplevel-funobj function-binding-usage)
(assert (null (borrowed-bindings toplevel-funobj)) ()
"Can't deal with toplevel closures yet. Borrowed: ~S"
(borrowed-bindings toplevel-funobj))
(setf (movitz-funobj-extent toplevel-funobj) :indefinite-extent)
(let ((sub-funobj-index 0))
(loop for (function-binding usage) on function-binding-usage by #'cddr
do (let ((sub-funobj (function-binding-funobj function-binding)))
;; (warn "USage: ~S => ~S" sub-funobj usage)
(case (car (movitz-funobj-name sub-funobj))
((muerte.cl:lambda)
(setf (movitz-funobj-name sub-funobj)
(list 'muerte.cl:lambda
(movitz-funobj-name toplevel-funobj)
(post-incf sub-funobj-index)))))
(loop for borrowed-binding in (borrowed-bindings sub-funobj)
do (pushnew borrowed-binding
(getf (binding-lending (borrowed-binding-target borrowed-binding))
:lended-to)))
;; (warn "old extent: ~S" (movitz-funobj-extent sub-funobj))
(cond
((or (null usage)
(null (borrowed-bindings sub-funobj)))
(when (null usage)
(warn "null usage for ~S" sub-funobj))
(change-class function-binding 'funobj-binding)
(setf (movitz-funobj-extent sub-funobj)
:indefinite-extent))
((equal usage '(:call))
(change-class function-binding 'closure-binding)
(setf (movitz-funobj-extent sub-funobj)
:lexical-extent))
((eq :dynamic-extent (movitz-funobj-extent sub-funobj))
(change-class function-binding 'closure-binding))
(t (change-class function-binding 'closure-binding)
(setf (movitz-funobj-extent sub-funobj)
:indefinite-extent))))))
;; Each time we change a function-binding to funobj-binding, that binding
;; no longer needs to be borrowed (because it doesn't share lexical bindings),
;; and therefore should be removed from any borrowed-binding list, which in
;; turn can cause the borrowing funobj to become a funobj-binding, and so on.
(loop for modified-p = nil
do (loop for function-binding in function-binding-usage by #'cddr
do (let ((sub-funobj (function-binding-funobj function-binding)))
(when (not (null (borrowed-bindings sub-funobj)))
(check-type function-binding closure-binding)
(when (null (setf (borrowed-bindings sub-funobj)
(delete-if (lambda (b)
(when (typep (borrowed-binding-target b) 'funobj-binding)
(setf modified-p t)))
(borrowed-bindings sub-funobj))))
(change-class function-binding 'funobj-binding)))))
while modified-p)
(loop for function-binding in function-binding-usage by #'cddr
do (finalize-funobj (function-binding-funobj function-binding)))
(finalize-funobj toplevel-funobj))
(defun finalize-funobj (funobj)
"Calculate funobj's constants, jumpers."
(loop with all-key-args-constants = nil
with all-constants-plist = () and all-jumper-sets = ()
for (nil . function-env) in (function-envs funobj)
;; (borrowed-bindings body-code) in code-specs
as body-code = (extended-code function-env)
as (const-plist jumper-sets key-args-constants) =
(multiple-value-list (find-code-constants-and-jumpers body-code))
do (when key-args-constants
(assert (not all-key-args-constants) ()
"only one &key parsing allowed per funobj.")
(setf all-key-args-constants key-args-constants))
(loop for (constant usage) on const-plist by #'cddr
do (incf (getf all-constants-plist constant 0) usage))
(loop for (name set) on jumper-sets by #'cddr
do (assert (not (getf all-jumper-sets name)) ()
"Jumper-set ~S multiply defined." name)
(setf (getf all-jumper-sets name) set))
finally
(multiple-value-bind (const-list num-jumpers jumpers-map borrower-map)
(layout-funobj-vector all-constants-plist
all-key-args-constants
#+ignore (mapcar (lambda (x)
(cons (movitz-read x) 1))
'(:a :b :c :d))
all-jumper-sets
(borrowed-bindings funobj))
(setf (movitz-funobj-num-jumpers funobj) num-jumpers
(movitz-funobj-const-list funobj) const-list
(movitz-funobj-num-constants funobj) (length const-list)
(movitz-funobj-jumpers-map funobj) jumpers-map)
(loop for (binding . pos) in borrower-map
do (setf (borrowed-binding-reference-slot binding) pos))
(return funobj))))
(defun layout-stack-frames (funobj)
"Lay out the stack-frame (i.e. create a frame-map) for funobj
and all its local functions. This must be done breadth-first, because
a (lexical-extent) sub-function might care about its parent frame-map."
(loop for (nil . function-env) in (function-envs funobj)
do (assert (not (slot-boundp function-env 'frame-map)))
(setf (frame-map function-env)
(funobj-assign-bindings (extended-code function-env)
function-env)))
(loop for (sub-function-binding) on (sub-function-binding-usage funobj) by #'cddr
do (layout-stack-frames (function-binding-funobj sub-function-binding)))
funobj)
(defun complete-funobj (funobj)
(case (funobj-entry-protocol funobj)
(:1req1opt
(complete-funobj-1req1opt funobj))
(t (complete-funobj-default funobj)))
(loop for (sub-function-binding) on (sub-function-binding-usage funobj) by #'cddr
do (complete-funobj (function-binding-funobj sub-function-binding)))
(register-function-code-size funobj))
(defun complete-funobj-1req1opt (funobj)
(assert (= 2 (length (function-envs funobj))))
(let* ((function-env (cdr (assoc 'muerte.cl::t (function-envs funobj))))
(optional-env (cdr (assoc :optional (function-envs funobj))))
(frame-map (frame-map function-env))
(resolved-code (finalize-code (extended-code function-env) funobj frame-map))
(resolved-optional-code (finalize-code (extended-code optional-env) funobj frame-map))
(stack-frame-size (frame-map-size (frame-map function-env)))
(use-stack-frame-p (or (plusp stack-frame-size)
(tree-search resolved-code
'(:pushl :popl :ebp :esp :call :leave))
(some (lambda (x)
(and (not (equal '(:movl (:ebp -4) :esi) x))
(tree-search x ':esi)))
resolved-code))))
(let* ((function-code
(let* ((req-binding (movitz-binding (first (required-vars function-env))
function-env nil))
(req-location (cdr (assoc req-binding frame-map)))
(opt-binding (movitz-binding (first (optional-vars function-env))
function-env nil))
(opt-location (cdr (assoc opt-binding frame-map)))
(optp-binding (movitz-binding (optional-function-argument-supplied-p-var opt-binding)
function-env nil))
(optp-location (cdr (assoc optp-binding frame-map)))
(stack-setup-pre 0))
(append `((:jmp (:edi ,(global-constant-offset 'trampoline-cl-dispatch-1or2))))
'(entry%1op)
(unless (eql nil opt-location)
resolved-optional-code)
(when optp-location
`((:movl :edi :edx)
(:jmp 'optp-into-edx-ok)))
'(entry%2op)
(when optp-location
`((,*compiler-global-segment-prefix*
:movl (:edi ,(global-constant-offset 't-symbol)) :edx)
optp-into-edx-ok))
(when use-stack-frame-p
+enter-stack-frame-code+)
'(start-stack-frame-setup)
(cond
((and (eql 1 req-location)
(eql 2 opt-location))
(incf stack-setup-pre 2)
`((:pushl :eax)
(:pushl :ebx)))
((and (eql 1 req-location)
(eql nil opt-location))
(incf stack-setup-pre 1)
`((:pushl :eax)))
((and (member req-location '(nil :eax))
(eql 1 opt-location))
(incf stack-setup-pre 1)
`((:pushl :ebx)))
((and (member req-location '(nil :eax))
(member opt-location '(nil :ebx)))
nil)
(t (error "Can't deal with req ~S opt ~S."
req-location opt-location)))
(cond
((not optp-location)
(make-stack-setup-code (- stack-frame-size stack-setup-pre)))
((and (integerp optp-location)
(= optp-location (1+ stack-setup-pre)))
(append `((:pushl :edx))
(make-stack-setup-code (- stack-frame-size stack-setup-pre 1))))
((integerp optp-location)
(append (make-stack-setup-code (- stack-frame-size stack-setup-pre))
`((:movl :edx (:ebp ,(stack-frame-offset optp-location))))))
(t (error "Can't deal with optional-p at ~S, after (~S ~S)."
optp-location req-location opt-location)))
(flet ((make-lending (location lended-cons-position)
(etypecase req-location
(integer
`((:movl (:ebp ,(stack-frame-offset location)) :edx)
(:movl :edi (:ebp ,(stack-frame-offset lended-cons-position))) ; cdr
(:movl :edx (:ebp ,(stack-frame-offset (1+ lended-cons-position)))) ; car
(:leal (:ebp 1 ,(stack-frame-offset (1+ lended-cons-position)))
:edx)
(:movl :edx (:ebp ,(stack-frame-offset location))))))))
(append
(when (binding-lended-p req-binding)
(make-lending req-location (getf (binding-lending req-binding)
:stack-cons-location)))
(when (binding-lended-p opt-binding)
(make-lending opt-location (getf (binding-lending opt-binding)
:stack-cons-location)))
(when (and optp-binding (binding-lended-p optp-binding))
(make-lending optp-location (getf (binding-lending optp-binding)
:stack-cons-location)))))
resolved-code
(make-compiled-function-postlude funobj function-env
use-stack-frame-p)))))
(let ((optimized-function-code
(optimize-code function-code
:keep-labels (append (subseq (movitz-funobj-const-list funobj)
0 (movitz-funobj-num-jumpers funobj))
'(entry%1op entry%2op)))))
(assemble-funobj funobj optimized-function-code)))))
(defun complete-funobj-default (funobj)
(let ((code-specs
(loop for (numargs . function-env) in (function-envs funobj)
collecting
(let* ((frame-map (frame-map function-env))
(resolved-code (finalize-code (extended-code function-env) funobj frame-map))
(stack-frame-size (frame-map-size (frame-map function-env)))
(use-stack-frame-p (or (plusp stack-frame-size)
(tree-search resolved-code
'(:push :pop :ebp :esp :call :leave))
(some (lambda (x)
(and (not (equal '(:movl (:ebp -4) :esi) x))
(tree-search x ':esi)))
resolved-code))))
(multiple-value-bind (prelude-code have-normalized-ecx-p)
(make-compiled-function-prelude stack-frame-size function-env use-stack-frame-p
(need-normalized-ecx-p function-env) frame-map
:do-check-stack-p (or (<= 32 stack-frame-size)
(tree-search resolved-code
'(:call))))
(let ((function-code
(install-arg-cmp (append prelude-code
resolved-code
(make-compiled-function-postlude funobj function-env
use-stack-frame-p))
have-normalized-ecx-p)))
(let ((optimized-function-code
(optimize-code function-code
:keep-labels (append
(subseq (movitz-funobj-const-list funobj)
0 (movitz-funobj-num-jumpers funobj))
'(entry%1op
entry%2op
entry%3op)))))
(cons numargs optimized-function-code))))))))
(let ((code1 (cdr (assoc 1 code-specs)))
(code2 (cdr (assoc 2 code-specs)))
(code3 (cdr (assoc 3 code-specs)))
(codet (cdr (assoc 'muerte.cl::t code-specs))))
(assert codet () "A default numargs-case is required.")
;; (format t "codet:~{~&~A~}" codet)
(let ((combined-code
(delete 'start-stack-frame-setup
(append
(when code1
`((:cmpb 1 :cl)
(:jne 'not-one-arg)
,@(unless (find 'entry%1op code1)
'(entry%1op (:movb 1 :cl)))
,@code1
not-one-arg))
(when code2
`((:cmpb 2 :cl)
(:jne 'not-two-args)
,@(unless (find 'entry%2op code2)
'(entry%2op (:movb 2 :cl)))
,@code2
not-two-args))
(when code3
`((:cmpb 3 :cl)
(:jne 'not-three-args)
,@(unless (find 'entry%3op code3)
'(entry%3op (:movb 3 :cl)))
,@code3