3 ;; Copyright (C) 2013 David Vazquez
5 ;; JSCL is free software: you can redistribute it and/or
6 ;; modify it under the terms of the GNU General Public License as
7 ;; published by the Free Software Foundation, either version 3 of the
8 ;; License, or (at your option) any later version.
10 ;; JSCL is distributed in the hope that it will be useful, but
11 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 ;; General Public License for more details.
15 ;; You should have received a copy of the GNU General Public License
16 ;; along with JSCL. If not, see <http://www.gnu.org/licenses/>.
25 ;;;; Random Common Lisp code useful to use here and there.
27 (defmacro with-gensyms ((&rest vars) &body body)
28 `(let ,(mapcar (lambda (var) `(,var (gensym ,(concatenate 'string (string var) "-")))) vars)
32 (and (consp x) (null (cdr x))))
38 (defun generic-printer (x stream)
39 (print-unreadable-object (x stream :type t :identity t)))
41 ;;; A generic counter mechanism. IDs are used generally for debugging
42 ;;; purposes. You can bind *counter-alist* to NIL to reset the
43 ;;; counters in a dynamic extent.
44 (defvar *counter-alist* nil)
45 (defun generate-id (class)
46 (let ((e (assoc class *counter-alist*)))
50 (push (cons class 1) *counter-alist*)))))
53 ;;;; Intermediate representation structures
55 ;;;; This intermediate representation (IR) is a simplified version of
56 ;;;; the first intermediate representation what you will find if you
57 ;;;; have a look to the source code of SBCL. Some terminology is also
58 ;;;; used, but other is changed, so be careful if you assume you know
59 ;;;; what it is because you know the name.
61 ;;;; Computations are represented by `node'. Nodes are grouped
62 ;;;; sequencially into `basic-block'. It is a plain representation
63 ;;;; rather than a nested one. Computations take data and produce a
64 ;;;; value. Both data transfer are represented by `lvar'.
68 ;;; A (lexical) variable. Special variables has not a special
69 ;;; representation in the IR. They are handled by the primitive
70 ;;; functions `%symbol-function' and `%symbol-value'.
71 (defstruct (var (:include leaf))
72 ;; The symbol which names this variable in the source code.
75 ;;; A literal Lisp object. It usually comes from a quoted expression.
76 (defstruct (constant (:include leaf))
80 ;;; A lambda expression. Why do we name it `functional'? Well,
81 ;;; function is reserved by the ANSI, isn't it?
82 (defstruct (functional (:include leaf) (:print-object generic-printer))
83 ;; The symbol which names this function in the source code or null
84 ;; if we do not know or it is an anonymous function.
90 ;;; An abstract place where the result of a computation is stored and
91 ;;; it can be referenced from other nodes, so lvars are responsible
92 ;;; for keeping the necessary information of the nested structure of
93 ;;; the code in this plain representation.
95 (id (generate-id 'lvar)))
97 ;;; A base structure for every single computation. Most of the
98 ;;; computations are valued.
99 (defstruct (node (:print-object generic-printer))
100 ;; The next and the prev slots are the next nodes and the previous
101 ;; node in the basic block sequence respectively.
103 ;; Lvar which stands for the result of the computation of this node.
106 ;;; Sentinel nodes in the basic block sequence of nodes.
107 (defstruct (block-entry (:include node)))
108 (defstruct (block-exit (:include node)))
110 ;;; A reference to a leaf (variable, constant and functions). The
111 ;;; meaning of this node is leaving the leaf into the lvar of the
113 (defstruct (ref (:include node))
116 ;;; An assignation of the LVAR VALUE into the var VARIABLE.
117 (defstruct (assignment (:include node))
121 ;;; A base node to function calls with a list of lvar as ARGUMENTS.
122 (defstruct (combination (:include node) (:constructor))
125 ;;; A function call to the ordinary Lisp function in the lvar FUNCTION.
126 (defstruct (call (:include combination))
129 ;;; A function call to the primitive FUNCTION.
130 (defstruct (primitive-call (:include combination))
134 ;;; A conditional branch. If the LVAR is not NIL, then we will jump to
135 ;;; the basic block CONSEQUENT, jumping to ALTERNATIVE otherwise. By
136 ;;; definition, a conditional must appear at the end of a basic block.
137 (defstruct (conditional (:include node))
144 ;;; Blocks are `basic block`. Basic blocks are organized as a control
145 ;;; flow graph with some more information in omponents.
146 (defstruct (basic-block
147 (:conc-name "BLOCK-")
148 (:constructor make-block)
150 (:print-object generic-printer))
151 (id (generate-id 'basic-block))
152 ;; List of successors and predecessors of this basic block. They are
153 ;; null only for deleted blocks and component's entry and exit.
155 ;; The sentinel nodes of the sequence.
157 ;; The component where the basic block belongs to.
159 ;; The order in the reverse post ordering of the blocks.
161 ;; A bit-vector representing the set of dominators. See the function
162 ;; `compute-dominators' to know how to use it properly.
164 ;; Arbitrary data which could be necessary to keep during IR
168 ;;; Sentinel nodes in the control flow graph of basic blocks.
169 (defstruct (component-entry (:include basic-block)))
170 (defstruct (component-exit (:include basic-block)))
172 ;;; Return T if B is an empty basic block and NIL otherwise.
173 (defun empty-block-p (b)
174 (block-exit-p (node-next (block-entry b))))
176 (defun boundary-block-p (block)
177 (or (component-entry-p block)
178 (component-exit-p block)))
180 ;;; Iterate across the nodes in a basic block forward.
182 ((node block &optional result &key include-sentinel-p) &body body)
183 `(do ((,node ,(if include-sentinel-p
184 `(block-entry ,block)
185 `(node-next (block-entry ,block)))
187 (,(if include-sentinel-p
189 `(block-exit-p ,node))
193 ;;; Iterate across the nodes in a basic block backward.
194 (defmacro do-nodes-backward
195 ((node block &optional result &key include-sentinel-p) &body body)
196 `(do ((,node ,(if include-sentinel-p
198 `(node-prev (block-entry ,block)))
200 (,(if include-sentinel-p
202 `(block-entry-p ,node))
206 ;;; Link FROM and TO nodes together. FROM and TO must belong to the
207 ;;; same basic block and appear in such order. The nodes between FROM
208 ;;; and TO are discarded.
209 (defun link-nodes (from to)
210 (setf (node-next from) to
215 ;;; Components are connected pieces of the control flow graph of
216 ;;; basic blocks with some additional information. Components have
217 ;;; well-defined entry and exit nodes. It is the toplevel
218 ;;; organizational entity in the compiler. The IR translation result
219 ;;; is accumulated into components incrementally.
220 (defstruct (component (:print-object generic-printer))
221 (id (generate-id 'component))
226 ;; TODO: Replace with a flags slot for indicate what
227 ;; analysis/transformations have been carried out.
231 ;;; The current component.
234 ;;; Create a new fresh empty basic block in the current component.
235 (defun make-empty-block ()
236 (let ((entry (make-block-entry))
237 (exit (make-block-exit)))
238 (link-nodes entry exit)
239 (let ((block (make-block :entry entry :exit exit :component *component*)))
240 (push block (component-blocks *component*))
243 ;;; Create a new component with an empty basic block, ready to start
244 ;;; conversion to IR. It returns the component and the basic block as
246 (defun make-empty-component (&optional name)
247 (let ((*component* (make-component :name name)))
248 (let ((entry (make-component-entry :component *component*))
249 (exit (make-component-exit :component *component*))
250 (block (make-empty-block)))
251 (setf (block-succ entry) (list block)
252 (block-pred exit) (list block)
253 (block-succ block) (list exit)
254 (block-pred block) (list entry)
255 (component-entry *component*) entry
256 (component-exit *component*) exit)
257 (values *component* block))))
259 ;;; A few consistency checks in the IR useful for catching bugs.
260 (defun check-ir-consistency (&optional (component *component*))
261 (with-simple-restart (continue "Continue execution")
262 (dolist (block (component-blocks component))
263 (dolist (succ (block-succ block))
264 (unless (find block (block-pred succ))
265 (error "The block `~S' does not belong to the predecessors list of the its successor `~S'"
267 (unless (or (boundary-block-p succ) (find succ (component-blocks component)))
268 (error "Block `~S' is reachable from its predecessor `~S' but it is not in the component `~S'"
269 succ block component)))
270 (dolist (pred (block-pred block))
271 (unless (find block (block-succ pred))
272 (error "The block `~S' does not belong to the successors' list of its predecessor `~S'"
274 (unless (or (boundary-block-p pred) (find pred (component-blocks component)))
275 (error "Block `~S' is reachable from its sucessor `~S' but it is not in the component `~S'"
276 pred block component))))))
278 ;;; Prepare a new component with a current empty block ready to start
279 ;;; IR conversion bound in the current cursor. BODY is evaluated and
280 ;;; the value of the last form is returned.
281 (defmacro with-component-compilation ((&optional name) &body body)
282 (with-gensyms (block)
283 `(multiple-value-bind (*component* ,block)
284 (make-empty-component ,name)
285 (let ((*cursor* (cursor :block ,block)))
288 ;;; Call function for each reachable block in component in
289 ;;; post-order. The consequences are unspecified if a block is
290 ;;; FUNCTION modifies a block which has not been processed yet.
291 (defun map-postorder-blocks (function component)
293 (labels ((compute-from (block)
294 (unless (or (component-exit-p block) (find block seen))
296 (dolist (successor (block-succ block))
297 (unless (component-exit-p block)
298 (compute-from successor)))
299 (funcall function block))))
300 (compute-from (unlist (block-succ (component-entry component))))
303 ;;; Change all the predecessors of BLOCK to precede NEW-BLOCK
304 ;;; instead. As consequence, BLOCK becomes unreachable.
305 (defun replace-block (block new-block)
306 (let ((predecessors (block-pred block)))
307 (setf (block-pred block) nil)
308 (dolist (pred predecessors)
309 (pushnew pred (block-pred new-block))
310 (setf (block-succ pred) (substitute new-block block (block-succ pred)))
311 (unless (component-entry-p pred)
312 (let ((last-node (node-prev (block-exit pred))))
313 (when (conditional-p last-node)
314 (macrolet ((replacef (place)
315 `(setf ,place (if (eq block ,place) new-block ,place))))
316 (replacef (conditional-consequent last-node))
317 (replacef (conditional-alternative last-node)))))))))
319 (defun delete-block (block)
320 (when (boundary-block-p block)
321 (error "Cannot delete entry or exit basic blocks."))
322 (unless (singlep (block-succ block))
323 (error "Cannot delete a basic block with multiple successors."))
324 (let ((successor (unlist (block-succ block))))
325 (replace-block block successor)
326 ;; At this point, block is unreachable, however we could have
327 ;; backreferences to it from its successors. Let's get rid of
329 (setf (block-pred successor) (remove block (block-pred successor)))
330 (setf (block-succ block) nil)))
335 ;;;; A cursor is a point between two nodes in some basic block in the
336 ;;;; IR representation where manipulations can take place, similarly
337 ;;;; to the cursors in text editing.
339 ;;;; Cursors cannot point to special component's entry and exit basic
340 ;;;; blocks or after a conditional node. Conveniently, the `cursor'
341 ;;;; function will signal an error if the cursor is not positioned
342 ;;;; correctly, so the rest of the code does not need to check once
348 ;;; The current cursor. It is the default cursor for many functions
349 ;;; which work on cursors.
352 ;;; Return the current basic block. It is to say, the basic block
353 ;;; where the current cursor is pointint.
354 (defun current-block ()
355 (cursor-block *cursor*))
357 ;;; Create a cursor which points to the basic block BLOCK. If omitted,
358 ;;; then the current block is used.
360 ;;; The keywords AFTER and BEFORE specify the cursor will point after (or
361 ;;; before) that node respectively. If none is specified, the cursor is
362 ;;; created before the exit node in BLOCK. An error is signaled if both
363 ;;; keywords are specified inconsistently, or if the nodes do not belong
366 ;;; AFTER and BEFORE could also be the special values :ENTRY and :EXIT,
367 ;;; which stand for the entry and exit nodes of the block respectively.
368 (defun cursor (&key (block (current-block))
369 (before nil before-p)
371 (when (boundary-block-p block)
372 (error "Invalid cursor on special entry/exit basic block."))
373 ;; Handle special values :ENTRY and :EXIT.
374 (flet ((node-designator (x)
376 (:entry (block-entry block))
377 (:exit (block-exit block))
379 (setq before (node-designator before))
380 (setq after (node-designator after)))
381 (let* ((next (or before (and after (node-next after)) (block-exit block)))
382 (cursor (make-cursor :block block :next next)))
383 (flet ((out-of-range-cursor ()
384 (error "Out of range cursor."))
386 (error "Ambiguous cursor specified between two non-adjacent nodes.")))
387 (when (conditional-p (node-prev next))
388 (error "Invalid cursor after conditional node."))
389 (when (or (null next) (block-entry-p next))
390 (out-of-range-cursor))
391 (when (and before-p after-p (not (eq after before)))
393 (do-nodes-backward (node block (out-of-range-cursor) :include-sentinel-p t)
394 (when (eq next node) (return))))
397 ;;; Accept a cursor specification just as described in `cursor'
398 ;;; describing a position in the IR and modify destructively the
399 ;;; current cursor to point there.
400 (defun set-cursor (&rest cursor-spec)
401 (let ((newcursor (apply #'cursor cursor-spec)))
402 (setf (cursor-block *cursor*) (cursor-block newcursor))
403 (setf (cursor-next *cursor*) (cursor-next newcursor))
406 ;;; Insert NODE at cursor.
407 (defun insert-node (node &optional (cursor *cursor*))
408 (link-nodes (node-prev (cursor-next cursor)) node)
409 (link-nodes node (cursor-next cursor))
412 ;;; Split the block at CURSOR. The cursor will point to the end of the
413 ;;; first basic block. Return the three basic blocks as multiple
415 (defun split-block (&optional (cursor *cursor*))
416 ;; <aaaaa|zzzzz> ==> <aaaaa|>--<zzzzz>
417 (let* ((block (cursor-block cursor))
418 (newexit (make-block-exit))
419 (newentry (make-block-entry))
420 (exit (block-exit block))
421 (newblock (make-block :entry newentry
424 :succ (block-succ block)
425 :component *component*)))
426 (insert-node newexit)
427 (insert-node newentry)
428 (setf (node-next newexit) nil)
429 (setf (node-prev newentry) nil)
430 (setf (block-exit block) newexit)
431 (setf (block-succ block) (list newblock))
432 (dolist (succ (block-succ newblock))
433 (setf (block-pred succ) (substitute newblock block (block-pred succ))))
434 (set-cursor :block block :before newexit)
435 (push newblock (component-blocks *component*))
438 ;;; Split the block at CURSOR if it is in the middle of it. The cursor
439 ;;; will point to the end of the first basic block. Return the three
440 ;;; basic blocks as multiple values.
441 (defun maybe-split-block (&optional (cursor *cursor*))
442 ;; If we are converting IR into the end of the basic block, it's
443 ;; fine, we don't need to do anything.
444 (unless (block-exit-p (cursor-next cursor))
445 (split-block cursor)))
448 ;;;; Lexical environment
450 ;;;; It keeps an association between names and the IR entities. It is
451 ;;;; used to guide the translation from the Lisp source code to the
452 ;;;; intermediate representation.
455 name namespace type value)
457 (defvar *lexenv* nil)
459 (defun find-binding (name namespace)
461 (and (eq (binding-name b) name)
462 (eq (binding-namespace b) namespace)))
465 (defun push-binding (name namespace value &optional type)
466 (push (make-binding :name name
475 ;;;; This code covers the translation from Lisp source code to the
476 ;;;; intermediate representation. The main entry point function to do
477 ;;;; that is the `ir-convert' function, which dispatches to IR
478 ;;;; translators. This function ss intended to do the initial
479 ;;;; conversion as well as insert new IR code during optimizations.
481 ;;; A alist of IR translator functions.
482 (defvar *ir-translator* nil)
484 ;;; Define a IR translator for NAME. LAMBDA-LIST is used to
485 ;;; destructure the arguments of the form. Calling the local function
486 ;;; `result-lvar' you can get the LVAR where the compilation of the
487 ;;; expression should store the result of the evaluation.
489 ;;; The cursor is granted to be at the end of a basic block with a
490 ;;; unique successor, and so it should be when the translator returns.
491 (defmacro define-ir-translator (name lambda-list &body body)
492 (check-type name symbol)
493 (let ((fname (intern (format nil "IR-CONVERT-~a" (string name)))))
494 (with-gensyms (result form)
496 (defun ,fname (,form ,result)
497 (flet ((result-lvar () ,result))
498 (declare (ignorable (function result-lvar)))
499 (destructuring-bind ,lambda-list ,form
501 (push (cons ',name #',fname) *ir-translator*)))))
503 ;;; Return the unique successor of the current block. If it is not
504 ;;; unique signal an error.
506 (unlist (block-succ (current-block))))
508 ;;; Set the next block of the current one.
509 (defun (setf next-block) (new-value)
510 (let ((block (current-block)))
511 (dolist (succ (block-succ block))
512 (setf (block-pred succ) (remove block (block-pred succ))))
513 (setf (block-succ block) (list new-value))
514 (push block (block-pred new-value))
517 (defun ir-convert-constant (form result)
518 (let* ((leaf (make-constant :value form)))
519 (insert-node (make-ref :leaf leaf :lvar result))))
521 (define-ir-translator quote (form)
522 (ir-convert-constant form (result-lvar)))
524 (define-ir-translator setq (variable value)
525 (let ((b (find-binding variable 'variable)))
528 (let ((var (make-var :name variable))
529 (value-lvar (make-lvar)))
530 (ir-convert value value-lvar)
531 (let ((assign (make-assignment :variable var :value value-lvar :lvar (result-lvar))))
532 (insert-node assign))))
534 (ir-convert `(set ',variable ,value) (result-lvar))))))
536 (define-ir-translator progn (&body body)
537 (mapc #'ir-convert (butlast body))
538 (ir-convert (car (last body)) (result-lvar)))
540 (define-ir-translator if (test then &optional else)
541 ;; It is the schema of how the basic blocks will look like
544 ;; <aaaaXX> --< >-- <|> -- <zzzz>
547 ;; Note that is important to leave the cursor in an empty basic
548 ;; block, as zzz could be the exit basic block of the component,
549 ;; which is an invalid position for a cursor.
550 (let ((test-lvar (make-lvar))
551 (then-block (make-empty-block))
552 (else-block (make-empty-block))
553 (join-block (make-empty-block)))
554 (ir-convert test test-lvar)
555 (insert-node (make-conditional :test test-lvar :consequent then-block :alternative else-block))
556 (let* ((block (current-block))
557 (tail-block (next-block)))
558 ;; Link together the different created basic blocks.
559 (setf (block-succ block) (list else-block then-block)
560 (block-pred else-block) (list block)
561 (block-pred then-block) (list block)
562 (block-succ then-block) (list join-block)
563 (block-succ else-block) (list join-block)
564 (block-pred join-block) (list else-block then-block)
565 (block-succ join-block) (list tail-block)
566 (block-pred tail-block) (substitute join-block block (block-pred tail-block))))
567 ;; Convert he consequent and alternative forms and update cursor.
568 (ir-convert then (result-lvar) (cursor :block then-block))
569 (ir-convert else (result-lvar) (cursor :block else-block))
570 (set-cursor :block join-block)))
572 (define-ir-translator block (name &body body)
573 (let ((new (split-block)))
574 (push-binding name 'block (cons (next-block) (result-lvar)))
575 (ir-convert `(progn ,@body) (result-lvar))
576 (set-cursor :block new)))
578 (define-ir-translator return-from (name &optional value)
580 (or (find-binding name 'block)
581 (error "Tried to return from unknown block `~S' name" name))))
582 (destructuring-bind (jump-block . lvar)
583 (binding-value binding)
584 (ir-convert value lvar)
585 (setf (next-block) jump-block)
586 ;; This block is really unreachable, even if the following code
587 ;; is labelled in a tagbody, as tagbody will create a new block
588 ;; for each label. However, we have to leave the cursor
589 ;; somewhere to convert new input.
590 (let ((dummy (make-empty-block)))
591 (set-cursor :block dummy)))))
593 (define-ir-translator tagbody (&rest statements)
595 (or (integerp x) (symbolp x))))
596 (let* ((tags (remove-if-not #'go-tag-p statements))
598 ;; Create a chain of basic blocks for the tags, recording each
599 ;; block in a alist in TAG-BLOCKS.
600 (let ((*cursor* *cursor*))
602 (setq *cursor* (cursor :block (split-block)))
603 (push-binding tag 'tag (current-block))
604 (if (assoc tag tag-blocks)
605 (error "Duplicated tag `~S' in tagbody." tag)
606 (push (cons tag (current-block)) tag-blocks))))
607 ;; Convert the statements into the correct block.
608 (dolist (stmt statements)
610 (set-cursor :block (cdr (assoc stmt tag-blocks)))
611 (ir-convert stmt))))))
613 (define-ir-translator go (label)
615 (or (find-binding label 'tag)
616 (error "Unable to jump to the label `~S'" label))))
617 (setf (next-block) (binding-value tag-binding))
618 ;; Unreachable block.
619 (let ((dummy (make-empty-block)))
620 (set-cursor :block dummy))))
623 (defun ir-convert-functoid (result name arguments &rest body)
625 (return-lvar (make-lvar)))
626 (with-component-compilation (name)
627 (ir-convert `(progn ,@body) return-lvar)
629 (setq component *component*))
635 :return-lvar return-lvar)))
636 (push functional (component-functions *component*))
637 (insert-node (make-ref :leaf functional :lvar result)))))
639 (define-ir-translator function (name)
641 (ir-convert `(symbol-function ,name) (result-lvar))
643 ((lambda named-lambda)
644 (let ((desc (cdr name)))
645 (when (eq 'lambda (car name))
647 (apply #'ir-convert-functoid (result-lvar) desc)))
650 (defun ir-convert-var (form result)
651 (let ((binds (find-binding form 'variable)))
653 (insert-node (make-ref :leaf (binding-value binds) :lvar result))
654 (ir-convert `(symbol-value ',form) result))))
656 (defun ir-convert-call (form result)
657 (destructuring-bind (function &rest args) form
658 (let ((func-lvar (make-lvar))
662 (let ((arg-lvar (make-lvar)))
663 (push arg-lvar args-lvars)
664 (ir-convert arg arg-lvar)))
665 (setq args-lvars (reverse args-lvars))
667 (if (find-primitive function)
668 (insert-node (make-primitive-call
669 :function (find-primitive function)
670 :arguments args-lvars
673 (ir-convert `(symbol-function ,function) func-lvar)
674 (insert-node (make-call :function func-lvar
675 :arguments args-lvars
678 ;;; Convert the Lisp expression FORM, it may create new basic
679 ;;; blocks. RESULT is the lvar representing the result of the
680 ;;; computation or null if the value should be discarded. The IR is
681 ;;; inserted at *CURSOR*.
682 (defun ir-convert (form &optional result (*cursor* *cursor*))
683 ;; Rebinding the lexical environment here we make sure that the
684 ;; lexical information introduced by FORM is just available for
686 (let ((*lexenv* *lexenv*))
687 ;; Possibly create additional blocks in order to make sure the
688 ;; cursor is at end the end of a basic block.
694 (ir-convert-var form result))
696 (ir-convert-constant form result))))
698 (destructuring-bind (op &rest args) form
699 (let ((translator (cdr (assoc op *ir-translator*))))
701 (funcall translator args result)
702 (ir-convert-call form result))))))
706 ;;;; IR Normalization
708 ;;;; IR as generated by `ir-convert' or after some transformations is
709 ;;;; not appropiated. Here, we remove unreachable and empty blocks and
710 ;;;; coallesce blocks when it is possible.
712 ;;; Try to coalesce BLOCK with the successor if it is unique and block
713 ;;; is its unique predecessor.
714 (defun maybe-coalesce-block (block)
715 (when (singlep (block-succ block))
716 (let ((succ (first (block-succ block))))
717 (when (and (not (component-exit-p succ)) (singlep (block-pred succ)))
718 (link-nodes (node-prev (block-exit block))
719 (node-next (block-entry succ)))
720 (setf (block-exit block) (block-exit succ))
721 (setf (block-succ block) (block-succ succ))
722 (dolist (next (block-succ succ))
723 (setf (block-pred next) (substitute block succ (block-pred next))))
724 (setf (block-succ succ) nil
725 (block-pred succ) nil)
728 ;;; Normalize a component. This function must be called after a batch
729 ;;; of modifications to the flowgraph of the component to make sure it
730 ;;; is a valid input for the possible optimizations and the backend.
731 (defun ir-normalize (&optional (component *component*))
732 ;; Initialize blocks as unreachables and remove empty basic blocks.
733 (dolist (block (component-blocks component))
734 (setf (block-data block) 'unreachable))
735 ;; Coalesce and mark blocks as reachable.
736 (map-postorder-blocks
738 (maybe-coalesce-block block)
739 (setf (block-data block) 'reachable))
741 (let ((block-list nil))
742 (dolist (block (component-blocks component))
744 ;; If the block is unreachable, but it is predeces a reachable
745 ;; one, then break the link between them. So we discard it
746 ;; from the flowgraph.
747 ((eq (block-data block) 'unreachable)
748 (setf (block-succ block) nil)
749 (dolist (succ (block-succ block))
750 (when (eq (block-data succ) 'reachable)
751 (remove block (block-pred succ)))))
752 ;; Delete empty blocks
753 ((empty-block-p block)
754 (delete-block block))
755 ;; The rest of blocks remain in the component.
757 (push block block-list))))
758 (setf (component-blocks component) block-list))
759 (check-ir-consistency))
764 ;;;; Once IR conversion has been finished. We do some analysis of the
765 ;;;; component to produce information which is useful for both
766 ;;;; optimizations and code generation. Indeed, we provide some
767 ;;;; abstractions to use this information.
769 (defun compute-reverse-post-order (component)
772 (flet ((add-block-to-list (block)
774 (setf (block-order block) (incf count))))
775 (map-postorder-blocks #'add-block-to-list component))
776 (setf (component-reverse-post-order-p component) t)
777 (setf (component-blocks component) output)))
779 ;;; Iterate across blocks in COMPONENT in reverse post order.
780 (defmacro do-blocks-forward ((block component &optional result) &body body)
781 (with-gensyms (g!component)
782 `(let ((,g!component ,component))
783 (dolist (,block (if (component-reverse-post-order-p ,g!component)
784 (component-blocks ,g!component)
785 (error "reverse post order was not computed yet."))
789 ;;; Iterate across blocks in COMPONENT in post order.
790 (defmacro do-blocks-backward ((block component &optional result) &body body)
791 (with-gensyms (g!component)
792 `(let ((,g!component ,component))
793 (dolist (,block (if (component-reverse-post-order-p ,g!component)
794 (reverse (component-blocks ,g!component))
795 (error "reverse post order was not computed yet."))
799 (defun compute-dominators (component)
800 ;; Initialize the dominators of the entry to the component to be
801 ;; empty and the power set of the set of blocks for proper basic
802 ;; blocks in the component.
803 (let ((n (length (component-blocks component))))
804 ;; The component entry special block has not predecessors in the
805 ;; set of (proper) basic blocks.
806 (setf (block-dominators% (component-entry component))
807 (make-array n :element-type 'bit :initial-element 0))
808 (dolist (block (component-blocks component))
809 (setf (block-dominators% block) (make-array n :element-type 'bit :initial-element 1))))
810 ;; Iterate across the blocks in the component removing non domintors
811 ;; until it reaches a fixed point.
813 (iteration 0 (1+ iteration))
817 (do-blocks-forward (block component)
818 (let* ((predecessors (block-pred block)))
819 (bit-and (block-dominators% block) (block-dominators% (first predecessors)) t)
820 (dolist (pred (rest predecessors))
821 (bit-and (block-dominators% block) (block-dominators% pred) t))
822 (setf (aref (block-dominators% block) i) 1)
823 (setf changes (or changes (not (equal (block-dominators% block) (block-dominators% block)))))
826 ;;; Return T if BLOCK1 dominates BLOCK2, else return NIL.
827 (defun dominate-p (block1 block2)
828 (let ((order (block-order block1)))
829 (= 1 (aref (block-dominators% block2) order))))
834 ;;;; This section provides a function `/print' which write a textual
835 ;;;; representation of a component to the standard output. Also, a
836 ;;;; `/ir' macro is provided, which takes a form, convert it to IR and
837 ;;;; then print the component as above. They are useful commands if
838 ;;;; you are hacking the front-end of the compiler.
841 (defun format-block-name (block)
843 ((eq block (unlist (block-succ (component-entry (block-component block)))))
844 (format nil "ENTRY-~a" (component-id (block-component block))))
845 ((component-exit-p block)
846 (format nil "EXIT-~a" (component-id (block-component block))))
848 (format nil "BLOCK ~a" (block-id block)))))
851 (defun print-node (node)
852 (when (node-lvar node)
853 (format t "$~a = " (lvar-id (node-lvar node))))
856 (let ((leaf (ref-leaf node)))
859 (format t "~a" (var-name leaf)))
861 (format t "'~s" (constant-value leaf)))
863 (format t "#<function ~a>" (functional-name leaf))))))
865 (format t "set ~a $~a"
866 (var-name (assignment-variable node))
867 (lvar-id (assignment-value node))))
868 ((primitive-call-p node)
869 (format t "primitive ~a" (primitive-name (primitive-call-function node)))
870 (dolist (arg (primitive-call-arguments node))
871 (format t " $~a" (lvar-id arg))))
873 (format t "call $~a" (lvar-id (call-function node)))
874 (dolist (arg (call-arguments node))
875 (format t " $~a" (lvar-id arg))))
876 ((conditional-p node)
877 (format t "if $~a then ~a else ~a~%"
878 (lvar-id (conditional-test node))
879 (format-block-name (conditional-consequent node))
880 (format-block-name (conditional-alternative node))))
882 (error "`print-node' does not support printing ~S as a node." node)))
885 (defun print-block (block)
886 (write-line (format-block-name block))
887 (do-nodes (node block)
889 (when (singlep (block-succ block))
890 (format t "GO ~a~%~%" (format-block-name (unlist (block-succ block))))))
892 (defun /print (component &optional (stream *standard-output*))
893 (format t ";;; COMPONENT ~a (~a) ~%~%" (component-name component) (component-id component))
894 (let ((*standard-output* stream))
895 (do-blocks-forward (block component)
896 (print-block block)))
897 (format t ";;; END COMPONENT ~a ~%~%" (component-name component))
898 (let ((*standard-output* stream))
899 (dolist (func (component-functions component))
900 (/print (functional-component func)))))
902 ;;; Translate FORM into IR and print a textual repreresentation of the
904 (defun convert-toplevel-and-print (form)
905 (let ((*counter-alist* nil))
906 (with-component-compilation ('toplevel)
907 (ir-convert form (make-lvar :id "out"))
909 (compute-reverse-post-order *component*)
914 `(convert-toplevel-and-print ',form))
920 ;;;; Primitive functions are a set of functions provided by the
921 ;;;; compiler. They cannot usually be written in terms of other
922 ;;;; functions. When the compiler tries to compile a function call, it
923 ;;;; looks for a primitive function firstly, and if it is found and
924 ;;;; the declarations allow it, a primitive call is inserted in the
925 ;;;; IR. The back-end of the compiler knows how to compile primitive
929 (defvar *primitive-function-table* nil)
934 (defmacro define-primitive (name args &body body)
935 (declare (ignore args body))
936 `(push (make-primitive :name ',name)
937 *primitive-function-table*))
939 (defun find-primitive (name)
940 (find name *primitive-function-table* :key #'primitive-name))
942 (define-primitive symbol-function (symbol))
943 (define-primitive symbol-value (symbol))
944 (define-primitive set (symbol value))
945 (define-primitive fset (symbol value))
947 (define-primitive + (&rest numbers))
948 (define-primitive - (number &rest other-numbers))
950 (define-primitive consp (x))
951 (define-primitive cons (x y))
952 (define-primitive car (x))
953 (define-primitive cdr (x))
956 ;;; compiler.lisp ends here