Pristine Ack-5.5
[Ack-5.5.git] / doc / cg.doc
1 .\" $Id: cg.doc,v 1.9 1994/06/24 10:01:47 ceriel Exp $
2 .RP
3 .ND Nov 1984
4 .TL
5 The table driven code generator from 
6 .br
7 the Amsterdam Compiler Kit
8 .AU
9 Hans van Staveren
10 .AI
11 Dept. of Mathematics and Computer Science
12 Vrije Universiteit
13 Amsterdam, The Netherlands
14 .AB
15 It is possible to automate the process of compiler building
16 to a great extent using collections of tools.
17 The Amsterdam Compiler Kit is such a collection of tools.
18 This document provides a description of the internal workings
19 of the table driven code generator in the Amsterdam Compiler Kit,
20 and a description of syntax and semantics of the driving table.
21 .PP
22 >>>  NOTE  <<<
23 .br
24 This document pertains to the \fBold\fP code generator.  Refer to the
25 "Second Revised Edition" for the new code generator.
26 .AE
27 .NH 1
28 Introduction
29 .PP
30 Part of the Amsterdam Compiler Kit is a code generator system consisting
31 of a code generator generator (\fIcgg\fP for short) and some machine
32 independent C code.
33 .I Cgg
34 reads a machine description table and creates two files,
35 tables.h and tables.c.
36 These are then used together with other C code to produce
37 a code generator for the machine at hand.
38 .PP
39 This in turn reads compact EM code and produces
40 assembly code.
41 The remainder of this document will first broadly describe
42 the working of the code generator,
43 then a description of the machine table follows after which
44 the internal workings of the code generator will be explained.
45 .PP
46 The reader is assumed to have at least a vague notion about the
47 semantics of the intermediary EM code.
48 Someone wishing to write a table for a new machine
49 should be thoroughly acquainted with EM code
50 and the assembly code of the machine at hand.
51 .NH 1
52 Global overview of the workings of the code generator.
53 .PP
54 The code generator or
55 .I cg
56 tries to generate good code by simulating the runtime stack
57 of the program compiled and delaying emission of code as long
58 as possible.
59 It also keeps track of register contents, which enables it to
60 eliminate redundant moves, and tries to eliminate redundant tests
61 by keeping information about condition code status,
62 if applicable for the machine.
63 .PP
64 .I Cg
65 maintains a `fakestack' containing `tokens' that are built
66 by executing the pseudo code contained in the code rules given
67 by the table writer.
68 One can think of the fakestack as a logical extension of the real
69 stack the program compiled will have when run.
70 During code generation tokens will be kept on the fakestack as long
71 as possible but when they are moved to the real stack,
72 by generating code for the push,
73 all tokens above\u*\d
74 .FS
75 * in the rest of this document the stack is assumed to grow downwards,
76 although the top of the stack will mean the first element that will
77 be popped.
78 .FE
79 the tokens pushed will be pushed also,
80 so that the fakestack will not contain holes.
81 .PP
82 The main loop of
83 .I cg
84 is this:
85 .IP 1)
86 find a pattern of EM instructions starting at the current one to
87 generate code for.
88 This pattern will usually be of length one but longer patterns can be used.
89 .IP 2)
90 Select one of the possibly many stack patterns that go with this
91 EM pattern on the basis of heuristics and/or lookahead.
92 .IP 3)
93 Force the current fakestack contents to match the pattern.
94 This may involve
95 copying tokens to registers, making dummy transformations, e.g. to
96 transform a "local" into an "register offsetted" or might even
97 cause to have the complete fakestack contents put to the real stack
98 and then back into registers if no suitable transformations
99 were provided by the table writer.
100 .IP 4)
101 Execute the pseudocode associated with the code rule just selected,
102 this may cause registers to be allocated,
103 code to be emitted etc..
104 .IP 5)
105 Put tokens onto the fakestack to reflect the result of the operation.
106 .IP 6)
107 Insert some EM instructions into the stream,
108 this is possible but not common.
109 .IP 7)
110 Account for the cost.
111 The cost is kept in a (space, time) vector and lookahead decisions
112 are based on a linear combination of these.
113 .PP
114 The table that drives
115 .I cg
116 is not read in every time,
117 but instead is used at compiletime
118 of
119 .I cg
120 to set parameters and to load pseudocode tables.
121 A program called
122 .I cgg
123 reads the table and produces large lists of numbers that are
124 compiled together with machine independent code to produce
125 a code generator for the machine at hand.
126 .NH 1
127 Description of the machine table
128 .PP
129 The machine description table consists of the following sections:
130 .IP 1)
131 Constant definitions
132 .IP 2)
133 Register definitions
134 .IP 3)
135 Token definitions
136 .IP 4)
137 Token expression definitions
138 .IP 5)
139 Code rules
140 .IP 6)
141 Move definitions
142 .IP 7)
143 Test definitions
144 .IP 8)
145 Stacking definitions
146 .PP
147 Input is in free format, white space and newlines may be used
148 at will to improve legibility.
149 Identifiers used in the table have the same syntax as C identifiers,
150 upper and lower case considered different, all characters significant.
151 There is however one exception:
152 identifiers must be more than one character long for parsing reasons.
153 C style comments are accepted
154 .DS
155         /* this is a comment */
156 .DE
157 and #define macros may be used if the need arises.
158 .NH 2
159 Some constants
160 .PP
161 Before anything else three constants must be defined,
162 all with the syntax NAME=value, value being an integer.
163 These constants are:
164 .IP EM_WSIZE 10
165 Number of bytes in a machine word.
166 This is the number of bytes
167 a simple \fBloc\fP instruction will put on the stack.
168 .IP EM_PSIZE
169 Number of bytes in a pointer.
170 This is the number of bytes
171 a \fBlal\fP instruction will put on the stack.
172 .IP EM_BSIZE
173 Number of bytes in the hole between AB and LB.
174 If the calling sequence just saves PC and LB this
175 size will be twice the pointersize.
176 .PP
177 EM_WSIZE and EM_PSIZE are checked when a program is compiled
178 with the resulting code generator.
179 EM_BSIZE is used by
180 .I cg
181 to add to the offset of instructions dealing with locals
182 having positive offsets,
183 i.e. parameters.
184 .PP
185 Optionally one can give here the factors with which the size and time
186 parts of the cost function have to be multiplied to ensure they have the
187 same order of magnitude.
188 This can be done as
189 .DS
190 TIMEFACTOR = C\d1\u/C\d2\u
191 SIZEFACTOR = C\d3\u/C\d4\u
192 .DE
193 Above numbers must be read as rational numbers.
194 Defaults are 1/1 for both of them.
195 These constants set the default size/time tradeoff in the code generator,
196 so if TIMEFACTOR and SIZEFACTOR are both 1 the code generator will choose
197 at random between two codesequences where one has
198 cost (10,4) and the other has cost (8,6).
199 See also the description of the cost field below.
200 .PP
201 Also optional is the definition of a printformat for integers in the codefile.
202 This is given as
203 .DS
204 FORMAT = string
205 .DE
206 The default for string is "%ld".
207 For example on the PDP 11 one can use
208 .DS
209 FORMAT= "0%lo"
210 .DE
211 to satisfy the old UNIX assembler that reads octal unless followed by
212 a period, and the ACK assembler that follows C conventions.
213 .NH 2
214 Register definition
215 .PP
216 The next part of the tables describes the various registers of the
217 machine and defines identifiers
218 to be used in later parts of the tables.
219 Example for the PDP-11:
220 .DS L
221 REGISTERS:
222 R0 = ( "r0",2), REG.
223 R1 = ( "r1",2), REG, ODDREG.
224 R2 = ( "r2",2), REG.
225 R3 = ( "r3",2), REG, ODDREG.
226 R4 = ( "r4",2), REG.
227 LB = ( "r5",2), LOCALBASE.
228 R01= ( "r0",4,R0,R1), REGPAIR.
229 R23= ( "r2",4,R2,R3), REGPAIR.
230 FR0= ( "r0",4), FREG.
231 FR1= ( "r1",4), FREG.
232 FR2= ( "r2",4), FREG.
233 FR3= ( "r3",4), FREG.
234 DR0= ( "r0",8,FR0), DREG.
235 DR1= ( "r1",8,FR1), DREG.
236 DR2= ( "r2",8,FR2), DREG.
237 DR3= ( "r3",8,FR3), DREG.
238 .DE
239 .PP
240 The identifier before the '=' sign is the name of the register
241 as used further on in the table.
242 The string is the name of the register as far as the assembler is concerned.
243 The number is the size of the register in bytes.
244 Identifiers following the number but within the parentheses are previously
245 defined registernames that are contained in the register being defined.
246 The identifiers following the closing parenthesis are properties
247 of the register.
248 So for example R23 is a register with assembler name r2, 4 bytes long,
249 contains the registers R2 and R3 and has the property REGPAIR.
250 .PP
251 It might seem wise to list each and every property of a register,
252 so one might give R0 the extra property MFPTREG named after the not
253 too well known MFPT instruction on newer PDP-11 types,
254 but this is not a good idea.
255 Every extra property means the registerset is more unorthogonal
256 and 
257 .I cg
258 execution time is influenced by that,
259 because it has to take into account a larger set of registers
260 that are not equivalent.
261 .PP
262 There is a predefined property SCRATCH that is dynamic,
263 i.e. a register can have the property SCRATCH one time,
264 and loose it the next.
265 A register has the property SCRATCH when it has a reference count of one.
266 One needs to be able to discriminate between SCRATCH registers
267 and others,
268 because it is only allowed to do arithmetic on
269 SCRATCH registers.
270 .NH 2
271 Stack token definition
272 .PP
273 The next part describes all possible tokens that can reside on
274 the fakestack during code generation.
275 Attributes of a token are described in the form of a C struct declaration,
276 this is followed by the size in bytes of the token,
277 optionally followed by the cost of the token when used as an addressing mode
278 and the format
279 to be used on output.
280 .PP
281 Tokens should usually be declared for every addressing mode
282 of the machine at hand and for every size directly usable in
283 a machine instruction.
284 Example for the PDP-11 (incomplete):
285 .DS L
286 TOKENS:
287 IREG2 =         { REGISTER reg; } 2 "*%[reg]" /* indirect register */
288 REGCONST =      { REGISTER reg; STRING off; } 2 /* not really addressable */
289 REGOFF2 =       { REGISTER reg; STRING off; } 2 "%[off](%[reg])"
290 IREGOFF2 =      { REGISTER reg; STRING off; } 2 "*%[off](%[reg])"
291 CONST =         { INT off; } 2 cost=(2,850) "$%[off]."
292 EXTERN2 =       { STRING off; } 2 "%[off]"
293 IEXTERN2 =      { STRING off; } 2 "*%[off]"
294 PAIRSIGNED =    { REGISTER regeven,regodd; } 2 "%[regeven]"
295 .DE
296 .PP
297 Types allowed in the struct are REGISTER, INT and STRING.
298 Tokens without a printformat should never be output.
299 .PP
300 Notice that tokens need not correspond to addressing modes,
301 the REGCONST token listed above,
302 meaning the sum of the contents of the register and the constant,
303 has no corresponding addressing mode on the PDP-11,
304 but is included so that a sequence of add constant, load indirect,
305 can be handled efficiently.
306 This REGCONST token is needed as part of the path
307 .DS
308 REGISTER -> REGCONST -> REGOFF
309 .DE
310 of which the first and the last "exist" and the middle is needed
311 only as an intermediate step.
312 .NH 2
313 Token expressions
314 .PP
315 Usually machines have certain collections of addressing modes that
316 can be used with certain instructions.
317 The stack patterns in the table are lists of these collections
318 and since it is cumbersome to write out these long lists
319 every time, there is a section here to give names to these
320 collections.
321 Please note that it is not forbidden to write out a token expression
322 in the remainder of the table,
323 but for clarity it is usually better not to.
324 Example for the PDP-11 (incomplete):
325 .DS L
326 TOKENEXPRESSIONS:
327 SOURCE2 = REG + IREG2 + REGOFF2 + IREGOFF2 + CONST + EXTERN2 +
328           IEXTERN2
329 SREG    = REG * SCRATCH
330 .DE
331 Permissible in the expressions are all PASCAL set operators, i.e.
332 .IP +
333 set union
334 .IP -
335 set difference
336 .IP *
337 set intersection
338 .PP
339 Every tokenidentifier is also a token expression identifier
340 denoting the singleton collection of tokens containing
341 just itself.
342 Every register property as defined above is also a token expression
343 matching all registers with that property when on the fakestack.
344 The standard token expression identifier ALL denotes the collection of 
345 all tokens.
346 .NH 2
347 Expressions
348 .PP
349 Throughout the rest of the table expressions can be used in some
350 places.
351 This section will give the syntax and semantics of expressions.
352 There are four types of expressions: integer, string, register and undefined.
353 Type checking is performed by
354 .I cgg .
355 An operator with at least one undefined operand returns undefined except
356 for the defined() function mentioned below.
357 An undefined expression is interpreted as FALSE when it is needed
358 as a truth value.
359 Basic terms in an expression are
360 .IP number 16
361 A number is a constant of type integer.
362 .IP "string"
363 A string within double quotes is a constant of type string.
364 All the normal C style escapes may be used within the string.
365 .IP REGIDENT
366 The name of a register is a constant of type register.
367 .IP $\fIi\fP
368 A dollarsign followed by a number is the representation of the argument
369 of EM instruction \fI\fP.
370 The type of the operand is dependent on the instruction,
371 sometimes it is integer,
372 sometimes it is string.
373 It is undefined when the instruction has no operand.
374 .br
375 Although an exhaustive list could be given describing all the types
376 the following rule of thumb will suffice.
377 If it is unimaginable for the operand of the instruction ever to be
378 something different from a plain integer, the type is integer,
379 otherwise it is string.
380 .br
381 .I Cg
382 makes all necessary conversions,
383 like adding EM_BSIZE to positive arguments of instructions
384 dealing with locals,
385 prepending underlines to global names,
386 converting codelabels into a unique representation etc.
387 Details about this can be found in the section about
388 machine dependent C code.
389 .IP %[1]
390 This in general means the token mentioned first in the
391 stack pattern.
392 When used inside an expression the token must be a simple register.
393 Type of this is register.
394 .IP %[1.off]
395 This means field "off" of the first stack pattern token.
396 Type is the same as that of field "off".
397 To use this expression implies a check that all tokens
398 in the token expression used have the same attributes.
399 .IP %[1.1]
400 This is the first subregister of the first token.
401 Previous comments apply.
402 .IP %[b]
403 The second allocated register.
404 .IP %[a.2]
405 The second subregister of the first allocated register.
406 .PP
407 All normal C operators apply to integers,
408 the + operator serves for string concatenation
409 and register expressions can only be compared to each other.
410 Furthermore there are some special "functions":
411 .IP tostring(e) 16
412 Converts an integer expression e to a string.
413 .IP defined(e)
414 Returns 1 if expression e is defined, 0 otherwise.
415 .IP samesign(e1,e2)
416 Returns 1 if integer expression e1 and e2 have the same sign.
417 .IP sfit(e1,e2)
418 Returns 1 if integer expression e1 fits as a signed integer
419 into a field of e2 bits, 0 otherwise.
420 .IP ufit(e1,e2)
421 Same as above but now for unsigned e1.
422 .IP rom(a,n)
423 Integer expression giving the n'th argument from the \fBrom\fP descriptor
424 pointed at by the a'th EM instruction.
425 Undefined if that descriptor does not exist.
426 .IP loww(a)
427 Returns the lower half of the argument of the a'th EM instruction.
428 This is used to split the arguments of a \fBldc\fP instruction.
429 .IP highw(a)
430 Same for upper half.
431 .NH 2
432 Code rules
433 .PP
434 The largest section of the tables consists of the code generation rules.
435 They specify EM patterns, stack patterns, code to be generated etc.
436 Syntax is
437 .DS L
438 code rule : EM pattern '|' stack pattern '|' code '|' 
439            stack replacement '|' EM replacement '|' cost ;
440 .DE
441 All parts are optional, however there must be at least one pattern present.
442 If the empattern is missing the rule becomes a rewriting rule or
443 .I coercion
444 to be used when code generation cannot continue 
445 because of an invalid stack pattern.
446 The code rules are preceded by the word
447 .DS
448 CODE:
449 .DE
450 The next paragraphs describe the various parts in detail.
451 .NH 3
452 The EM pattern
453 .PP
454 The EM pattern consists of a list of EM mnemonics followed
455 by a boolean expression.
456 Examples:
457 .DS
458 \fBloe\fP
459 .DE
460 will match a single \fBloe\fP instruction,
461 .DS
462 \fBloc\fP \fBloc\fP \fBcif\fP $1==2 && $2==8
463 .DE
464 is a pattern that will match
465 .DS
466 \fBloc\fP 2
467 \fBloc\fP 8
468 \fBcif\fP
469 .DE
470 and
471 .DS
472 \fBlol\fP \fBinc\fP \fBstl\fP $1==$3
473 .DE
474 will match for example
475 .DS
476 .ta 10m 20m 30m 40m 50m 60m
477 \fBlol\fP 6     \fBlol\fP -2            \fBlol\fP 4
478 \fBinc\fP       \fBinc\fP       but \fInot\fP   \fBinc\fP
479 \fBstl\fP 6     \fBstl\fP -2            \fBstl\fP -4
480 .DE
481 A missing boolean expression evaluates to TRUE.
482 .PP
483 When the EM pattern is the same as in the previous code rule the pattern
484 should be given as `...'.
485 The code generator will match the longest EM pattern on every occasion,
486 if two patterns of the same length match the first in the table will be chosen,
487 while all patterns of length greater than or equal to three are considered
488 to be of the same length.
489 .NH 3
490 The stack pattern
491 .PP
492 The stack pattern is a list of token expressions,
493 usually token expression identifiers for clarity.
494 No boolean expression is allowed here.
495 The first expression is the one that matches the top of the stack.
496 .PP
497 The pattern can be followed by the word STACK
498 in which case the pattern only matches if there is nothing
499 else on the fakestack.
500 The code generator will stack everything not matched at the start
501 of the rule.
502 .PP
503 The pattern can be preceded with the word
504 .DS
505 nocoercions:
506 .DE
507 which tells the code generator not to try to coerce to the pattern
508 but only to use it when it is already there.
509 There are two reasons for this construction,
510 correctness and speed.
511 It is needed for correctness when the pattern contains a register
512 that is not transparent when data is moved through it.
513 .PP
514 Example: on the PDP-11 the shortest code for
515 .DS
516 \fBlae\fP a
517 \fBloi\fP 8
518 \fBlae\fP b
519 \fBsti\fP 8
520 .DE
521 is
522 .DS
523 movf _a,fr0
524 movf fr0,_b
525 .DE
526 assuming that the floating point processor is in double
527 precision mode and fr0 is free.
528 Unfortunately this is not correct since a trap can occur on certain
529 kinds of data.
530 This could happen if there was a pattern for \fBsti\fP\ 8 that allowed
531 one to move a floating point register not preceded by nocoercions: .
532 The code generator would then find that moving the 8-byte global _a
533 to a floating point register and then storing it to _b was the cheapest,
534 assuming that the space/time knob was turned far enough to space.
535 It is unfortunate that the type information is no longer present,
536 since if _a really is a floating point number the move could be
537 made without error.
538 .PP
539 The second reason for the nocoercions: construct is speed.
540 When the code generator has a long list of possible stack patterns
541 for one EM pattern it can waste a lot of time trying to find coercions
542 to all of them, while the mere presence of such a long list
543 indicates that the table writer has given a lot of special cases.
544 In this case prepending all the special cases by nocoercions:
545 will stop the code generator from trying to find things there aren't.
546 .NH 3
547 The code part
548 .PP
549 The code part consists of three parts, stack cleanup, register allocation
550 and code to generate.
551 All of these may be omitted.
552 .NH 4
553 Stack cleanup
554 .PP
555 The stack cleanup part describes certain stacktokens that should neither remain on
556 the fakestack, nor remembered as contents of registers.
557 This is usually only required with store operations.
558 The entire fakestack, except for the part matched in the stack pattern,
559 is searched for tokens matching the expression and they are copied
560 to the real stack.
561 Every register that contains the stacktoken is marked as empty.
562 .PP
563 Syntax is
564 .DS
565 remove(token expression) \fIor\fP
566 remove(token expression, boolean expression)
567 .DE
568 Example:
569 .DS
570 remove(REGOFF2,%[reg] != LB || %[off] == $1)
571 .DE
572 is part of a remove() call for use in the \fBstl\fP code rule.
573 It removes all register offsetted tokens where the register is not the
574 localbase plus the local wherein the store is done.
575 The necessity for this can be seen from the following example:
576 .DS
577 \fBlol\fP 4
578 \fBinl\fP 4
579 \fBstl\fP 6
580 .DE
581 Without a proper remove() call in the rule for \fBinl\fP code would
582 be generated as here
583 .DS
584 inc 4(r5)
585 mov 4(r5),6(r5)
586 .DE
587 so local 6 would be given the new value of local 4 instead of the old
588 as the EM code prescribed.
589 .PP
590 When generating something like a branch instruction it 
591 might be needed to empty the fakestack completely.
592 This can of course be done with
593 .DS
594 remove(ALL)
595 .DE
596 .NH 4
597 Register allocation
598 .PP
599 The register allocation part describes the kind of registers needed.
600 Syntax for allocate() is
601 .DS
602 allocate(itemlist)
603 .DE
604 where itemlist is a list of three kinds of things:
605 .IP 1)
606 a tokendescription, for example %[1].
607 .br
608 This will instruct the code generator to temporarily decrement the reference count 
609 of all registers contained in the token,
610 so that they are available for allocation in this allocate() call
611 if they were only used in that token.
612 See example below.
613 .IP 2)
614 a register property.
615 .br
616 This will allocate a register with that property.
617 The register will be marked as empty at this point.
618 Lookahead will be performed if necessary.
619 .IP 3)
620 a register property with initialization.
621 .br
622 This will allocate the register as in 2) but will also
623 initialize it.
624 This eases the task of the code generator because it can
625 find a register already filled with the right value
626 if it exists.
627 .PP
628 Examples:
629 .DS
630 allocate(OREG)
631 .DE
632 will allocate an odd register, while 
633 .DS
634 allocate(REG={REGOFF2,LB,$1})
635 .DE
636 will allocate a register while simultaneously filling it with
637 the asked value.
638 .br
639 Inside the coercion from SOURCE2 to REGISTER in the PDP-11 table
640 the following allocate() can be found.
641 .DS
642 allocate(%[1],REG=%[1])
643 .DE
644 This tells the code generator that registers contained in %[1] can be used
645 again and asks to fill the register allocated with %[1].
646 So if %[1]={REGOFF2,R3,"4"} and R3 has a reference count of 1
647 the following code might be generated.
648 .DS
649 mov 4(r3),r3
650 .DE
651 In the rest of the line the registers allocated can be named by
652 %[a] and %[b.1],%[b.2], i.e. with lower case letters
653 in order of allocation.
654 .PP
655 Warning: 
656 .DS
657 allocate(R3)
658 .DE
659 is \fRnot\fP the way to allocate R3.
660 R3 is not a register property, so it will be seen as a token description
661 and the effect is that R3 will have its reference count decremented.
662 .NH 4
663 Code
664 .PP
665 Code to be generated is specified as a list of items of the following kind:
666 .IP 1)
667 a string in double quotes ("This is a string").
668 .br
669 This is copied to the codefile and a newline ( \en ) is appended.
670 Inside the string all normal C string conventions are allowed,
671 and substitutions can be made of the following sorts.
672 .RS
673 .IP a)
674 $1, $2 etc.
675 These are the operands of the corresponding EM instructions
676 and are printed according to their type.
677 To put a real '$' inside the string it must be doubled ('$$').
678 .IP b)
679 %[1], %[2.reg], %[b.1] etc.
680 These have their obvious meaning.
681 If they describe a complete token ( %[1] )
682 the printformat for the token is used.
683 If they stand for a basic term in an expression
684 they will be printed according to their type.
685 To put a real '%' inside the string it must be doubled ('%%').
686 .IP c)
687 %( arbitrary expression %).
688 This allows inclusion of arbitrary expressions inside strings.
689 Usually not needed very often,
690 so that the awkward notation is not too bad.
691 Note that %(%[1]%) is equivalent to %[1].
692 .RE
693 .IP 2)
694 a move() call.
695 This has the following syntax:
696 .DS
697 move(token description, token description)
698 .DE
699 Moves are handled specially since that enables the code generator
700 to keep track of register contents.
701 Example:
702 .DS
703 move(R3,{REGOFF2,LB,$1})
704 .DE
705 will generate code to move R3 to $1(r5) except when
706 R3 already was a copy of $1(r5).
707 Then the code will be omitted.
708 The rules describing how to move things to each other
709 can be found in the MOVES section described below.
710 .IP 3)
711 an erase() call.
712 This has the following syntax:
713 .DS
714 erase(register expression)
715 .DE
716 This tells the code generator that the register mentioned no longer has any
717 useful value.
718 This is 
719 .I necessary
720 after code in the table has changed the contents of registers.
721 For example, after an add to a register the register must be erased,
722 because the contents do no longer match any token.
723 .IP 4)
724 For machines that have condition codes,
725 alas most of them do,
726 there are provisions to remember condition code setting
727 and prevent needless testing.
728 To set the condition code to a token put in the code the following call:
729 .DS
730 test(token)
731 .DE
732 where token can be all of the standard forms that can also be used in move().
733 This will generate a test if the condition codes 
734 were not already set to that token.
735 It is also possible to tell 
736 .I cg
737 that a certain operation, like a preceding add
738 has set the condition codes to some token with the call
739 .DS
740 setcc(token)
741 .DE
742 So a sequence of a setcc and a test on the same token will generate
743 no code. 
744 Another allowed call within the code is
745 .DS
746 samecc
747 .DE
748 which tells the code generator that condition codes were unaffected
749 in this rule.
750 If no setcc or samecc has been given the default is
751 .DS
752 nocc
753 .DE
754 when a piece of code contained strings,
755 which tells the code generator that the condition codes
756 have no useful value any more.
757 .NH 3
758 Stack replacement
759 .PP
760 The stack replacement is a possibly empty list of items to be pushed onto
761 the fakestack. Three kinds of items are possible:
762 .IP 1)
763 An item of the form %[1]. This will push the stacktoken mentioned back
764 onto the stack unchanged.
765 .IP 2)
766 A register expression. This will push the register mentioned
767 onto the fakestack.
768 .IP 3)
769 An item of the form { REGOFF2,%[1.reg],$1 }.
770 This generates a token with tokenidentifier REGOFF2 and attributes 
771 in order of declaration.
772 .PP
773 All tokens matched by the stack pattern at the beginning of the code rule
774 are first removed and their registers deallocated.
775 Items are pushed in the order of appearance.
776 This means that the last item will be on the top of the
777 stack after the push.
778 So if the stack pattern contained two token expressions
779 and they must be pushed back unchanged,
780 they have to be specified as stack replacement
781 .DS
782 %[2] %[1]
783 .DE
784 and not the other way around.
785 .NH 3
786 EM replacement
787 .PP
788 In exceptional cases it might be useful to leave part of an empattern
789 undone.
790 For example, a \fBsdl\fP instruction might be split into two \fBstl\fP instructions
791 when there is no 4-byte quantity on the stack. The emreplacement part allows
792 one to express this.
793 Example:
794 .DS
795 \fBstl\fP $1 \fBstl\fP $1+2
796 .DE
797 The instructions are inserted in the stream so that they can match
798 the first part of a pattern in the next step.
799 Note that since the code generator traverses the EM instructions in a strict
800 linear fashion,
801 it is impossible to let the EM replacement match later parts of a pattern.
802 So if there is a pattern
803 .DS
804 \fBloc\fP \fBstl\fP $1==0
805 .DE
806 and the input is
807 .DS
808 \fBloc\fP 0 \fBsdl\fP 4
809 .DE
810 the \fBloc\fP\ 0 will be processed first,
811 then the \fBsdl\fP might be split into two \fBstl\fP's but the pattern
812 cannot match now.
813 .NH 3
814 Cost
815 .PP
816 The cost field can be specified when there is more than one
817 code rule with the same empattern.
818 If the code generator has a choice between two possibilities
819 to generate code it will choose the cheapest according to
820 the cost field.
821 The cost for a code generation is the sum of the costs
822 of all the coercions needed, plus the cost for freeing
823 registers plus the cost of the code rule itself.
824 .PP
825 The format of the costfield is
826 .DS
827 ( nbytes, time )                or
828 ( nbytes, time ) + %[\fIi\fP]
829 .DE
830 with time in the metric desired, like nanoseconds or states.
831 See constants section above.
832 The %[\fIi\fP] in the second example is used for adding the cost of a certain
833 address mode used in the code generated.
834 This can of course be repeated if desired.
835 The cost of the address mode must then be specified in the token definition
836 section.
837 .NH 3
838 Examples
839 .PP
840 A list of examples for the PDP-11 is given here.
841 Far from being complete it gives examples of most kinds
842 of instructions.
843 .DS L
844 \fBadi\fP $1==2 | SREG,SOURCE2 |
845         "add %[2],%[1]" erase(%[1]) setcc(%[1])
846           | %[1] | | (2,450) + %[2]
847 \&...       | SOURCE2,SREG |
848         "add %[1],%[2]" erase(%[2]) setcc(%[2])
849           | %[2] | | (2,450) + %[1]
850 .DE
851 is an example of the use of the `...' construct
852 and shows how to place erase() and setcc() calls.
853 .DS L
854
855 \fBdvi\fP $1==2 | SOURCE2,SPAIRSIGNED |
856         "div %[1],%[2]" erase(%[2])
857           | %[2.regeven] | |
858
859 \fBcmi\fP \fBtgt\fP $1==2 | SOURCE2,SOURCE2 | allocate(REG={CONST,0})
860         "cmp %[2],%[1];ble 1f;inc %[a];1:" erase(%[a])
861           | %[a] | |
862
863 \fBcal\fP | STACK |
864         "jsr pc,$1" 
865           | | |
866
867 \fBlol\fP | | | { REGOFF2, LB, $1 } | |
868
869 \fBstl\fP | SOURCE2 |
870         remove(REGOFF2,%[off]==$1)
871         move(%[1],{REGOFF2,LB,$1})
872           | | |
873
874 | SOURCE2 |
875         allocate(%[1],REGPAIR)
876         move(%[1],%[a.2])
877         test(%[a.2])
878         "sxt %[a.even]" | { PAIRSIGNED, %[a.1], %[a.2] }| | 
879 .DE
880 This coercion shows how to use the move and test calls.
881 At first one might think that the testcall is unnecessary,
882 since the move will have set the condition codes,
883 but the move may never have been executed
884 if the register already contained the value,
885 in which case it is necessary to do the test.
886 If the move was executed the test will be omitted.
887 .DS L
888 | SOURCE2 | allocate(%[1],REG=%[1]) | %[a] | |
889
890 \fBsdl\fP | SOURCE2 | | %[1] | \fBstl\fP $1 \fBstl\fP $1+2 |
891
892 \fBexg\fP $1==2 | SOURCE2 SOURCE2 | | %[1] %[2] | |
893 .DE
894 This last example again shows the difference in the order
895 of the stack pattern and the stack replacement.
896 .NH 2
897 Move code rules
898 .PP
899 When issuing a move() call as described above or a register allocation
900 with initialization, the code generator has to know which
901 instruction to use for the move.
902 The code will of course only be generated if it cannot be omitted.
903 This is listed in the move section of the tables by giving a list
904 of tuples:
905 .DS
906 ( source, destination, codepart [ , costfield ] )
907 .DE
908 where the square brackets mean the costfield is optional.
909 Example for the PDP-11
910 .DS
911 MOVES:
912 ( CONST %[off]==0 , SOURCE2, "clr %[2]" )
913 ( SOURCE2, SOURCE2, "mov %[1],%[2]" )
914 .DE
915 The moves are scanned from top to bottom,
916 so the first one that matches will be chosen.
917 .NH 2
918 Test code rules
919 .PP
920 When issuing a test() call as described above,
921 the code generator has to know which instruction
922 to use for the test.
923 The code will only be generated if the condition codes
924 were not already set to the token.
925 This is listed in the test section of the tables by giving
926 a list of tuples:
927 .DS
928 ( source, codepart [ , costfield ] )
929 .DE
930 Example for the PDP-11
931 .DS
932 TESTS:
933 ( SOURCE2, "tst %[1]")
934 ( DREG, "tstf %[1]\encfcc")
935 .DE
936 The tests are scanned from top to bottom,
937 so the first one that matches will be chosen.
938 .NH 2
939 Stacking code rules.
940 .PP
941 When the code generator has to stack a token it must know
942 which code to use.
943 Since it must at all times be possible to empty the fakestack
944 even when no registers are free,
945 it is mandatory that all
946 tokens used must have a rule attached for stacking them
947 without using a scratch register.
948 Since however this might be clumsy and 
949 a register might in practice be available
950 it is also possible to give rules
951 which use a register.
952 On the Intel 8086 for example,
953 there is no instruction to push a constant without using a register,
954 and the code needed to do it without, must use global data
955 and as such is very complicated and wasteful of memory and time.
956 It can therefore be left to be used in extreme cases,
957 while in general the constant is pushed through a register.
958 The stacking rules are listed in the stack section of the table as a list
959 of tuples:
960 .DS
961 (source, [ register property ] , codepart [ , costfield ] )
962 .DE
963 Example for the Intel 8086:
964 .DS
965 STACKS:
966 (CONST, REG, move(%[1],%[a]) "push %[a]")
967 (REG ,, "push %[1]")
968 .DE
969 .NH 1
970 The files mach.h and mach.c
971 .PP
972 The table writer must also supply two files containing
973 machine dependent declarations and C code.
974 These files are mach.h and mach.c.
975 .NH 2
976 Types in the code generator
977 .PP
978 Three different types of integer coexist in the code generator
979 and their range depends on the machine at hand.
980 The type 'int' is used for things like labelcounters that won't require
981 more than 16 bits precision.
982 The type 'word' is used among others to assemble datawords and
983 is of type 'long'.
984 The type 'full' is used for addresses and is of type 'long' if
985 EM_WSIZE>2 or EM_PSIZE>2.
986 .PP
987 In macro and function definitions in later paragraphs implicit typing
988 will be used for parameters, that is parameters starting with an 's'
989 will be of type string, and the letters 'i','w','f' will stand for
990 int, word and full respectively.
991 .NH 2
992 Global variables to work with
993 .PP
994 Some global variables are present in the code generator
995 that can be manipulated by the routines in mach.h and mach.c.
996 .LP
997 The declarations are:
998 .DS L
999 .ta 20
1000 FILE *codefile; /* code is emitted on this stream */
1001 word part_word; /* words to be output are put together here */
1002 int part_size;  /* number of bytes already put in part_word */
1003 char str[];     /* Last string read in */
1004 long argval;    /* Last int read and kept */
1005 .DE
1006 .NH 2
1007 Macros in mach.h
1008 .PP
1009 In the file mach.h a collection of macros is defined that have
1010 to do with formatting of assembly code for the machine at hand.
1011 Some of these macros can of course be left undefined in which case the
1012 macro calls are left in the source and will be treated as 
1013 function calls.
1014 These functions can then be defined in \fImach.c\fR.
1015 .PP
1016 The macros to be defined are:
1017 .IP ex_ap(s) 16
1018 Must print the magic incantations that will mark the symbol \fI\fR
1019 to be exported to other modules.
1020 This is the translation of the EM \fBexa\fP and \fBexp\fP instructions.
1021 .IP in_ap(s)
1022 Same to import the symbol.
1023 Translation of \fBina\fP and \fBinp\fP.
1024 .IP newplb(s)
1025 Must print the definition of procedure label \fIs\fR.
1026 If left undefined the newilb() macro is used instead.
1027 .IP newilb(s)
1028 Must print the definition of instruction label \fIs\fR.
1029 .IP newdlb(s)
1030 Must print the definition of data label \fIs\fR.
1031 .IP dlbdlb(s1,s2)
1032 Must define data label
1033 .I s1
1034 to be equal to
1035 .I s2 .
1036 .IP newlbss(s,f)
1037 Must declare a piece of memory initialized to BSS_INIT(see below)
1038 of length 
1039 .I f
1040 and with label
1041 .I s .
1042 .IP cst_fmt
1043 Format to be used when converting constant arguments of
1044 EM instructions to string.
1045 Argument to be formatted will be 'full'.
1046 .IP off_fmt
1047 Format to be used for integer part of label+constant,
1048 argument will be 'full'.
1049 .IP fmt_ilb(ip,il,s)
1050 Must use the numbers 
1051 .I ip
1052 and 
1053 .I il
1054 which are a procedure number
1055 and a label number respectively and copy a string to
1056 .I s
1057 that must be unique for that combination.
1058 This procedure is optional, if it is not given ilb_fmt
1059 must be defined as below.
1060 .IP ilb_fmt
1061 Format to be used for creation of unique instruction labels.
1062 Arguments will be a unique procedure number (int) and the label
1063 number (int).
1064 .IP dlb_fmt
1065 Format to be used for printing numeric data labels.
1066 Argument will be 'int'.
1067 .IP hol_fmt
1068 Format to be used for generation of labels for
1069 space generated by a
1070 .B hol
1071 pseudo.
1072 Argument will be 'int'.
1073 .IP hol_off
1074 Format to be used for printing of the address of an element in
1075 .B hol
1076 space.
1077 Arguments will be the offset in the
1078 .B hol
1079 block (word) and the number of the
1080 .B hol
1081 (int).
1082 .IP con_cst(w)
1083 Must generate output that will assemble into one machineword.
1084 .IP con_ilb(s)
1085 Must generate output that will put the address of the instruction label
1086 into the datastream.
1087 .IP con_dlb(s)
1088 Must generate output that will put the address of the data label
1089 into the datastream.
1090 .IP fmt_id(sf,st)
1091 Must take the string in
1092 .I sf
1093 which is a nonnumeric global label, and transform it into a copy made to
1094 .I st
1095 which will not collide with reserved assembler words and system labels.
1096 This procedure is optional, if it is not given the id_first macro is used
1097 as defined below.
1098 .IP id_first
1099 Must be a character.
1100 This is prepended to all nonnumeric global labels if their length
1101 is shorter than the maximum allowed(currently 8) or if they already
1102 start with that character.
1103 This is to avoid conflicts of user labels with system labels.
1104 .IP BSS_INIT
1105 Must be a constant.
1106 This is the value filled in all the words not initialized explicitly.
1107 This is loader and system dependent.
1108 If omitted no initialization is assumed.
1109 .NH 3
1110 Example mach.h for the PDP-11
1111 .DS L
1112 .ta 8 16 24 32 40 48 56
1113 #define ex_ap(y)        fprintf(codefile,"\et.globl %s\en",y)
1114 #define in_ap(y)        /* nothing */
1115
1116 #define newplb(x)       fprintf(codefile,"%s:\en",x)
1117 #define newilb(x)       fprintf(codefile,"%s:\en",x)
1118 #define newdlb(x)       fprintf(codefile,"%s:\en",x)
1119 #define dlbdlb(x,y)     fprintf(codefile,"%s=%s\en",x,y)
1120 #define newlbss(l,x)    fprintf(codefile,"%s:.=.+%d.\en",l,x);
1121
1122 #define cst_fmt         "$%d."
1123 #define off_fmt         "%d."
1124 #define ilb_fmt         "I%x_%x"
1125 #define dlb_fmt         "_%d"
1126 #define hol_fmt         "hol%d"
1127
1128 #define hol_off         "%ld.+hol%d"
1129
1130 #define con_cst(x)      fprintf(codefile,"%ld.\en",x)
1131 #define con_ilb(x)      fprintf(codefile,"%s\en",x)
1132 #define con_dlb(x)      fprintf(codefile,"%s\en",x)
1133
1134 #define id_first        '_'
1135 #define BSS_INIT        0
1136 .DE
1137 .NH 2
1138 Functions in mach.c
1139 .PP
1140 In mach.c some functions must be supplied,
1141 mostly manipulating data resulting from pseudoinstructions.
1142 The specifications are given here,
1143 implicit typing of parameters as above.
1144 .IP con_part(isz,word) 20
1145 This function must manipulate the globals 
1146 part_word and part_size to append the isz bytes
1147 contained in word to the output stream.
1148 If part_word is full, i.e. part_size==EM_WSIZE
1149 the function part_flush() may be called to empty the buffer.
1150 This is the function that must go through the trouble of
1151 doing byte order in words correct.
1152 .IP con_mult(w_size)
1153 This function must take the string str[] and create an integer
1154 from the string of size w_size and generate code to assemble global
1155 data for that integer.
1156 Only the sizes for which arithmetic is implemented need be
1157 handled,
1158 so if 200-byte integer division is not implemented,
1159 200-byte integer global data do not have to be implemented.
1160 Here one must take care of word order in long integers.
1161 .IP con_float()
1162 This function must generate code to assemble a floating
1163 point number of which the size is contained in argval
1164 and the ASCII representation in str[].
1165 .IP prolog(f_nlocals)
1166 This function is called at the start of every procedure.
1167 Function prolog code must be generated,
1168 and room made for local variables for a total of f_nlocals bytes.
1169 .IP mes(w_mesno)
1170 This function is called when a
1171 .B mes
1172 pseudo is seen that is not handled by the machine independent part.
1173 The example below probably shows all the table writer ever has to know
1174 about that.
1175 .IP segname[]
1176 This is not a function,
1177 but an array of four strings.
1178 These strings are put out whenever the code generator
1179 switches segments.
1180 Segments are SEGTXT, SEGCON, SEGROM and SEGBSS in that order.
1181 .NH 3
1182 Example mach.c for the PDP-11
1183 .PP
1184 As an example of the sort of code expected,
1185 the mach.c for the PDP-11 is presented here.
1186 .DS L
1187 .ta 8 16 24 32 40 48 56 64
1188 /*
1189  * machine dependent back end routines for the PDP-11
1190  */
1191
1192 con_part(sz,w) register sz; word w; {
1193
1194         while (part_size % sz)
1195                 part_size++;
1196         if (part_size == EM_WSIZE)
1197                 part_flush();
1198         if (sz == 1) {
1199                 w &= 0xFF;
1200                 if (part_size)
1201                         w <<= 8;
1202                 part_word |= w;
1203         } else {
1204                 assert(sz == 2);
1205                 part_word = w;
1206         }
1207         part_size += sz;
1208 }
1209
1210 con_mult(sz) word sz; {
1211         long l;
1212
1213         if (sz != 4)
1214                 fatal("bad icon/ucon size");
1215         l = atol(str);
1216         fprintf(codefile,"\et%o;%o\en",(int)(l>>16),(int)l);
1217 }
1218
1219 con_float() {
1220         double f;
1221         register short *p,i;
1222
1223         /*
1224          * This code is correct only when the code generator is
1225          * run on a PDP-11 or VAX-11 since it assumes native
1226          * floating point format is PDP-11 format.
1227          */
1228
1229         if (argval != 4 && argval != 8)
1230                 fatal("bad fcon size");
1231         f = atof(str);
1232         p = (short *) &f;
1233         i = *p++;
1234         if (argval == 8) {
1235                 fprintf(codefile,"\et%o;%o;",i,*p++);
1236                 i = *p++;
1237         }
1238         fprintf(codefile,"\et%o;%o\en",i,*p++);
1239 }
1240
1241 prolog(nlocals) full nlocals; {
1242
1243         fprintf(codefile,"mov r5,-(sp)\enmov sp,r5\en");
1244         if (nlocals == 0)
1245                 return;
1246         if (nlocals == 2)
1247                 fprintf(codefile,"tst -(sp)\en");
1248         else
1249                 fprintf(codefile,"sub $%d.,sp\en",nlocals);
1250 }
1251
1252 mes(type) word type; {
1253         int argt ;
1254
1255         switch ( (int)type ) {
1256         case ms_ext :
1257                 for (;;) {
1258                         switch ( argt=getarg(
1259                             ptyp(sp_cend)|ptyp(sp_pnam)|sym_ptyp) ) {
1260                         case sp_cend :
1261                                 return ;
1262                         default:
1263                                 strarg(argt) ;
1264                                 fprintf(codefile,".globl %s\en",argstr) ;
1265                                 break ;
1266                         }
1267                 }
1268         default :
1269                 while ( getarg(any_ptyp) != sp_cend ) ;
1270                 break ;
1271         }
1272 }
1273
1274 char    *segname[] = {
1275         ".text",        /* SEGTXT */
1276         ".data",        /* SEGCON */
1277         ".data",        /* SEGROM */
1278         ".bss"          /* SEGBSS */
1279 };
1280 .DE
1281 .NH 1
1282 Coercions
1283 .PP
1284 A central part in code generation is taken by the
1285 .I coercions .
1286 It is the responsibility of the table writer to provide
1287 all necessary coercions so that code generation can continue.
1288 The very minimal set of coercions are
1289 the coercions to unstack every token expression,
1290 in combination with the rules to stack every token.
1291 .PP
1292 If these are present the code generator can always make the necessary
1293 transformations by stacking and unstacking.
1294 Of course for codequality it is usually best to provide extra coercions
1295 to prevent this stacking to take place.
1296 .I Cg
1297 discriminates three types of coercions:
1298 .IP 1)
1299 Unstacking coercions.
1300 This category can use the allocate() call in its code.
1301 .IP 2)
1302 Splitting coercions, these are the coercions that split
1303 larger tokens into smaller ones.
1304 .IP 3)
1305 Transforming coercions, these are the coercions that transform
1306 a token into another one of the same size.
1307 This category can use the allocate() call in its code.
1308 .PP
1309 When a stack configuration does not match the stack pattern
1310 .I coercions
1311 are searched for in the following order:
1312 .IP 1)
1313 First tokens are split if necessary to get their sizes right.
1314 .IP 2)
1315 Then transforming coercions are found that will make the pattern match.
1316 .IP 3)
1317 Finally if the stack pattern is longer than the fakestack contents
1318 unstacking coercions will be used to fill up the pattern.
1319 .PP
1320 At any point, when coercions are missing so code generation could not
1321 continue, the offending tokens are stacked.
1322 .NH 1
1323 Internal workings of the code generator.
1324 .NH 2
1325 Description of tables.c and tables.h contents
1326 .PP
1327 In this section the intermediate files will be described 
1328 that are produced by
1329 .I cgg
1330 and compiled with machine independent code to produce a code generator.
1331 .NH 3
1332 Tables.c
1333 .PP
1334 Tables.c contains a large number of initialized array's of all sorts.
1335 Description of each follows:
1336 .br
1337 .in 1i
1338 .ti -0.5i
1339 byte code rules[]
1340 .br
1341 Pseudo code interpreted by the code generator.
1342 Always starts with some opcode followed by operands depending
1343 on the opcode.
1344 Integers in this table are between 0 and 32767 and have a one byte
1345 encoding if between 0 and 127.
1346 .ti -0.5i
1347 char stregclass[]
1348 .br
1349 Number of computed static register class per register.
1350 Two registers are in the same class if they have the same properties
1351 and don't share a common subregister.
1352 .ti -0.5i
1353 struct reginfo machregs[]
1354 .br
1355 Info per register.
1356 Initialized with representation string, size,
1357 members of the register and set of registers affected when this
1358 one is changed.
1359 Also contains room for runtime information,
1360 like contents and reference count.
1361 .ti -0.5i
1362 tkdef_t tokens[]
1363 .br
1364 Information per tokentype.
1365 Initialized with size, cost, type of operands and formatstring.
1366 .ti -0.5i
1367 node_t enodes[]
1368 .br
1369 List of triples representing expressions for the code generator.
1370 .ti -0.5i
1371 string code strings[]
1372 .br
1373 List of strings.
1374 All strings are put in a list and checked for duplication,
1375 so only one copy per string will reside here.
1376 .ti -0.5i
1377 set_t machsets[]
1378 .br
1379 List of token expression sets.
1380 Bit 0 of the set is used for the SCRATCH property of registers,
1381 bit 1 upto NREG are for the corresponding registers
1382 and bit NREG+1 upto the end are for corresponding tokens.
1383 .ti -0.5i
1384 inst_t tokeninstances[]
1385 .br
1386 List of descriptions for building tokens.
1387 Contains type of rule for building one,
1388 plus operands depending on the type.
1389 .ti -0.5i
1390 move_t moves[]
1391 .br
1392 List of move rules.
1393 Contains token expressions for source and destination
1394 plus cost and index for code rule.
1395 .ti -0.5i
1396 byte pattern[]
1397 .br
1398 EM patterns.
1399 This is structured internally as chains of patterns,
1400 each chain pointed at by pathash[].
1401 After each pattern the list of possible code rules is given.
1402 .ti -0.5i
1403 int pathash[256]
1404 .br
1405 Indices into pattern[] for all patterns with a certain low order
1406 byte of the hashing function.
1407 .ti -0.5i
1408 c1_t c1coercs[]
1409 .br
1410 List of rules to stack tokens.
1411 Contains token expressions,
1412 register needed,
1413 cost
1414 and code rule.
1415 .ti -0.5i
1416 c2_t c2coercs[]
1417 .br
1418 List of splitting coercions.
1419 Token expressions,
1420 split factor,
1421 replacements
1422 and code rule.
1423 .ti -0.5i
1424 c3_t c3coercs[]
1425 .br
1426 List of one to one coercions.
1427 Token expressions,
1428 register needed,
1429 replacement
1430 and code rule.
1431 .ti -0.5i
1432 struct reginfo **reglist[]
1433 .br
1434 List of lists of pointers to register information.
1435 For every property the list is here
1436 to find the registers corresponding to it.
1437 .in 0
1438 .NH 3
1439 tables.h
1440 .PP
1441 In tables.h various derived constants for the tables are
1442 given.
1443 They are then used to determine array sizes in the actual code generator,
1444 plus loop termination in some cases.
1445 .NH 2
1446 Other important data structures
1447 .PP
1448 During code generation some other data structures are used
1449 and here is a short description of some of the important ones.
1450 .PP
1451 Tokens are kept in the code generator as a struct consisting of
1452 one integer
1453 .I t_token
1454 which is -1 if the token is a register,
1455 and the number of the token otherwise,
1456 plus an array of
1457 .I TOKENSIZE
1458 unions
1459 .I t_att
1460 of which the first is the register number in case of a register.
1461 .PP
1462 The fakestack is an array of these tokens,
1463 there is a global variable
1464 .I stackheight .
1465 .PP
1466 The results of expressions are kept in a struct
1467 .I result
1468 with elements
1469 .I e_typ ,
1470 giving the type of the expression:
1471 .I EV_INT ,
1472 .I EV_REG
1473 or
1474 .I EV_STR ,
1475 and a union
1476 .I e_v
1477 which contains the real result.
1478 .NH 2
1479 A tour through the sources
1480 .NH 3
1481 codegen.c
1482 .PP
1483 The file codegen.c contains one large function consisting
1484 of one giant switch statement.
1485 It is the interpreter for the code generator pseudo code
1486 as contained in code rules[].
1487 This function can call itself recursively when doing lookahead.
1488 Arguments are:
1489 .IP codep 10
1490 Pointer into code rules, pseudo program counter.
1491 .IP ply
1492 Number of EM pattern lookahead allowed.
1493 .IP toplevel
1494 Boolean telling whether this is the toplevel codegen() or
1495 a deeper incarnation.
1496 .IP costlimit
1497 A cutoff value to limit searches.
1498 If the cost crosses costlimit the incarnation can terminate.
1499 .IP forced
1500 A register number if nonzero.
1501 This is used inside coercions to force the allocate() call to allocate
1502 a register determined by earlier lookahead.
1503 .PP
1504 The instructions inplemented in the switch:
1505 .NH 4
1506 DO_NEXTEM
1507 .PP
1508 Matches the next EM pattern and does lookahead if necessary to find the best
1509 code rule associated with this pattern.
1510 Heuristics are used to determine best code rule when possible.
1511 This is done by calling the distance() function.
1512 .NH 4
1513 DO_COERC
1514 .PP
1515 This sets the code generator in the state to do a from stack coercion.
1516 .NH 4
1517 DO_XMATCH
1518 .PP
1519 This is done when a match no longer has to be checked.
1520 Used when the nocoercions: trick is used in the table.
1521 .NH 4
1522 DO_MATCH
1523 .PP
1524 This is the big one inside this function.
1525 It has the task to transform the contents of the current
1526 fakestack to match the pattern given after it.
1527 .PP
1528 Since the code generator does not know combining coercions,
1529 i.e. there is no way to make a big token out of two smaller ones,
1530 the first thing done is to stack every token that is too small.
1531 After that all tokens too big are split if possible to the right size.
1532 .PP
1533 Next the coercions are sought that would transform tokens in place to
1534 the right one, plus the coercions that would pop tokens of the stack.
1535 Each of those might need a register, so a list of registers is generated
1536 and at the end of looking for coercions the function 
1537 .I tuples()
1538 is called to generate the list of all possible \fIn\fP-tuples,
1539 where 
1540 .I n
1541 equals the number of registers needed.
1542 .PP
1543 Lookahead is now performed if the number of tuples is greater than one.
1544 If no possibility is found within the costlimit,
1545 the fakestack is made smaller by pushing the bottom token,
1546 and this process is repeated until either a way is found or
1547 the fakestack is completely empty and there is still no way
1548 to make the match.
1549 .PP
1550 If there is a way the corresponding coercions are executed
1551 and the code is finished.
1552 .NH 4
1553 DO_REMOVE
1554 .PP
1555 Here the remove() call is executed, all tokens matched by the 
1556 token expression plus boolean expression are pushed.
1557 In the current implementation there is no attempt to move those
1558 tokens to registers, but that is a possible future extension.
1559 .NH 4
1560 DO_DEALLOCATE
1561 .PP
1562 This one temporarily decrements by one the reference count of all registers
1563 contained in the token given as argument.
1564 .NH 4
1565 DO_REALLOCATE
1566 .PP
1567 Here all temporary deallocates are made undone.
1568 .NH 4
1569 DO_ALLOCATE
1570 .PP
1571 This is the part that allocates a register and decides which one to use.
1572 If the
1573 .I forced
1574 argument was given its task is simple,
1575 otherwise some work must be done.
1576 First the list of possible registers is scanned,
1577 all free registers noted and it is noted whether any of those
1578 registers is already
1579 containing the initialization.
1580 If no registers are available some fakestack token is stacked and the
1581 process is repeated.
1582 .PP
1583 After that if an exact match was found, 
1584 the list of registers is reduced to one register matching exactly
1585 out of every register class.
1586 Now lookahead is performed if necessary and the register chosen.
1587 If an initialization was given the corresponding move is performed,
1588 otherwise the register is marked empty.
1589 .NH 4
1590 DO_LOUTPUT
1591 .PP
1592 This prints a string and an expression.
1593 Only done on toplevel.
1594 .NH 4
1595 DO_ROUTPUT
1596 .PP
1597 Prints a string and a new line.
1598 Only on toplevel.
1599 .NH 4
1600 DO_MOVE
1601 .PP
1602 Calls the move() function in the code generator to implement the move()
1603 function in the table.
1604 .NH 4
1605 DO_ERASE
1606 .PP
1607 Marks the register that is its argument as empty.
1608 .NH 4
1609 DO_TOKREPLACE
1610 .PP
1611 This is the token replacement part.
1612 It is also called if there is no token replacement because it has
1613 some other functions as well.
1614 .PP
1615 First the tokens that will be pushed on the fakestack are computed
1616 and stored in a temporary array.
1617 Then the tokens that were matched in this rule are popped
1618 and their embedded registers have their reference count
1619 decremented.
1620 After that the replacement tokens are pushed.
1621 .PP
1622 Finally all registers allocated in this rule have their reference count
1623 decremented.
1624 If they were not pushed on the fakestack they will be available again
1625 in the next code rule.
1626 .NH 4
1627 DO_EMREPLACE
1628 .PP
1629 Places replacement EM instructions back into the instruction stream.
1630 .NH 4
1631 DO_COST
1632 .PP
1633 Accounts for cost as given in the code rule.
1634 .NH 4
1635 DO_RETURN
1636 .PP
1637 Returns from this level of codegen().
1638 Is used at the end of coercions,
1639 move rules etc..
1640 .NH 3
1641 compute.c
1642 .PP
1643 This module computes the various expressions as given
1644 in the enodes[] array.
1645 Nothing very special happens here,
1646 it is just a recursive function computing leaves
1647 of expressions and applying the operator.
1648 .NH 3
1649 equiv.c
1650 .PP
1651 In this module the tuples() function is implemented.
1652 It is given the number of registers needed and
1653 a list of register lists and it constructs a list of tuples
1654 where the \fIn\fP'th register comes from the \fIn\fP'th list.
1655 Before the list is constructed however 
1656 the dynamic register classes are computed.
1657 Two registers are in the same dynamic class if they are in the
1658 same static class and their contents is the same.
1659 .PP
1660 After that the permute() recursive function is called to
1661 generate the list of tuples.
1662 After construction a generated tuple is added to the list
1663 if it is not already pairwise in the same class
1664 or if the register relations are not the same,
1665 i.e. if the first and second register share a common
1666 subregister in one tuple and not in the other they are considered different.
1667 .NH 3
1668 fillem.c
1669 .PP
1670 This is the routine that does the reading of EM instructions
1671 and the handling of pseudos.
1672 The mach.c module provided by the table writer is included
1673 at the end of this module.
1674 The routine fillemlines() is called by nextem() at toplevel
1675 to make sure there are enough instruction to match.
1676 It fills the EM instruction buffer up to 5 places from the end to
1677 keep room for EM replacement instructions,
1678 or up to a pseudo.
1679 .PP
1680 The dopseudo() function performs the function of the pseudo last
1681 encountered.
1682 If the pseudo is a 
1683 .B rom
1684 the corresponding label is saved with the contents of the
1685 .B rom
1686 to be available to the code generator later.
1687 The rest of the routines are small service routines for either
1688 input or data output.
1689 .NH 3
1690 gencode.c
1691 .PP
1692 This module contains routines called by codegen() to generate the real
1693 code to the codefile.
1694 The function gencode() gets a string as argument and copies it to codefile
1695 while processing certain embedded control characters implementing
1696 the $2 and [1.reg] escapes.
1697 The function genexpr() prints the expression given as argument.
1698 It is used to implement the %(\ expr\ %) escape.
1699 The prtoken() function interprets the tokenformat as given in
1700 the tokens[] array.
1701 .NH 3
1702 glosym.c
1703 .PP
1704 This module maintains a list of global symbols that have a 
1705 .B rom
1706 pseudo associated.
1707 There are functions to enter a symbol and to find a symbol.
1708 .NH 3
1709 main.c
1710 .PP
1711 Main routine of the code generator.
1712 Processes arguments and flags.
1713 Flags available are:
1714 .IP -d
1715 Sets debug mode if the code generator was not compiled with
1716 the NDEBUG macro defined.
1717 Debug mode gives very long output on stderr indicating
1718 all steps of the code generation process including nesting
1719 of the codegen() function.
1720 .IP -p\fIn\fP
1721 Sets the lookahead depth to
1722 .I n ,
1723 the
1724 .I p
1725 stands for ply,
1726 a well known word in chess playing programs.
1727 .IP -w\fIn\fP
1728 Sets the weight percentage for size in the cost function to
1729 .I n
1730 percent.
1731 Uses Euclides algorithm to simplify rationals.
1732 .NH 3
1733 move.c
1734 .PP
1735 Function to implement the move() pseudo function in the tables,
1736 register initialization and the setcc and test pseudo functions.
1737 First tests are made to try to prevent the move from really happening.
1738 The condition code register is treated special here.
1739 After that, if there is an after that,
1740 the move rule is found and the code executed.
1741 .NH 3
1742 nextem.c
1743 .PP
1744 The entry point of this module is nextem().
1745 It hashes the next three EM instructions,
1746 and uses the low order byte of the hash
1747 as an index into the array pathash[],
1748 to find a chain of patterns in the array
1749 pattern[],
1750 that are all tried for a match.
1751 .PP
1752 The function trypat() does most of the work
1753 checking patterns.
1754 When a pattern is found to match all instructions
1755 the operands of the instruction are placed into the dollar[] array.
1756 Then the boolean expression is tried.
1757 If it matches the function can return,
1758 leaving the operands still in the dollar[] array,
1759 so later in the code rule they can still be used.
1760 .NH 3
1761 reg.c
1762 .PP
1763 Collection of routines to handle registers.
1764 Reference count routines are here,
1765 chrefcount() and getrefcount(),
1766 plus routines to erase a single register or all of them,
1767 erasereg() and cleanregs().
1768 .PP
1769 If NDEBUG hasn't been defined, here is also the routine that checks
1770 if the reference count kept with the register information is in
1771 agreement with the number of times it occurs on the fakestack.
1772 .NH 3
1773 salloc.c
1774 .PP
1775 Module for string allocation and garbage collection.
1776 Contains entry points myalloc(),
1777 a routine calling malloc() and checking whether room is left,
1778 myfree(), just free(),
1779 popstr() a function called from state.c to free all strings
1780 made since the last saved status.
1781 Furthermore there is salloc() which has the size of the string as parameter
1782 and returns a pointer to the allocated space,
1783 while keeping a copy of the pointer for garbage allocation purposes.
1784 .PP
1785 The function garbage_collect is called from codegen() at toplevel
1786 every now and then,
1787 and checks all places where strings may reside to mark strings
1788 as being in use.
1789 Strings not in use are returned to the pool of free space.
1790 .NH 3
1791 state.c
1792 .PP
1793 Set of routines called to save current status,
1794 restore a previous saved state and to free the room
1795 occupied by a saved state.
1796 A list of structs is kept here to save the state.
1797 If this is not done,
1798 small allocates will take space
1799 from the holes big enough for state saves,
1800 and as a result every new state save will need a new struct.
1801 The code generator runs out of room very rapidly under these conditions.
1802 .NH 3
1803 subr.c
1804 .PP
1805 Random set of leftover routines.
1806 .NH 4
1807 match
1808 .PP
1809 Computes whether a certain token matches a certain token expression.
1810 Just computes a bitnumber according to the algorithm explained with
1811 machsets[],
1812 and tests the bit and the boolean expression if it is there.
1813 .NH 4
1814 instance,cinstance
1815 .PP
1816 These two functions compute a token from a description.
1817 They differ very slight, cinstance() is used to compute
1818 the result of a coercion in a certain context
1819 and therefore has more arguments, which it uses instead of
1820 the global information instance() works on.
1821 .NH 4
1822 eqtoken
1823 .PP
1824 eqtoken computes whether two tokens can be considered identical.
1825 Used to check register contents during moves mainly.
1826 .NH 4
1827 distance
1828 .PP
1829 This is the heuristic function that computes a distance from
1830 the current fakestack contents to the token pattern in the table.
1831 It likes exact matches most, then matches where at least the sizes are correct
1832 and if the sizes are not correct it likes too large sizes more than too
1833 small, since splitting a token is easier than combining one.
1834 .NH 4
1835 split
1836 .PP
1837 This function tries to find a splitting coercion
1838 and executes it immediately when found.
1839 The fakestack is shuffled thoroughly when this happens,
1840 so pieces below the token that must be split are saved first.
1841 .NH 4
1842 docoerc
1843 .PP
1844 This function executes a coercion that was found.
1845 The same shuffling is done, so the top of the stack is again saved.
1846 .NH 4
1847 stackupto
1848 .PP
1849 This function gets a pointer into the fakestack and must stack
1850 every token including the one pointed at up to the bottom of the fakestack.
1851 The first stacking rule possible is used,
1852 so rules using registers must come first.
1853 .NH 4
1854 findcoerc
1855 .PP
1856 Looks for a one to one coercion, if found it returns a pointer
1857 to it and leaves a list of possible registers to use in the global
1858 variable curreglist.
1859 This is used by codegen().
1860 .NH 3
1861 var.c
1862 .PP
1863 Global variables used by more than one module.
1864 External definitions are in extern.h.