OSDN Git Service

Hand patch: update to github/binutils.
[pf3gnuchains/pf3gnuchains4x.git] / cgen / doc / pmacros.texi
1 @c Copyright (C) 2000, 2009 Red Hat, Inc.
2 @c This file is part of the CGEN manual.
3 @c For copying conditions, see the file cgen.texi.
4
5 @node Preprocessor macros
6 @chapter Preprocessor macros
7 @cindex Preprocessor macros
8 @cindex pmacros
9
10 Preprocessor macros provide a way of simplifying the writing of
11 @file{.cpu} files.
12
13 @menu
14 * Pmacros introduction::   Introduction to pmacros
15 * Defining pmacros::       @code{define-pmacro}
16 * Using pmacros::          Using preprocessor macros
17 * Pmacro expansion::       How pmacros are expanded
18 * Syntactic forms::        Pmacros that defer argument expansion
19 * Default argument values::  Specifying default values of arguments
20 * Multiple result statements::  Using @code{begin}
21 * Symbols and strings::    Symbols and strings
22 * Number utilities::       Manipulating numbers
23 * List utilities::         Manipulating lists
24 * Iteration utilities::    Iterating over lists
25 * Conditional macros::     Conditional execution
26 * Pmacro utilities::       Utilities for using macros
27 * Debugging utilities::    Pmacros to assist debugging
28 * Comparisons::            Comparing things
29 * Arithmetic functions::   Math
30 * Logical functions::      Shifts, bitwise logical functions
31 * Internal use pmacros::   For internal use only
32 @end menu
33
34 @node Pmacros introduction
35 @section Pmacros introduction
36
37 The macro facility provided by CGEN is quite extensive.
38 This is to give @file{.cpu} file writers the freedom to
39 write the file in ways that work for the architecture in question.
40 Not all architectures are best described in the same way.
41
42 The macros are called @samp{pmacros} because the word @samp{macro}
43 has become overloaded.  For clarity, we give them a unique name:
44 @samp{pmacros}.
45
46 One important point to keep in mind regarding pmacros is that
47 when loading @file{.cpu} files all pmacros are expanded and discarded,
48 their only purpose is to simplify writing the @code{dni}s and other
49 elements of the architecture description.
50
51 Therefore, do not try to write RTL as pmacros.
52 You can of course use pmacros to assist in the writing of RTL,
53 but remember that the resulting RTL @emph{cannot} use pmacros.
54 By the time the RTL is processed all pmacros have been expanded
55 and discarded.
56
57 A simple picture may help.
58 Here is a basic diagram of the steps in processing cpu descriptions.
59
60 @example
61          (1) .cpu file
62                 |
63       (2) pmacro expansion
64                 |
65 (3) define-@{insn,operand,etc.@} processing
66                 |
67    (4) instruction set analysis
68                 |
69  (5) application source file generation
70 @end example
71
72 Once CGEN gets to step (3) pmacros no longer exist.
73
74 @node Defining pmacros
75 @section Defining pmacros
76 @cindex define-pmacro
77
78 There are two kinds of macros:
79
80 @itemize @bullet
81 @item function macros
82 @item variable macros
83 @end itemize
84
85 Preprocessor function macros are defined with:
86
87 @smallexample
88 (define-pmacro (name [parm1 parm2 ... parmN])
89   ["optional comment"]
90   expansion
91 )
92 @end smallexample
93
94 @samp{expansion} must be exactly one expression.
95
96 Preprocessor variable macros are just global variables, nothing special.
97 When invoked their value is used in place of their name.
98
99 Variable macros are defined with:
100
101 @smallexample
102 (define-pmacro name
103   ["optional comment"]
104   expansion
105 )
106 @end smallexample
107
108 @node Using pmacros
109 @section Using pmacros
110
111 Functional macros are invoked in either of two ways: positional arguments
112 or specifying arguments by name.
113
114 @smallexample
115 (define-pmacro (foo arg1 arg2) (bar arg1 arg2))
116
117 ;; Invoke by positional arguments.
118
119 (foo abc def) ==> (bar abc def)
120
121 ;; Invoke by naming arguments.
122
123 (foo #:arg1 ghi #:arg2 jkl) ==> (bar ghi jkl)
124 @end smallexample
125
126 Variable macros are invoked simply by specifying their name.
127
128 @smallexample
129 (define-pmacro foo "abc")
130
131 (.str foo "def") ==> "abcdef"
132 @end smallexample
133
134 @node Pmacro expansion
135 @section Pmacro expansion
136
137 Most@footnote{Syntactic form pmacros don't pre-evaluate their arguments.
138 @xref{Syntactic forms}.}
139 function pmacros are expanded by first processing any macros in the invocation,
140 binding the resulting expressions to the pmacro's parameters,
141 processing the pmacro according to its definition, and returning the result.
142 Free variables are left unchanged.@footnote{A "free variable",
143 as defined here, is one that is not already bound, be it to
144 parameter, macro, or local variable within a macro.
145 Note that to pmacros, cpu description file elements like
146 @code{reg}, @code{sequence}, @code{VOID}, etc. are just symbols;
147 they have no special meaning.}
148
149 Variable macros are expanded simply by replacing their name with their value.
150
151 After a pmacro has been expanded, if the result is a symbol that names
152 another pmacro, it is in turn processed.  This happens just once,
153 not repeatedly.@footnote{This behaviour will go away eventually, do not
154 rely on it.}
155
156 Here is a simple example that uses pmacros to simplify the
157 definition of several instructions.
158
159 @smallexample
160 ;; OP1_*,OP2_* are previously defined enums
161 (define-pmacro arithmetic-insns
162   ((add OP2_0) (sub OP2_1) (mul OP2_2) (div OP2_3))
163 )
164 (define-pmacro (make-arith-reg/reg-format opcode)
165   (+ OP1_0 opcode dr sr)
166 )
167 (define-pmacro (make-arith-reg/imm-format opcode)
168   (+ OP1_1 opcode dr sr)
169 )
170 (define-pmacro (define-arith-insn ispec)
171   (begin
172     (dni (.ref ispec 0)
173          (.str (.ref ispec 0) " reg/reg")
174          ()
175          (.str (.ref ispec 0) " $dr,$sr")
176          (make-arith-reg/reg-format (.ref ispec 1))
177          (set dr ((.ref ispec 0) dr sr))
178          ()
179          )
180     (dni (.ref ispec 0)
181          (.str (.ref ispec 0) " reg/imm")
182          ()
183          (.str (.ref ispec 0) " $dr,$imm")
184          (make-arith-reg/imm-format (.ref ispec 1))
185          (set dr ((.ref ispec 0) dr imm))
186          ()
187          )
188   )
189 )
190
191 ;; Create dnis for each kind of instruction.
192 ;; The result of this is:
193 ;; (begin (begin (dni ...) ...) (begin (dni ...) ...) ...)
194 (.splice begin (.unsplice (.map define-arith-insn arithmetic-insns)))
195 @end smallexample
196
197 The @code{.splice}, @code{.unsplice} are necessary to pass properly
198 formed expressions to the @file{.cpu} file reader.
199 If we just used @samp{(.map define-arith-insn arithmetic-insns)}
200 the reader would see @samp{((begin (dni ...) ...) (begin (dni ...) ...))}.
201 Note how the first @code{begin} is nested within a list, and does not
202 appear in the ``top level'' list.
203
204 Another way to accomplish the same thing that doesn't require
205 @code{.splice}, @code{.unsplice} is to use @code{.for-each}, @code{.exec}.
206 @code{.for-each} is only used for its side-effects, it does not
207 return a result.  Therefore, in order to actually cause the
208 @file{.cpu} file reader to see any definitions we need to use
209 @code{.exec} to pass the dnis to the reader.
210
211 @smallexample
212 (define-pmacro (define-arith-insn ispec)
213   (.exec (dni (.ref ispec 0)
214            (.str (.ref ispec 0) " reg/reg")
215            ()
216            (.str (.ref ispec 0) " $dr,$sr")
217            (make-arith-reg/reg-format (.ref ispec 1))
218            (set dr ((.ref ispec 0) dr sr))
219            ()
220            ))
221   (.exec (dni (.ref ispec 0)
222            (.str (.ref ispec 0) " reg/imm")
223            ()
224            (.str (.ref ispec 0) " $dr,$imm")
225            (make-arith-reg/imm-format (.ref ispec 1))
226            (set dr ((.ref ispec 0) dr imm))
227            ()
228            ))
229 )
230 (.for-each define-arith-insn arithmetic-insns)
231 @end smallexample
232
233 @node Syntactic forms
234 @section Syntactic forms
235
236 Some function pmacros are called @samp{syntactic forms}.
237 These pmacros are processed differently in that parameters are
238 @emph{not} evaluated first.  Instead it is up to the pmacro
239 to decide when, and if, the parameters are evaluated.
240
241 The syntactic forms are:
242
243 @itemize @bullet
244
245 @item @code{.pmacro}.
246 @xref{Defining a pmacro inline}.
247 @item @code{.let}, @code{.let*}.
248 @xref{Defining a block of locals}.
249 @item @code{.if}.
250 @xref{Traditional @code{if}}.
251 @item @code{.case}.
252 @xref{Traditional @code{case}}.
253 @item @code{.cond}.
254 @xref{Extended if/elseif/else}.
255 @item @code{.begin}.
256 @xref{A block of statements}.
257 @item @code{.andif}.
258 @xref{.andif}.
259 @item @code{.orif}.
260 @xref{.orif}.
261
262 @end itemize
263
264 The docs for each syntactic pmacro describes when it evaluates its arguments.
265
266 All syntactic form pmacros are pre-defined.
267 The user can not currently define his/her own.
268
269 @node Default argument values
270 @section Default argument values
271
272 Invoking pmacros by specifying argument names allows some, or all,
273 arguments to be elided and thus allows for arguments to have default values.
274
275 Specify default values with the following syntax.
276
277 @smallexample
278 (define-pmacro (macro-name (arg1 . default-value)
279                            (arg2 . default value) ...)
280   ...
281 )
282 @end smallexample
283
284 To invoke a pmacro with default values for some, or all,
285 arguments, you @emph{must} specify arguments by name.
286
287 Example:
288
289 @smallexample
290 (define-pmacro (foo (arg1 . 1) (arg2 . 2))
291   (bar arg1 arg2)
292 )
293
294 (foo #:arg1 4) ==> (bar 4 2)
295
296 (foo 4) ==> ERROR, must invoke pmacro by specifying arguments by name
297 @end smallexample
298
299 @node Multiple result statements
300 @section Multiple result statements
301 @cindex begin
302
303 The result of a preprocessor macro is exactly one expression.
304 It is often useful, however, to return multiple expressions, say for
305 example when you want one macro to define several instructions.
306
307 The way to do this is to enclose all the expressions with @code{begin}.
308 @code{begin} is only valid at the top [definition] level.
309
310 Note that this is @emph{not} the @code{.begin} builtin pmacro.
311 We want to pass a list of statements to the @file{.cpu} file reader,
312 and pmacros have all been evaluated and discarded by this point.
313
314 @node Symbols and strings
315 @section Symbols and strings
316
317 There are several builtin macros for symbol and string manipulation.
318
319 @menu
320 * Symbol concatenation::          The @code{.sym} builtin
321 * String concatenation::          The @code{.str} builtin
322 * Convert a number to a hex::     The @code{.hex} builtin
323 * Convert a string to uppercase:: The @code{.upcase} builtin
324 * Convert a string to lowercase:: The @code{.downcase} builtin
325 * Getting part of a string::      The @code{.substring} builtin
326 * Symbol or string length::       The @code{.length} builtin
327 @end menu
328
329 @node Symbol concatenation
330 @subsection Symbol concatenation
331 @cindex .sym
332
333 Symbol and string concatenation are supported. Symbol concatenation is
334 done with:
335
336 @code{(.sym arg1 arg2 ...)}
337
338 Acceptable arguments are symbols, strings, and numbers.
339 The result is a symbol with the arguments concatenated together.
340 Numbers are converted to a string, base 10, and then to a symbol.
341 The result must be a valid Scheme symbol with the additional restriction
342 that the first character must be a letter.  The resulting symbol
343 is recursively macro-expanded.
344
345 @node String concatenation
346 @subsection String concatenation
347 @cindex .str
348
349 String concatenation is done with
350
351 @code{(.str arg1 arg2 ...)}
352
353 Acceptable arguments are symbols, strings, and numbers.  The result is a
354 string with the arguments concatenated together.
355 Numbers are converted base 10.
356
357 Example:
358
359 @smallexample
360 (define-pmacro (bin-op mnemonic op2-op sem-op)
361   (dni mnemonic
362        (.str mnemonic " reg/reg")
363        ()
364        (.str mnemonic " $dr,$sr")
365        (+ OP1_0 op2-op dr sr)
366        (set dr (sem-op dr sr))
367        ())
368 )
369 (bin-op and OP2_12 and)
370 (bin-op or OP2_14 or)
371 (bin-op xor OP2_13 xor)
372 @end smallexample
373
374 @node Convert a number to a hex
375 @subsection Convert a number to a hex
376 @cindex .hex
377
378 Convert a number to a lowercase hex string with @code{.hex}.  If
379 @code{width} is present, the result is that many characters beginning
380 with the least significant digit.  Zeros are prepended as necessary.
381
382 Syntax: @code{(.hex number [width])}
383
384 Examples:
385
386 @smallexample
387 (.hex 42)   --> "2a"
388 (.hex 42 1) --> "a"
389 (.hex 42 4) --> "002a"
390 @end smallexample
391
392 @node Convert a string to uppercase
393 @subsection Convert a string to uppercase
394 @cindex .upcase
395
396 Convert a string to uppercase with @code{.upcase}.
397
398 Syntax: @code{(.upcase string)}
399
400 Example:
401
402 @smallexample
403 (.upcase "foo!") --> "FOO!"
404 @end smallexample
405
406 @node Convert a string to lowercase
407 @subsection Convert a string to lowercase
408 @cindex .downcase
409
410 Convert a string to lowercase with @code{.downcase}.
411
412 Syntax: @code{(.downcase string)}
413
414 Example:
415
416 @smallexample
417 (.downcase "BAR?") --> "bar?"
418 @end smallexample
419
420 @node Getting part of a string
421 @subsection Getting part of a string
422 @cindex .substring
423
424 Extract a part of a string with @code{.substring}.
425
426 Syntax: @samp{(.substring string start end)}
427
428 where @samp{start} is the starting character, and @samp{end} is one past
429 the ending character.  Character numbering begins at position 0.
430 If @samp{start} and @samp{end} are the same, and both valid, the empty
431 string is returned.
432
433 Example:
434
435 @smallexample
436 (.substring "howzitgoineh?" 2 6) --> "wzit"
437 @end smallexample
438
439 @node Symbol or string length
440 @subsection Symbol or string length
441 @c @cindex .length - the @cindex for this is in the list section
442
443 Compute the length, in characters, of a symbol or string.
444
445 Syntax: @samp{(.length symbol-or-string)}
446
447 Examples:
448
449 @smallexample
450 (.length abc) --> 3
451 (.length "def") --> 3
452 (.length "") --> 0
453 @end smallexample
454
455 @node Number utilities
456 @section Number utilities
457
458 Builtin macros for manipulating numbers.
459
460 @menu
461 * Number generation::             The @code{.iota} builtin
462 @end menu
463
464 @node Number generation
465 @subsection Number generation
466 @cindex .iota
467 @cindex Number generation
468
469 Machine descriptions often require a list of sequential numbers.
470 Generate a list of numbers with the @code{.iota} builtin macro.
471
472 Syntax: @samp{(.iota count [start [incr]])}.
473
474 Examples:
475
476 @smallexample
477 (.iota 5)      --> 0 1 2 3 4
478 (.iota 5 4)    --> 4 5 6 7 8
479 (.iota 5 5 -1) --> 5 4 3 2 1
480 @end smallexample
481
482 @node List utilities
483 @section List utilities
484
485 Builtin macros for maninpulating lists.
486
487 @menu
488 * Creating lists::                The @code{.list} builtin
489 * List splicing::                 The @code{.splice} builtin
490 * Referencing a list element::    The @code{.ref} builtin
491 * List length::                   The @code{.length} builtin
492 * Lists of repeated elements::    The @code{.replicate} builtin
493 * Finding a subset of a list::    The @code{.find} builtin
494 * car/cdr::                       car, cdr, etc. from Scheme/Lisp
495 @end menu
496
497 @node Creating lists
498 @subsection Creating lists
499 @cindex .list
500
501 Lists can be created with the @code{.list} builtin.
502
503 Syntax: @samp{(.list elm1 elm2 ...)}
504
505 It's somewhat redundant as lists can also be created simply writing
506 @samp{(elm1 elm2 ...)}.
507
508 @node List splicing
509 @subsection List splicing
510 @cindex .splice
511
512 Syntax: @samp{(.splice [expr1] [expr2] [(.unsplice list1)]
513               [(.unsplice list2)] [expr3] ...)}
514
515 It is often useful to splice a list into a "parent" list.
516 This is best explained with an example.
517
518 @smallexample
519 (define-pmacro (splice-test a b c)
520                (.splice a (.unsplice b) c))
521 (pmacro-dump (splice-test 1 (2) 3))
522
523 --> (1 2 3)
524 @end smallexample
525
526 Note that a level of parentheses around @code{2} has been removed.
527
528 This is useful, for example, when one wants to pass a list of fields to
529 a macro that defines an instruction.  For example:
530
531 @smallexample
532 (define-pmacro (cond-move-1 name comment mnemonic cc-prefix cc-name cc-opcode
533                             src-name src-opcode cond test)
534   (dni name
535        (.str "move %" cc-name " " comment ", v9 page 191")
536        ((MACH64))
537        (.str mnemonic " " cc-prefix cc-name ",$" src-name ",$rd")
538        (.splice + OP_2 rd OP3_MOVCC cond
539                 (.unsplice cc-opcode) (.unsplice src-opcode))
540        (if (test cc-name)
541            (set rd src-name))
542        ())
543 )
544 @end smallexample
545
546 This macro, taken from @file{sparc64.cpu}, defines a conditional move
547 instruction. Arguments @code{cc-opcode} and @code{src-opcode} are lists
548 of fields. The macro is invoked with (simplified from @file{sparc64.cpu}):
549
550 @smallexample
551 (cond-move-1 mova-icc "blah ..." mova
552              "%" icc ((f-fmt4-cc2 1) (f-fmt4-cc1-0 0))
553              rs2 ((f-i 0) (f-fmt4-res10-6 0) rs2)
554              CC_A test-always)
555 (cond-move-1 mova-imm-icc "blah ..." mova
556              "%" icc ((f-fmt4-cc2 1) (f-fmt4-cc1-0 0))
557              simm11 ((f-i 1) simm11)
558              CC_A test-always)
559 @end smallexample
560
561 Macro @code{cond-move-1} is being used here to define both the register
562 and the immediate value case.  Each case has a slightly different list
563 of opcode fields.  Without the use of @code{.splice}/@code{.unsplice},
564 the resulting formats would be:
565
566 @smallexample
567 (+ OP_2 rd OP3_MOVCC CC_A ((f-fmt4-cc2-1) (f-fmt4-cc1-0 0))
568    ((f-i 0) (f-fmt4-res10-6 0) rs2))
569
570 and
571
572 (+ OP_2 rd OP3_MOVCC CC_A ((f-fmt4-cc2-1) (f-fmt4-cc1-0 0))
573    ((f-i 1) simm11))
574 @end smallexample
575
576 respectively.  This is not what is wanted.  What is wanted is
577
578 @smallexample
579 (+ OP_2 rd OP3_MOVCC CC_A (f-fmt4-cc2-1) (f-fmt4-cc1-0 0)
580    (f-i 0) (f-fmt4-res10-6 0) rs2)
581
582 and
583
584 (+ OP_2 rd OP3_MOVCC CC_A (f-fmt4-cc2-1) (f-fmt4-cc1-0 0)
585    (f-i 1) simm11)
586 @end smallexample
587
588 respectively, which is what @code{.splice} achieves.
589
590 @code{.unsplice} is a special reserved symbol that is only recognized inside
591 @code{.splice}.  There can be any number of @code{.unsplice} expressions
592 in a @code{.splice} but they all must be at the ``top level''.
593
594 I.e. this is not supported:
595 @samp{(.splice 1 (2 3 (.unsplice (4 5))))}.
596
597 Note that @code{.splice} without any @code{.unsplice} expressions
598 behaves identically to @code{.list}.
599
600 Also note that the arguments to @code{.splice} and @code{.unsplice} are
601 evaluted first.  Any macro invocations are first expanded, and then
602 @code{.unsplice} is processed.
603
604 @node Referencing a list element
605 @subsection Referencing a list element
606 @cindex .ref
607
608 Reference elements of a list with @code{.ref}.
609
610 Syntax: @samp{(.ref list element-number)}
611
612 Example:
613
614 @smallexample
615 (.ref (1 2 3) 1) --> 2
616 @end smallexample
617
618 @node List length
619 @subsection List length
620 @cindex .length
621
622 The length of a list is computed with @code{.length}.
623
624 Syntax: @samp{(.length list)}.
625
626 Example:
627
628 @smallexample
629 (.length (1 2 3)) --> 3
630 @end smallexample
631
632 @node Lists of repeated elements
633 @subsection Lists of repeated elements
634 @cindex .replicate
635
636 Create a list of repeated elements with @code{.replicate}.
637
638 Syntax: @samp{(.replicate n expr)}
639
640 Example:
641
642 @smallexample
643 (.replicate 4 5) --> (5 5 5 5)
644 @end smallexample
645
646 @node Finding a subset of a list
647 @subsection Finding a subset of a list
648 @cindex .find
649
650 Compute a subset of a list matching a specified predicate with @code{.find}.
651
652 Syntax: @samp{(.find predicate list)}
653
654 Example:
655
656 @smallexample
657 (.find (.pmacro (n) (.lt n 2)) (.iota 4)) --> (0 1)
658 @end smallexample
659
660 @node car/cdr
661 @subsection car/cdr
662 @cindex .car
663 @cindex .cdr
664 @cindex .caar
665 @cindex .cadr
666 @cindex .cdar
667 @cindex .cddr
668
669 CGEN provides a small set of pmacros for those familiar with
670 Scheme/Lisp lists.
671
672 @itemize @bullet
673 @item car
674
675 Equivalent to @samp{(.ref list 0)}.
676
677 Example:
678
679 @smallexample
680 (.car (1 2 3)) --> 1
681 @end smallexample
682
683 @item cdr
684
685 Return all elements of the list after the first one.
686
687 Example:
688
689 @smallexample
690 (.cdr (1 2 3)) --> (2 3)
691 @end smallexample
692
693 @item caar
694
695 Return the first element of the first element of the list.
696
697 I.e., the @code{car} of the @code{car} of the list.
698
699 Example:
700
701 @smallexample
702 (.caar ((1 2 3) (4 5 6))) --> 1
703 @end smallexample
704
705 @item cadr
706
707 Return the second element of the list.
708
709 I.e., the @code{car} of the @code{cdr} of the list.
710
711 Example:
712
713 @smallexample
714 (.cadr (1 2 3)) --> 2
715 @end smallexample
716
717 @item cdar
718
719 Return all elements after the first element of the first element of the list.
720 That's a bit of a mouthful, it's easier to understand by applying
721 @code{car} and @code{cdr} in turn.
722
723 I.e., the @code{cdr} of the @code{car} of the list.
724
725 Example:
726
727 @smallexample
728 (.cadr ((1 2 3) (4 5 6))) --> (2 3)
729 @end smallexample
730
731 @item cddr
732
733 I.e., the @code{cdr} of the @code{cdr} of the list.
734
735 Return all elements of the list after the first two.
736
737 Example:
738
739 @smallexample
740 (.cddr (1 2 3)) --> (3)
741 @end smallexample
742
743 @end itemize
744
745 @node Iteration utilities
746 @section Iteration utilities
747
748 Macros for iterating over lists
749
750 @menu
751 * Mapping a macro over a list::   The @code{.map} builtin
752 * Iterating over a list::         The @code{.for-each} builtin
753 @end menu
754
755 @node Mapping a macro over a list
756 @subsection Mapping a macro over a list
757 @cindex .map
758
759 Apply a macro to each element of a list, or set of lists, with @code{.map}.
760 The order in which each element of the list is processed is unspecified.
761
762 The syntax is @samp{(.map macro-name list1 [list2 ...])}.
763 @samp{macro} must take as many arguments as there are lists.
764
765 The result is a list with @samp{macro} applied to each element of
766 @samp{listN}.  This is often useful in constructing enum and register name lists.
767
768 Example:
769
770 @smallexample
771 (define-pmacro (foo name number) ((.sym X name) number))
772 (.map foo (A B C D E) (.iota 5))
773
774 -->
775
776 ((XA 0) (XB 1) (XC 2) (XD 3) (XE 4))
777 @end smallexample
778
779 @node Iterating over a list
780 @subsection Iterating over a list
781 @cindex .for-each
782
783 Apply a macro to each element of a list, or set of lists,
784 with @code{.for-each}.
785 Each element of the list is guaranteed to be processed in order.
786
787 The syntax is @samp{(.for-each macro list1 [list2 ...])}.
788 @samp{macro} must take as many arguments as there are lists.
789
790 There is no result, or rather the result is always the empty list ().
791 Note that this macro is therefore useless for macro expansion.
792 It's purpose is to process @code{macro} for its side-effects.
793 The @code{.exec} builtin pmacro is useful here.
794
795 @node Conditional macros
796 @section Conditional macros
797
798 Macros for conditional execution.
799
800 @menu
801 * Traditional @code{if}::         The @code{.if} builtin
802 * Traditional @code{case}::       The @code{.case} builtin
803 * Extended if/elseif/else::       The @code{.cond} builtin
804 @end menu
805
806 @node Traditional @code{if}
807 @subsection Traditional @code{if}
808 @cindex .if
809
810 Syntax: @samp{(.if condition then-expr [else-expr])}.
811
812 The @code{condition} is evaluated, and if it is non-#f then
813 @code{then-expr} is evaluated and returned.
814 Otherwise, if @code{else-expr} is present it is evaluated and returned.
815 Otherwise, the empty list @code{()} is returned.
816
817 @node Traditional @code{case}
818 @subsection Traditional @code{case}
819 @cindex .case
820
821 Syntax: @samp{(.case expr ((case1-list) expr-list) [case-list] [(else expr-list)])}
822
823 The expression @code{expr} is evaluated, and then
824 each case list is examined in turn to look for a match.
825 The first case list with an element that matches @code{expr} wins,
826 its @code{expr-list} is evaluated and the result of the last expression
827 in the expression list is returned.
828
829 If there is no successful match and no @code{else} part,
830 then the empty list @code{()} is returned.
831
832 @node Extended if/elseif/else
833 @subsection Extended if/elseif/else
834 @cindex .cond
835
836 Syntax: @samp{(.cond (expr1 expr-list) [cond-list] [(else expr-list)])}
837
838 Each condition's expression is evaluated in turn.
839 The first condition to evaluate to non-#f wins,
840 its @code{expr-list} is evaluated and the result of the last expression
841 in the expression list is returned.
842
843 If there is no successful condition and no @code{else} part,
844 then the empty list @code{()} is returned.
845
846 @node Pmacro utilities
847 @section Pmacro utilities
848
849 Pmacros for working with pmacros.
850
851 @menu
852 * Re-evaluating an expression::      The @code{.eval} builtin
853 * Immediate execution of a command:: The @code{.exec} builtin
854 * Applying a pmacro to a list::      The @code{.apply} builtin
855 * Defining a pmacro inline::         The @code{.pmacro} builtin
856 * Passing pmacros as arguments::     Passing a pmacro to another pmacro
857 * Defining a block of locals::       The @code{.let}, @code{.let*} builtins
858 * A block of statements::            The @code{.begin} builtin
859 * Testing if something is a pmacro:: The @code{.pmacro?} builtin
860 @end menu
861
862 @node Re-evaluating an expression
863 @subsection Re-evaluating an expression
864 @cindex .eval
865
866 Syntax: @samp{(.eval expr)}
867
868 Sometimes one wishes to build up an expression in non-trivial ways
869 and then have the expression evaluated.
870 Use the @code{.eval} builtin pmacro for this purpose,
871 it re-evaluates @samp{expr}, invoking any pmacros contained therein.
872
873 A perhaps contrived example is when one wants to construct the pmacro's
874 name from a set of parameters.
875
876 Example:
877
878 @smallexample
879 (define-pmacro (do-foo a b) (foo a b))
880 (define-pmacro (do-bar a b) (bar a b))
881 (define-pmacro (doer what a b) (.eval (.list (.sym do- what) a b)))
882 (doer foo 1 2) ;; --> (foo 1 2)
883 (doer bar 3 4) ;; --> (bar 3 4)
884 @end smallexample
885
886 @node Immediate execution of a command
887 @subsection Immediate execution of a command
888 @cindex .exec
889
890 Syntax: @samp{(.exec expr)}
891
892 Sometimes one wishes to pass an expression to the @file{.cpu} file reader
893 immediately, rather than waiting for it to process the expression
894 that is the result of a pmacro.  This typically happens with the
895 @code{.for-each} builtin pmacro.
896 Use the @code{.exec} builtin pmacro for this purpose.
897 It immediately passes @samp{expr} to the @file{.cpu} file reader
898 for processing and returns @code{()} as a result.
899
900 @node Applying a pmacro to a list
901 @subsection Applying a pmacro to a list
902 @cindex .apply
903
904 Invoke a macro with each argument coming from an element of a list,
905 with @code{.apply}.
906
907 The syntax is @samp{(.apply macro-name list)}.
908
909 The result is the result of invoking macro @samp{macro-name}.
910 @samp{macro-name} should take as many arguments as there elements in
911 @samp{list}.  If @samp{macro-name} takes a variable number of trailing
912 arguments, there must be at least as many list elements as there are
913 fixed arguments.
914 @c clumsily worded or what
915
916 Example:
917 @c need a more useful example
918
919 Example:
920
921 @smallexample
922 (.apply .str (.iota 5)) --> "01234"
923 @end smallexample
924
925 Note that @code{(.str (.iota 5))} is an error.  Here the list
926 @samp{(0 1 2 3 4)} is passed as the first argument of @code{.str},
927 which is wrong.
928
929 @node Defining a pmacro inline
930 @subsection Defining a pmacro inline
931 @cindex .pmacro
932
933 Define a macro inline with @code{.pmacro}.
934 This is only supported when passing macros as arguments to other macros,
935 and as values for local variables in @code{.let} or @code{.let*}.
936
937 Example:
938
939 @smallexample
940 (define-pmacro (load-op suffix op2-op mode ext-op)
941   (begin
942     (dni (.sym ld suffix) (.str "ld" suffix)
943          ()
944          (.str "ld" suffix " $dr,@@$sr")
945          (+ OP1_2 op2-op dr sr)
946          (set dr (ext-op WI (mem mode sr)))
947          ())
948   )
949 )
950
951 (load-op "" OP2_12 WI (.pmacro (mode expr) expr))
952 (load-op b OP2_8 QI (.pmacro (mode expr) (ext mode expr)))
953 (load-op h OP2_10 HI (.pmacro (mode expr) (ext mode expr)))
954 (load-op ub OP2_9 QI (.pmacro (mode expr) (zext mode expr)))
955 (load-op uh OP2_11 HI (.pmacro (mode expr) (zext mode expr)))
956 @end smallexample
957
958 .pmacro's bind the same way Scheme lambda expressions do.
959 In the following example, arg2 in the second pmacro is bound
960 to the arg2 argument of the outer pmacro.
961
962 @smallexample
963 (define-pmacro (foo arg1 arg2) ((.pmacro (bar) (+ arg2 bar)) arg1))
964 (foo 3 4) ==> (+ 4 3)
965 @end smallexample
966
967 The contents of a @code{.pmacro} are not evaluated until the pmacro
968 is invoked.
969
970 @node Passing pmacros as arguments
971 @subsection Passing pmacros as arguments
972
973 Macros may be passed to other macros.
974
975 Example:
976
977 @smallexample
978 (define-pmacro (no-ext-expr mode expr) expr)
979 (define-pmacro (ext-expr mode expr) (ext mode expr))
980 (define-pmacro (zext-expr mode expr) (zext mode expr))
981
982 (define-pmacro (load-op suffix op2-op mode ext-op)
983   (begin
984     (dni (.sym ld suffix) (.str "ld" suffix)
985          ()
986          (.str "ld" suffix " $dr,@@$sr")
987          (+ OP1_2 op2-op dr sr)
988          (set dr (ext-op WI (mem mode sr)))
989          ())
990   )
991 )
992
993 (load-op "" OP2_12 WI no-ext-expr)
994 (load-op b OP2_8 QI ext-expr)
995 (load-op h OP2_10 HI ext-expr)
996 (load-op ub OP2_9 QI zext-expr)
997 (load-op uh OP2_11 HI zext-expr)
998 @end smallexample
999
1000 @node Defining a block of locals
1001 @subsection Defining a block of locals
1002 @cindex .let
1003 @cindex .let*
1004
1005 It is often handy to assign expressions to local variables,
1006 if only to improve readability.
1007 This is accomplished with the @code{.let} and @code{.let*} builtin pmacros.
1008
1009 @code{.let} and @code{.let*} have the same syntax:
1010
1011     @samp{(.let local-list expr1 [expr2 ...])}
1012
1013     @samp{(.let* local-list expr1 [expr2 ...])}
1014
1015 where @samp{local-list} is a list of local variable assignments,
1016 with the syntax @samp{(name expr)}.  All variable names must be distinct.
1017
1018 The difference is that in @code{.let} all expressions of all locals
1019 are evaluated @emph{first} and @emph{then} assigned to the locals,
1020 whereas in @code{.let*} each local is evaluated and assigned in turn.
1021 This means that expressions in @code{.let} cannot refer to other locals
1022 in the @code{.let}.  If they do, they will get the values the variables had
1023 before the @code{.let}.  Also remember that symbols in pmacros are
1024 ``self-quoting'', so if a symbol isn't bound to any value, its value is
1025 the symbol name.
1026
1027 Example:
1028
1029 @smallexample
1030 (define-pmacro (load-op suffix op2-op mode ext-op)
1031   (.let (
1032          (no-ext-expr (.pmacro (mode expr) expr))
1033          (ext-expr (.pmacro (mode expr) (ext mode expr)))
1034          (zext-expr (.pmacro (mode expr) (zext mode expr)))
1035         )
1036     (begin
1037       (dni (.sym ld suffix) (.str "ld" suffix)
1038            ()
1039            (.str "ld" suffix " $dr,@@$sr")
1040            (+ OP1_2 op2-op dr sr)
1041            (set dr (ext-op WI (mem mode sr)))
1042            ())
1043     )
1044   )
1045 )
1046
1047 (load-op "" OP2_12 WI no-ext-expr)
1048 (load-op b OP2_8 QI ext-expr)
1049 (load-op h OP2_10 HI ext-expr)
1050 (load-op ub OP2_9 QI zext-expr)
1051 (load-op uh OP2_11 HI zext-expr)
1052 @end smallexample
1053
1054 Note that one can also assign pmacros to local variables.
1055
1056 Note that @code{.let*} is equivalent to a set of nested @code{.let}
1057 expressions:
1058
1059 @smallexample
1060 (.let* ((x 1) (y x)) y)
1061 ;; is equivalent to
1062 (.let ((x 1)) (.let ((y x)) y))
1063 @end smallexample
1064
1065 @node A block of statements
1066 @subsection A block of statements
1067 @cindex .begin
1068
1069 Sometimes one wishes to have a list of expressions (or statements)
1070 and the context only allows one expression.
1071 This can happen, for example, in the @samp{then} and @samp{else}
1072 clauses of the @code{.if} builtin pmacro.
1073 Use the @code{.begin} builtin pmacro for these situations.
1074
1075 Syntax: @samp{(.begin [expr1 [expr2 ...]])}
1076
1077 Each expression is evaluated in turn and the result is the result
1078 of the last expression.
1079
1080 @node Testing if something is a pmacro
1081 @subsection Testing if something is a pmacro
1082 @cindex .pmacro?
1083
1084 Sometimes one wishes to know if an argument is a pmacro or not.
1085 This is useful when one is writing a pmacro that has a parameter
1086 that is either a pmacro or is not (e.g., it could be an rtl function
1087 instead).  When the parameter is a pmacro one might like to @samp{.apply}
1088 it to another argument, and if not one might like to simply construct
1089 a list of it and the other argument.
1090
1091 Syntax: @samp{(.pmacro? arg)}
1092
1093 Example:
1094
1095 @smallexample
1096 (define-pmacro (compare a b) (if (eq a b) 1 0))
1097 (define-pmacro (maybe-apply fun args)
1098   (.if (.pmacro? fun)
1099        (.apply fun args)
1100        (.splice fun (.unsplice args))))
1101 (define-pmacro (gen-semantics semfun args)
1102   (set dest (maybe-apply semfun args)))
1103 (gen-semantics add (op1 op2))) ;; ==> (set dest (add op1 op2))
1104 (gen-semantics compare (op1 op2))) ;; ==> (set dest (if (eq op1 op2) 1 0))
1105 @end smallexample
1106
1107 @node Debugging utilities
1108 @section Debugging utilities
1109
1110 @menu
1111 * .print::     Printing a diagnostic message
1112 * .dump::      Printing arbitrarily complex objects
1113 * .error::     Signalling an error has occurred
1114 @end menu
1115
1116 @node .print
1117 @subsection .print
1118 @cindex .print
1119
1120 Syntax: @samp{(.print expr1 [...])}
1121
1122 Evaluate and print the supplied expressions.
1123 This is useful for debugging and logging messages.
1124
1125 NOTE: Strings are printed without enclosing quotes.
1126 Use @code{dump} if you want to print strings with enclosing quotes.
1127
1128 The result is the empty list @code{()}.
1129
1130 @node .dump
1131 @subsection .dump
1132 @cindex .dump
1133
1134 Syntax: @samp{(.dump expr1 [...])}
1135
1136 Evaluate and print the supplied expressions.
1137 This is useful for debugging and logging messages.
1138
1139 NOTE: Strings are printed with enclosing quotes.
1140 Use @code{print} if you want to print strings without enclosing quotes.
1141
1142 The result is the empty list @code{()}.
1143
1144 @node .error
1145 @subsection .error
1146 @cindex .error
1147
1148 Syntax: @samp{(.error expr1 [...])}
1149
1150 Evaluate the supplied expressions and signal an error.
1151 The expressions are typically error messages, often with the
1152 object that caused the error.
1153
1154 @node Comparisons
1155 @section Comparisons
1156
1157 Builtin macros for comparing objects.
1158
1159 In CGEN ``true'' is represented by @code{#t}
1160 and ``false'' is represented by @code{#f}.
1161
1162 @menu
1163 * .equal?::      Deep comparison
1164 * .andif::       && in C
1165 * .orif::        || in C
1166 * .not::         ! in C
1167 * .eq::          Shallow comparison
1168 * .ne::          Shallow comparison
1169 * .lt::          Less than
1170 * .gt::          Greater than
1171 * .le::          Less than or equal to
1172 * .ge::          Greater than or equal to
1173 @end menu
1174
1175 @node .equal?
1176 @subsection .equal?
1177 @cindex .equal?
1178
1179 Syntax: @samp{(.equal? x y)}
1180
1181 Return #t if @code{x} is equal to @code{y}, otherwise #f.
1182
1183 A ``deep'' comparison is used.
1184 I.e., if @code{x} and @code{y} are lists, list elements
1185 are recursively compared
1186
1187 Examples:
1188
1189 @smallexample
1190 (.equal? "abc" "abc") --> #t
1191 (.equal? symbol1 symbol1) --> #t
1192 (.equal? ((1 2 3) (4 5 6)) ((1 2 3) (4 5 6))) --> #t
1193 @end smallexample
1194
1195 @node .andif
1196 @subsection .andif
1197 @cindex .andif
1198
1199 Syntax: @samp{(.andif [expr1 [expr2 ...]])}
1200
1201 Each expression is evaluated in turn.
1202 If an expression evaluates to false (@code{#f}) then
1203 evaluation stops and the result is @code{#f}.
1204 If all expressions evaluate to non-@code{#f}, then
1205 the value of the last expression is returned.
1206
1207 Note that this is a special form.
1208 Just like @code{&&} in C, evaluation of subsequent
1209 expressions is not done once an expression is found
1210 that evaluates to ``false''.
1211
1212 Examples:
1213
1214 @smallexample
1215 (.andif 1 #f 2) --> #f
1216 (.andif 1 2 3) --> 3
1217 (.andif) --> #t
1218 @end smallexample
1219
1220 @node .orif
1221 @subsection .orif
1222 @cindex .orif
1223
1224 Syntax: @samp{(.orif [expr1 [expr2 ...]])}
1225
1226 Each expression is evaluated in turn.
1227 If an expression evaluates to non-false (@code{#f}) then
1228 evaluation stops and the result is the value of the first
1229 non-@code{#f} expression.
1230 If all expressions evaluate to @code{#f}, then
1231 the result is @code{#f}.
1232
1233 Note that this is a special form.
1234 Just like @code{||} in C, evaluation of subsequent
1235 expressions is not done once an expression is found
1236 that evaluates to non-``false''.
1237
1238 Examples:
1239
1240 @smallexample
1241 (.orif 1 2 3) --> 1
1242 (.orif #f #f #f) --> #f
1243 (.orif) --> #f
1244 @end smallexample
1245
1246 @node .not
1247 @subsection .not
1248 @cindex .not
1249
1250 Syntax: @samp{(.not expr)}
1251
1252 If @code{expr} is @code{#f} return @code{#t}.
1253 If @code{expr} is non-@code{#f} return @code{#f}.
1254
1255 @emph{Note that (.not 0) is not 1, it is #f!}.
1256
1257 @node .eq
1258 @subsection .eq
1259 @cindex .eq
1260
1261 Syntax: @samp{(.eq x y)}
1262
1263 Return ``true'' if @code{x} equals @code{y}, otherwise ``false''.
1264
1265 Note that this does @emph{not} do a deep comparison,
1266 and can only be used with symbols, strings, and numbers.
1267 Both @code{x} and @code{y} must be the same type.
1268
1269 Examples:
1270
1271 @smallexample
1272 (.eq 1 1) -> #t
1273 (.eq 0 1) -> #f
1274 (.eq 0 one) -> error
1275 (.eq one one) -> #t
1276 (.eq zero one) -> #f
1277 (.eq "abc" "abc") -> #t
1278 (.eq "abc" "def") -> #f
1279 @end smallexample
1280
1281 @node .ne
1282 @subsection .ne
1283 @cindex .ne
1284
1285 Syntax: @samp{(.ne x y)}
1286
1287 Return ``true'' if @code{x} does not equal @code{y}, otherwise ``false''.
1288
1289 Note that this does @emph{not} do a deep comparison,
1290 and can only be used with symbols, strings, and numbers.
1291 Both @code{x} and @code{y} must be the same type.
1292
1293 Examples:
1294
1295 @smallexample
1296 (.ne 1 1) -> #f
1297 (.ne 0 1) -> #t
1298 (.ne 0 one) -> error
1299 (.ne one one) -> #f
1300 (.ne zero one) -> #t
1301 (.ne "abc" "abc") -> #f
1302 (.ne "abc" "def") -> #t
1303 @end smallexample
1304
1305 @node .lt
1306 @subsection .lt
1307 @cindex .lt
1308
1309 Syntax: @samp{(.lt x y)}
1310
1311 Return ``true'' if @code{x} is less than @code{y}, otherwise ``false''.
1312
1313 Both @code{x} and @code{y} must be numbers.
1314
1315 @node .gt
1316 @subsection .gt
1317 @cindex .gt
1318
1319 Syntax: @samp{(.gt x y)}
1320
1321 Return ``true'' if @code{x} is greater than @code{y}, otherwise ``false''.
1322
1323 Both @code{x} and @code{y} must be numbers.
1324
1325 @node .le
1326 @subsection .le
1327 @cindex .le
1328
1329 Syntax: @samp{(.le x y)}
1330
1331 Return ``true'' if @code{x} is less than or equal to @code{y},
1332 otherwise ``false''.
1333
1334 Both @code{x} and @code{y} must be numbers.
1335
1336 @node .ge
1337 @subsection .ge
1338 @cindex .ge
1339
1340 Syntax: @samp{(.ge x y)}
1341
1342 Return ``true'' if @code{x} is greater than or equal to @code{y},
1343 otherwise ``false''.
1344
1345 Both @code{x} and @code{y} must be numbers.
1346
1347 @node Arithmetic functions
1348 @section Arithmetic functions
1349
1350 @menu
1351 * .add::      Addition
1352 * .sub::      Subtraction
1353 * .mul::      Multiplication
1354 * .div::      Integer division
1355 * .rem::      Integer remainder
1356 @end menu
1357
1358 @node .add
1359 @subsection .add
1360 @cindex .add
1361
1362 Syntax: @samp{(.add x y)}
1363
1364 Return @code{x} + @code{y}.
1365
1366 @node .sub
1367 @subsection .sub
1368 @cindex .sub
1369
1370 Syntax: @samp{(.sub x y)}
1371
1372 Return @code{x} - @code{y}.
1373
1374 @node .mul
1375 @subsection .mul
1376 @cindex .mul
1377
1378 Syntax: @samp{(.mul x y)}
1379
1380 Return @code{x} * @code{y}.
1381
1382 @node .div
1383 @subsection .div
1384 @cindex .div
1385
1386 Syntax: @samp{(.div x y)}
1387
1388 Return the quotient of @code{x} divided by @code{y}.
1389
1390 Only integer division is supported,
1391 both @code{x} and @code{y} must be integers.
1392
1393 @node .rem
1394 @subsection .rem
1395 @cindex .rem
1396
1397 Syntax: @samp{(.rem x y)}
1398
1399 Return the remainder of @code{x} divided by @code{y}.
1400
1401 Only integer division is supported,
1402 both @code{x} and @code{y} must be integers.
1403
1404 @c Need to define and document behaviour for negative numbers.
1405
1406 @node Logical functions
1407 @section Logical functions
1408
1409 Builtin macros for shifts and bitwise functions.
1410
1411 @menu
1412 * .sll::       Shift left logical
1413 * .srl::       Shift right logical
1414 * .sra::       Shift right arithmetic
1415 * .and::       Bitwise and
1416 * .or::        Bitwise or
1417 * .xor::       Bitwise exclusive-or
1418 * .inv::       Bitwise inversion
1419 @end menu
1420
1421 @node .sll
1422 @subsection .sll
1423 @cindex .sll
1424
1425 Syntax: @samp{(.sll x n)}
1426
1427 Shift @code{x} left by @code{n} bits.
1428 Zeroes are shifted into the low-order bits.
1429
1430 @code{n} must be a non-negative integer.
1431
1432 @node .srl
1433 @subsection .srl
1434 @cindex .srl
1435
1436 Syntax: @samp{(.srl x n)}
1437
1438 Shift @code{x} right by @code{n} bits.
1439
1440 @code{x} @emph{must} be a non-negative integer.
1441 Numbers at the pmacro level have ``infinite precision'',
1442 and shifting zeroes into the high-order bits of
1443 infinite-precision negative numbers is undefined.
1444
1445 @code{n} must be a non-negative integer.
1446
1447 @node .sra
1448 @subsection .sra
1449 @cindex .sra
1450
1451 Syntax: @samp{(.sra x n)}
1452
1453 Shift @code{x} right arithmetically by @code{n} bits.
1454 The sign bit of @code{x} is shifted into the high-order bits.
1455
1456 @code{n} must be a non-negative integer.
1457
1458 @node .and
1459 @subsection .and
1460 @cindex .and
1461
1462 Syntax: @samp{(.and x y)}
1463
1464 Return the bitwise @code{and} of @code{x} and @code{y}.
1465
1466 @node .or
1467 @subsection .or
1468 @cindex .or
1469
1470 Syntax: @samp{(.or x y)}
1471
1472 Return the bitwise @code{or} of @code{x} and @code{y}.
1473
1474 @node .xor
1475 @subsection .xor
1476 @cindex .xor
1477
1478 Syntax: @samp{(.xor x y)}
1479
1480 Return the bitwise @code{exclusive-or} of @code{x} and @code{y}.
1481
1482 @node .inv
1483 @subsection .inv
1484 @cindex .inv
1485
1486 Syntax: @samp{(.inv x)}
1487
1488 Return the bitwise @code{inversion} of @code{x}.
1489
1490 @node Internal use pmacros
1491 @section Internal use pmacros
1492
1493 This section documents pmacros that are for internal use only.
1494 Today there's only one, @samp{.internal-test}, and it is used
1495 by the testsuite.
1496
1497 @subsection .internal-test
1498 @cindex .internal-test
1499
1500 Syntax: @samp{(.internal-test expr)}
1501
1502 Execute @samp{expr} as a Scheme expression and return #f if the
1503 expression returns #f and return #t if the expression returns non-#f.
1504
1505 This is for use in the CGEN testsuite only.
1506 See the testsuite for usage examples.