3 ;;; Code generation protocol
5 ;;; (c) 2009 Straylight/Edgeware
8 ;;;----- Licensing notice ---------------------------------------------------
10 ;;; This file is part of the Sensble Object Design, an object system for C.
12 ;;; SOD is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
17 ;;; SOD is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
28 ;;;--------------------------------------------------------------------------
33 (export 'format-temporary-name)
34 (defgeneric format-temporary-name (var stream)
36 "Write the name of a temporary variable VAR to STREAM."))
38 (export 'var-in-use-p)
39 (defgeneric var-in-use-p (var)
41 "Answer whether VAR is currently being used. See `with-temporary-var'.")
43 "Non-temporary variables are always in use."
44 (declare (ignore var))
46 (defgeneric (setf var-in-use-p) (value var)
48 "Record whether VAR is currently being used. See `with-temporary-var'."))
52 (export 'temporary-name)
53 (defclass temporary-name ()
54 ((tag :initarg :tag :reader temp-tag))
56 "Base class for temporary variable and argument names."))
58 ;; Important variables.
60 (defparameter *temporary-index* 0
61 "Index for temporary name generation.
63 This is automatically reset to zero before the output functions are
64 invoked to write a file. This way, we can ensure that the same output
65 file is always produced from the same input."
66 ;; FIXME: this is currently a lie. Need some protocol to ensure that this
70 ;; Important temporary names.
72 (export '(*sod-ap* *sod-master-ap*))
73 (defparameter *sod-ap*
74 (make-instance 'temporary-name :tag "sod__ap"))
75 (defparameter *sod-master-ap*
76 (make-instance 'temporary-name :tag "sod__master_ap"))
78 ;;;--------------------------------------------------------------------------
86 "A base class for instructions.
88 An `instruction' is anything which might be useful to string into a code
89 generator. Both statements and expressions map can be represented by
90 trees of instructions. The `definst' macro is a convenient way of
91 defining new instructions.
93 The only important protocol for instructions is output, which is achieved
94 by calling `print-object' with `*print-escape*' nil.
96 This doesn't really do very much, but it acts as a handy marker for
97 instruction subclasses."))
100 (defgeneric inst-metric (inst)
102 "Returns a `metric' describing how complicated INST is.
104 The default metric of an inst node is simply 1; `inst' subclasses
105 generated by `definst' (q.v.) have an automatically generated method which
106 returns one plus the sum of the metrics of the node's children.
108 This isn't intended to be a particularly rigorous definition. Its purpose
109 is to allow code generators to make decisions about inlining or calling
110 code fairly simply.")
112 (declare (ignore inst))
115 ;; Instruction definition.
118 (defmacro definst (code (streamvar) args &body body)
119 "Define an instruction type and describe how to output it.
121 An `inst' can represent any structured piece of output syntax: a
122 statement, expression or declaration, for example. This macro defines the
125 * A class `CODE-inst' to represent the instruction.
127 * Instance slots named after the ARGS, with matching keyword initargs,
128 and `inst-ARG' readers.
130 * A constructor `make-CODE-inst' which accepts the ARGS (in order, not
131 with keywords) as arguments and returns a fresh instance.
133 * A print method, which prints a diagnostic dump if `*print-escape*' is
134 set, or invokes the BODY (with STREAMVAR bound to the output stream)
135 otherwise. The BODY is expected to produce target code at this
138 (let ((inst-var (gensym "INST"))
139 (class-name (symbolicate code '-inst))
140 (keys (mapcar (lambda (arg) (intern (symbol-name arg) :keyword))
143 (defclass ,class-name (inst)
144 ,(mapcar (lambda (arg key)
145 `(,arg :initarg ,key :reader ,(symbolicate 'inst- arg)))
147 (defun ,(symbolicate 'make- code '-inst) (,@args)
148 (make-instance ',class-name ,@(mappend #'list keys args)))
149 (defmethod inst-metric ((,inst-var ,class-name))
150 (with-slots (,@args) ,inst-var
151 (+ 1 ,@(mapcar (lambda (arg) `(inst-metric ,arg)) args))))
152 (defmethod print-object ((,inst-var ,class-name) ,streamvar)
153 (with-slots (,@args) ,inst-var
155 (print-unreadable-object (,inst-var ,streamvar :type t)
156 (format stream "~@<~@{~S ~@_~S~^ ~_~}~:>"
157 ,@(mappend #'list keys args)))
160 ;; Important instruction classes.
162 (export '(block-inst make-block-inst var-inst make-var-inst
163 function-inst make-function-inst set-inst make-set-inst
164 return-inst make-return-inst expr-inst make-expr-inst
165 inst-decls inst-body inst-name inst-type inst-init inst-var
168 (definst var (stream) (name type init)
169 (pprint-c-type type stream name)
171 (format stream " = ~A" init)))
172 (definst set (stream) (var expr)
173 (format stream "~@<~A = ~@_~2I~A;~:>" var expr))
174 (definst return (stream) (expr)
175 (format stream "return~@[ (~A)~];" expr))
176 (definst expr (stream) (expr)
177 (format stream "~A;" expr))
178 (definst block (stream) (decls body)
179 (format stream "{~:@_~@< ~2I~@[~{~A;~:@_~}~:@_~]~{~A~^~:@_~}~:>~:@_}"
181 (definst function (stream) (name type body)
182 (pprint-logical-block (stream nil)
183 (princ "static " stream)
184 (pprint-c-type type stream name)
185 (format stream "~:@_~A~:@_~:@_" body)))
187 ;; Formatting utilities.
189 (defun format-compound-statement* (stream child morep thunk)
190 "Underlying function for `format-compound-statement'."
191 (cond ((typep child 'block-inst)
192 (funcall thunk stream)
193 (write-char #\space stream)
195 (when morep (write-char #\space stream)))
197 (pprint-logical-block (stream nil)
198 (funcall thunk stream)
199 (write-char #\space stream)
200 (pprint-indent :block 2 stream)
201 (pprint-newline :linear stream)
203 (pprint-indent :block 0 stream)
206 (write-char #\space stream)
207 (pprint-newline :linear stream))
209 (pprint-newline :mandatory stream)))))))
211 (export 'format-compound-statement)
212 (defmacro format-compound-statement
213 ((stream child &optional morep) &body body)
214 "Format a compound statement to STREAM.
216 The introductory material is printed by BODY. The CHILD is formatted
217 properly according to whether it's a `block-inst'. If MOREP is true, then
218 allow for more stuff following the child."
219 `(format-compound-statement* ,stream ,child ,morep
220 (lambda (,stream) ,@body)))
222 ;;;--------------------------------------------------------------------------
227 (export 'codegen-functions)
228 (defgeneric codegen-functions (codegen)
230 "Return the list of `function-inst's of completed functions."))
233 (defgeneric ensure-var (codegen name type &optional init)
235 "Add a variable to CODEGEN's list.
237 The variable is called NAME (which should be comparable using `equal' and
238 print to an identifier) and has the given TYPE. If INIT is present and
239 non-nil it is an expression `inst' used to provide the variable with an
242 (export '(emit-inst emit-insts))
243 (defgeneric emit-inst (codegen inst)
245 "Add INST to the end of CODEGEN's list of instructions."))
246 (defgeneric emit-insts (codegen insts)
248 "Add a list of INSTS to the end of CODEGEN's list of instructions.")
249 (:method (codegen insts)
250 (dolist (inst insts) (emit-inst codegen inst))))
252 (export 'codegen-push)
253 (defgeneric codegen-push (codegen)
255 "Pushes the current code generation state onto a stack.
257 The state consists of the accumulated variables and instructions."))
259 (export 'codegen-pop)
260 (defgeneric codegen-pop (codegen)
262 "Pops a saved state off of the CODEGEN's stack.
264 Returns the newly accumulated variables and instructions as lists, as
267 (export 'codegen-add-function)
268 (defgeneric codegen-add-function (codegen function)
270 "Adds a function to CODEGEN's list.
272 Actually, we're not picky: FUNCTION can be any kind of object that you're
273 willing to find in the list returned by `codegen-functions'."))
275 (export 'temporary-var)
276 (defgeneric temporary-var (codegen type)
278 "Return the name of a temporary variable.
280 The temporary variable will have the given TYPE, and will be marked
281 in-use. You should clear the in-use flag explicitly when you've finished
282 with the variable -- or, better, use `with-temporary-var' to do the
283 cleanup automatically."))
285 (export 'codegen-build-function)
286 (defun codegen-build-function (codegen name type vars insts)
287 "Build a function and add it to CODEGEN's list.
289 Returns the function's name."
290 (codegen-add-function codegen
291 (make-function-inst name type
292 (make-block-inst vars insts)))
295 (export 'codegen-pop-block)
296 (defgeneric codegen-pop-block (codegen)
298 "Makes a block (`block-inst') out of the completed code in CODEGEN.")
300 (multiple-value-bind (vars insts) (codegen-pop codegen)
301 (make-block-inst vars insts))))
303 (export 'codegen-pop-function)
304 (defgeneric codegen-pop-function (codegen name type)
306 "Makes a function out of the completed code in CODEGEN.
308 The NAME can be any object you like. The TYPE should be a function type
309 object which includes argument names. The return value is the NAME.")
310 (:method (codegen name type)
311 (multiple-value-bind (vars insts) (codegen-pop codegen)
312 (codegen-build-function codegen name type vars insts))))
314 (export 'with-temporary-var)
315 (defmacro with-temporary-var ((codegen var type) &body body)
316 "Evaluate BODY with VAR bound to a temporary variable name.
318 During BODY, VAR will be marked in-use; when BODY ends, VAR will be marked
319 available for re-use."
320 `(let ((,var (temporary-var ,codegen ,type)))
323 (setf (var-in-use-p ,var) nil))))
325 ;;;--------------------------------------------------------------------------
326 ;;; Code generation idioms.
328 (export 'deliver-expr)
329 (defun deliver-expr (codegen target expr)
330 "Emit code to deliver the value of EXPR to the TARGET.
332 The TARGET may be one of the following.
334 * `:void', indicating that the value is to be discarded. The expression
335 will still be evaluated.
337 * `:void-return', indicating that the value is to be discarded (as for
338 `:void') and furthermore a `return' from the current function should
339 be forced after computing the value.
341 * `:return', indicating that the value is to be returned from the
344 * A variable name, indicating that the value is to be stored in the
347 In the cases of `:return', `:void' and `:void-return' targets, it is valid
348 for EXPR to be nil; this signifies that no computation needs to be
349 performed. Variable-name targets require an expression."
352 (:return (emit-inst codegen (make-return-inst expr)))
353 (:void (when expr (emit-inst codegen (make-expr-inst expr))))
354 (:void-return (when expr (emit-inst codegen (make-expr-inst expr)))
355 (emit-inst codegen (make-return-inst nil)))
356 (t (emit-inst codegen (make-set-inst target expr)))))
358 (export 'convert-stmts)
359 (defun convert-stmts (codegen target type func)
360 "Invoke FUNC to deliver a value to a non-`:return' target.
362 FUNC is a function which accepts a single argument, a non-`:return'
363 target, and generates statements which deliver a value (see
364 `deliver-expr') of the specified TYPE to this target. In general, the
365 generated code will have the form
367 setup instructions...
368 (deliver-expr CODEGEN TARGET (compute value...))
369 cleanup instructions...
371 where the cleanup instructions are essential to the proper working of the
374 The `convert-stmts' function will call FUNC to generate code, and arrange
375 that its value is correctly delivered to TARGET, regardless of what the
376 TARGET is -- i.e., it lifts the restriction to non-`:return' targets. It
377 does this by inventing a new temporary variable."
380 (:return (with-temporary-var (codegen var type)
382 (deliver-expr codegen target var)))
383 (:void-return (funcall func :void)
384 (emit-inst codegen (make-return-inst nil)))
385 (t (funcall func target))))
387 ;;;----- That's all, folks --------------------------------------------------