1 @c Copyright (C) 1999 Free Software Foundation, Inc.
2 @c This is part of the G77 manual.
3 @c For copying conditions, see the file g77.texi.
7 @cindex GNU Fortran Front End (FFE)
9 @cindex @code{g77}, front end
10 @cindex front end, @code{g77}
12 This chapter describes some aspects of the design and implementation
13 of the @code{g77} front end.
14 Much of the information below applies not to current
15 releases of @code{g77},
16 but to the 0.6 rewrite being designed and implemented
19 To find about things that are ``To Be Determined'' or ``To Be Done'',
20 search for the string TBD.
21 If you want to help by working on one or more of these items,
22 email @email{gcc@@gcc.gnu.org}.
23 If you're planning to do more than just research issues and offer comments,
24 see @uref{http://www.gnu.org/software/contribute.html} for steps you might
28 * Overview of Sources::
29 * Overview of Translation Process::
30 * Philosophy of Code Generation::
33 * Transforming Statements::
34 * Transforming Expressions::
35 * Internal Naming Conventions::
38 @node Overview of Sources
39 @section Overview of Sources
41 The current directory layout includes the following:
44 @item @value{srcdir}/gcc/
47 @item @value{srcdir}/gcc/f/
48 GNU Fortran front end sources
50 @item @value{srcdir}/libf2c/
51 @code{libg2c} configuration and @code{g2c.h} file generation
53 @item @value{srcdir}/libf2c/libF77/
54 General support and math portion of @code{libg2c}
56 @item @value{srcdir}/libf2c/libI77/
57 I/O portion of @code{libg2c}
59 @item @value{srcdir}/libf2c/libU77/
60 Additional interfaces to Unix @code{libc} for @code{libg2c}
63 Components of note in @code{g77} are described below.
65 @file{f/} as a whole contains the source for @code{g77},
66 while @file{libf2c/} contains a portion of the separate program
68 Note that the @code{libf2c} code is not part of the program @code{g77},
69 just distributed with it.
71 @file{f/} contains text files that document the Fortran compiler, source
72 files for the GNU Fortran Front End (FFE), and some other stuff.
73 The @code{g77} compiler code is placed in @file{f/} because it,
74 along with its contents,
75 is designed to be a subdirectory of a @code{gcc} source directory,
77 which is structured so that language-specific front ends can be ``dropped
78 in'' as subdirectories.
79 The C++ front end (@code{g++}), is an example of this---it resides in
80 the @file{cp/} subdirectory.
81 Note that the C front end (also referred to as @code{gcc})
82 is an exception to this, as its source files reside
83 in the @file{gcc/} directory itself.
85 @file{libf2c/} contains the run-time libraries for the @code{f2c} program,
86 also used by @code{g77}.
87 These libraries normally referred to collectively as @code{libf2c}.
88 When built as part of @code{g77},
89 @code{libf2c} is installed under the name @code{libg2c} to avoid
90 conflict with any existing version of @code{libf2c},
91 and thus is often referred to as @code{libg2c} when the
92 @code{g77} version is specifically being referred to.
94 The @code{netlib} version of @code{libf2c/}
95 contains two distinct libraries,
96 @code{libF77} and @code{libI77},
97 each in their own subdirectories.
98 In @code{g77}, this distinction is not made,
99 beyond maintaining the subdirectory structure in the source-code tree.
101 @file{libf2c/} is not part of the program @code{g77},
102 just distributed with it.
103 It contains files not present
104 in the official (@code{netlib}) version of @code{libf2c},
105 and also contains some minor changes made from @code{libf2c},
107 and to facilitate automatic configuration, building, and installation of
108 @code{libf2c} (as @code{libg2c}) for use by @code{g77} users.
109 See @file{libf2c/README} for more information,
110 including licensing conditions
111 governing distribution of programs containing code from @code{libg2c}.
113 @code{libg2c}, @code{g77}'s version of @code{libf2c},
114 adds Dave Love's implementation of @code{libU77},
115 in the @file{libf2c/libU77/} directory.
116 This library is distributed under the
117 GNU Library General Public License (LGPL)---see the
118 file @file{libf2c/libU77/COPYING.LIB}
119 for more information,
121 governs distribution conditions for programs containing code
122 from this portion of the library.
124 Files of note in @file{f/} and @file{libf2c/} are described below:
128 Lists some important bugs known to be in g77.
129 Or use Info (or GNU Emacs Info mode) to read
130 the ``Actual Bugs'' node of the @code{g77} documentation:
133 info -f f/g77.info -n "Actual Bugs"
137 Lists recent changes to @code{g77} internals.
139 @item libf2c/ChangeLog
140 Lists recent changes to @code{libg2c} internals.
143 Contains the per-release changes.
144 These include the user-visible
145 changes described in the node ``Changes''
146 in the @code{g77} documentation, plus internal
151 info -f f/g77.info -n News
155 The @code{g77} documentation, in Info format,
156 produced by building @code{g77}.
158 All users of @code{g77} (not just installers) should read this,
159 using the @code{more} command if neither the @code{info} command,
160 nor GNU Emacs (with its Info mode), are available, or if users
161 aren't yet accustomed to using these tools.
162 All of these files are readable as ``plain text'' files,
163 though they're easier to navigate using Info readers
164 such as @code{info} and GNU Emacs Info mode.
167 If you want to explore the FFE code, which lives entirely in @file{f/},
168 here are a few clues.
169 The file @file{g77spec.c} contains the @code{g77}-specific source code
170 for the @code{g77} command only---this just forms a variant of the
171 @code{gcc} command, so,
172 just as the @code{gcc} command itself does not contain the C front end,
173 the @code{g77} command does not contain the Fortran front end (FFE).
174 The FFE code ends up in an executable named @file{f771},
175 which does the actual compiling,
176 so it contains the FFE plus the @code{gcc} back end (GBE),
177 the latter to do most of the optimization, and the code generation.
179 The file @file{parse.c} is the source file for @code{yyparse()},
180 which is invoked by the GBE to start the compilation process,
183 The file @file{top.c} contains the top-level FFE function @code{ffe_file}
184 and it (along with top.h) define all @samp{ffe_[a-z].*}, @samp{ffe[A-Z].*},
185 and @samp{FFE_[A-Za-z].*} symbols.
187 The file @file{fini.c} is a @code{main()} program that is used when building
188 the FFE to generate C header and source files for recognizing keywords.
189 The files @file{malloc.c} and @file{malloc.h} comprise a memory manager
190 that defines all @samp{malloc_[a-z].*}, @samp{malloc[A-Z].*}, and
191 @samp{MALLOC_[A-Za-z].*} symbols.
193 All other modules named @var{xyz}
194 are comprised of all files named @samp{@var{xyz}*.@var{ext}}
195 and define all @samp{ffe@var{xyz}_[a-z].*}, @samp{ffe@var{xyz}[A-Z].*},
196 and @samp{FFE@var{XYZ}_[A-Za-z].*} symbols.
197 If you understand all this, congratulations---it's easier for me to remember
198 how it works than to type in these regular expressions.
199 But it does make it easy to find where a symbol is defined.
200 For example, the symbol @samp{ffexyz_set_something} would be defined
201 in @file{xyz.h} and implemented there (if it's a macro) or in @file{xyz.c}.
203 The ``porting'' files of note currently are:
208 This defines the ``language'' used by all the other source files,
209 the language being Standard C plus some useful things
210 like @code{ARRAY_SIZE} and such.
214 These describe the target machine
215 in terms of what data types are supported,
217 (to what C type does an @code{INTEGER*8} map, for example),
218 how to convert between them,
220 Over time, versions of @code{g77} rely less on this file
221 and more on run-time configuration based on GBE info
226 These are the primary interface to the GBE.
230 This contains code for implementing recognized executable statements
235 These contain information on the format(s) of source files
236 (such as whether they are never to be processed as case-insensitive
237 with regard to Fortran keywords).
240 If you want to debug the @file{f771} executable,
241 for example if it crashes,
242 note that the global variables @code{lineno} and @code{input_filename}
243 are usually set to reflect the current line being read by the lexer
244 during the first-pass analysis of a program unit and to reflect
245 the current line being processed during the second-pass compilation
248 If an invocation of the function @code{ffestd_exec_end} is on the stack,
249 the compiler is in the second pass, otherwise it is in the first.
251 (This information might help you reduce a test case and/or work around
252 a bug in @code{g77} until a fix is available.)
254 @node Overview of Translation Process
255 @section Overview of Translation Process
257 The order of phases translating source code to the form accepted
262 Stripping punched-card sources (@file{g77stripcard.c})
265 Lexing (@file{lex.c})
268 Stand-alone statement identification (@file{sta.c})
271 INCLUDE handling (@file{sti.c})
274 Order-dependent statement identification (@file{stq.c})
277 Parsing (@file{stb.c} and @file{expr.c})
280 Constructing (@file{stc.c})
283 Collecting (@file{std.c})
286 Expanding (@file{ste.c})
289 To get a rough idea of how a particularly twisted Fortran statement
290 gets treated by the passes, consider:
297 The job of @file{lex.c} is to know enough about Fortran syntax rules
298 to break the statement up into distinct lexemes without requiring
299 any feedback from subsequent phases:
314 The job of @file{sta.c} is to figure out the kind of statement,
315 or, at least, statement form, that sequence of lexemes represent.
317 The sooner it can do this (in terms of using the smallest number of
318 lexemes, starting with the first for each statement), the better,
319 because that leaves diagnostics for problems beyond the recognition
320 of the statement form to subsequent phases,
321 which can usually better describe the nature of the problem.
323 In this case, the @samp{=} at ``level zero''
324 (not nested within parentheses)
325 tells @file{sta.c} that this is an @emph{assignment-form},
326 not @code{FORMAT}, statement.
328 An assignment-form statement might be a statement-function
329 definition or an executable assignment statement.
331 To make that determination,
332 @file{sta.c} looks at the first two lexemes.
334 Since the second lexeme is @samp{(},
335 the first must represent an array for this to be an assignment statement,
336 else it's a statement function.
338 Either way, @file{sta.c} hands off the statement to @file{stq.c}
339 (via @file{sti.c}, which expands INCLUDE files).
340 @file{stq.c} figures out what a statement that is,
341 on its own, ambiguous, must actually be based on the context
342 established by previous statements.
344 So, @file{stq.c} watches the statement stream for executable statements,
345 END statements, and so on, so it knows whether @samp{A(B)=C} is
346 (intended as) a statement-function definition or an assignment statement.
348 After establishing the context-aware statement info, @file{stq.c}
349 passes the original sample statement on to @file{stb.c}
350 (either its statement-function parser or its assignment-statement parser).
353 statement-specific record containing the pertinent information.
354 That information includes a source expression and,
355 for an assignment statement, a destination expression.
356 Expressions are parsed by @file{expr.c}.
358 This record is passed to @file{stc.c},
359 which copes with the implications of the statement
360 within the context established by previous statements.
362 For example, if it's the first statement in the file
363 or after an @code{END} statement,
364 @file{stc.c} recognizes that, first of all,
365 a main program unit is now being lexed
366 (and tells that to @file{std.c}
367 before telling it about the current statement).
369 @file{stc.c} attaches whatever information it can,
370 usually derived from the context established by the preceding statements,
371 and passes the information to @file{std.c}.
373 @file{std.c} saves this information away,
374 since the GBE cannot cope with information
375 that might be incomplete at this stage.
377 For example, @samp{I3} might later be determined
378 to be an argument to an alternate @code{ENTRY} point.
380 When @file{std.c} is told about the end of an external (top-level)
382 it passes all the information it has saved away
383 on statements in that program unit
386 @file{ste.c} ``expands'' each statement, in sequence, by
387 constructing the appropriate GBE information and calling
388 the appropriate GBE routines.
390 Details on the transformational phases follow.
391 Keep in mind that Fortran numbering is used,
392 so the first character on a line is column 1,
393 decimal numbering is used, and so on.
407 * Gotchas (Transforming)::
408 * TBD (Transforming)::
412 @subsection g77stripcard
414 The @code{g77stripcard} program handles removing content beyond
415 column 72 (adjustable via a command-line option),
416 optionally warning about that content being something other
417 than trailing whitespace or Fortran commentary.
419 This program is needed because @code{lex.c} doesn't pay attention
420 to maximum line lengths at all, to make it easier to maintain,
421 as well as faster (for sources that don't depend on the maximum
422 column length vis-a-vis trailing non-blank non-commentary content).
424 Just how this program will be run---whether automatically for
425 old source (perhaps as the default for @file{.f} files?)---is not
428 In the meantime, it might as well be implemented as a typical UNIX pipe.
430 It should accept a @samp{-fline-length-@var{n}} option,
431 with the default line length set to 72.
433 When the text it strips off the end of a line is not blank
434 (not spaces and tabs),
435 it should insert an additional comment line
436 (beginning with @samp{!},
437 so it works for both fixed-form and free-form files)
439 following the stripped line.
440 The inserted comment should have a prefix of some kind,
441 TBD, that distinguishes the comment as representing stripped text.
442 Users could use that to @code{sed} out such lines, if they wished---it
443 seems silly to provide a command-line option to delete information
444 when it can be so easily filtered out by another program.
446 (This inserted comment should be designed to ``fit in'' well
447 with whatever the Fortran community is using these days for
448 preprocessor, translator, and other such products, like OpenMP.
449 What that's all about, and how @code{g77} can elegantly fit its
450 special comment conventions into it all, is TBD as well.
451 We don't want to reinvent the wheel here, but if there turn out
452 to be too many conflicting conventions, we might have to invent
453 one that looks nothing like the others, but which offers their
454 host products a better infrastructure in which to fit and coexist
457 @code{g77stripcard} probably shouldn't do any tab expansion or other
459 People can use @code{expand} or other pre-filtering if they like.
460 The idea here is to keep each stage quite simple, while providing
461 excellent performance for ``normal'' code.
463 (Code with junk beyond column 73 is not really ``normal'',
464 as it comes from a card-punch heritage,
465 and will be increasingly hard for tomorrow's Fortran programmers to read.)
470 To help make the lexer simple, fast, and easy to maintain,
471 while also having @code{g77} generally encourage Fortran programmers
472 to write simple, maintainable, portable code by maximizing the
473 performance of compiling that kind of code:
477 There'll be just one lexer, for both fixed-form and free-form source.
480 It'll care about the form only when handling the first 7 columns of
481 text, stuff like spaces between strings of alphanumerics, and
482 how lines are continued.
484 Some other distinctions will be handled by subsequent phases,
485 so at least one of them will have to know which form is involved.
487 For example, @samp{I = 2 . 4} is acceptable in fixed form,
488 and works in free form as well given the implementation @code{g77}
490 But the standard requires a diagnostic for it in free form,
491 so the parser has to be able to recognize that
492 the lexemes aren't contiguous
493 (information the lexer @emph{does} have to provide)
494 and that free-form source is being parsed,
495 so it can provide the diagnostic.
497 The @code{g77} lexer doesn't try to gather @samp{2 . 4} into a single lexeme.
498 Otherwise, it'd have to know a whole lot more about how to parse Fortran,
499 or subsequent phases (mainly parsing) would have two paths through
500 lots of critical code---one to handle the lexeme @samp{2}, @samp{.},
501 and @samp{4} in sequence, another to handle the lexeme @samp{2.4}.
504 It won't worry about line lengths
505 (beyond the first 7 columns for fixed-form source).
507 That is, once it starts parsing the ``statement'' part of a line
508 (column 7 for fixed-form, column 1 for free-form),
509 it'll keep going until it finds a newline,
510 rather than ignoring everything past a particular column
513 The implication here is that there shouldn't @emph{be}
514 anything past that last column, other than whitespace or
515 commentary, because users using typical editors
516 (or viewing output as typically printed)
517 won't necessarily know just where the last column is.
519 Code that has ``garbage'' beyond the last column
520 (almost certainly only fixed-form code with a punched-card legacy,
521 such as code using columns 73-80 for ``sequence numbers'')
522 will have to be run through @code{g77stripcard} first.
524 Also, keeping track of the maximum column position while also watching out
525 for the end of a line @emph{and} while reading from a file
526 just makes things slower.
527 Since a file must be read, and watching for the end of the line
528 is necessary (unless the typical input file was preprocessed to
529 include the necessary number of trailing spaces),
530 dropping the tracking of the maximum column position
531 is the only way to reduce the complexity of the pertinent code
532 while maintaining high performance.
535 ASCII encoding is assumed for the input file.
537 Code written in other character sets will have to be converted first.
541 will be converted to spaces via the straightforward
544 Specifically, a tab is converted to between one and eight spaces
545 as necessary to reach column @var{n},
546 where dividing @samp{(@var{n} - 1)} by eight
547 results in a remainder of zero.
549 That saves having to pass most source files through @code{expand}.
552 Linefeeds (ASCII code 10)
553 mark the ends of lines.
556 A carriage return (ASCII code 13)
557 is accept if it immediately precedes a linefeed,
558 in which case it is ignored.
560 Otherwise, it is rejected (with a diagnostic).
563 Any other characters other than the above
564 that are not part of the GNU Fortran Character Set
565 (@pxref{Character Set})
566 are rejected with a diagnostic.
568 This includes backspaces, form feeds, and the like.
570 (It might make sense to allow a form feed in column 1
571 as long as that's the only character on a line.
572 It certainly wouldn't seem to cost much in terms of performance.)
575 The end of the input stream (EOF)
576 ends the current line.
579 The distinction between uppercase and lowercase letters
582 It will be up to subsequent phases to decide to fold case.
584 Current plans are to permit any casing for Fortran (reserved) keywords
585 while preserving casing for user-defined names.
586 (This might not be made the default for @file{.f} files, though.)
588 Preserving case seems necessary to provide more direct access
589 to facilities outside of @code{g77}, such as to C or Pascal code.
591 Names of intrinsics will probably be matchable in any case,
592 However, there probably won't be any option to require
593 a particular mixed-case appearance of intrinsics
594 (as there was for @code{g77} prior to version 0.6),
595 because that's painful to maintain,
596 and probably nobody uses it.
598 (How @samp{external SiN; r = sin(x)} would be handled is TBD.
599 I think old @code{g77} might already handle that pretty elegantly,
600 but whether we can cope with allowing the same fragment to reference
601 a @emph{different} procedure, even with the same interface,
602 via @samp{s = SiN(r)}, needs to be determined.
603 If it can't, we need to make sure that when code introduces
604 a user-defined name, any intrinsic matching that name
605 using a case-insensitive comparison
609 Backslashes in @code{CHARACTER} and Hollerith constants
612 This avoids the confusion introduced by some Fortran compiler vendors
613 providing C-like interpretation of backslashes,
614 while others provide straight-through interpretation.
616 Some kind of lexical construct (TBD) will be provided to allow
617 flagging of a @code{CHARACTER}
618 (but probably not a Hollerith)
619 constant that permits backslashes.
620 It'll necessarily be a prefix, such as:
623 PRINT *, C'This line has a backspace \b here.'
624 PRINT *, F'This line has a straight backslash \ here.'
627 Further, command-line options might be provided to specify that
628 one prefix or the other is to be assumed as the default
629 for @code{CHARACTER} constants.
631 However, it seems more helpful for @code{g77} to provide a program
632 that converts prefix all constants
633 (or just those containing backslashes)
634 with the desired designation,
635 so printouts of code can be read
636 without knowing the compile-time options used when compiling it.
638 If such a program is provided
639 (let's name it @code{g77slash} for now),
640 then a command-line option to @code{g77} should not be provided.
641 (Though, given that it'll be easy to implement, it might be hard
642 to resist user requests for it ``to compile faster than if we
643 have to invoke another filter''.)
645 This program would take a command-line option to specify the
646 default interpretation of slashes,
647 affecting which prefix it uses for constants.
649 @code{g77slash} probably should automatically convert Hollerith
650 constants that contain slashes
651 to the appropriate @code{CHARACTER} constants.
652 Then @code{g77} wouldn't have to define a prefix syntax for Hollerith
653 constants specifying whether they want C-style or straight-through
657 To allow for form-neutral INCLUDE files without requiring them
659 the fixed-form lexer should offer an extension (if possible)
660 allowing a trailing @samp{&} to be ignored, especially if after
661 column 72, as it would be using the traditional Unix Fortran source
662 model (which ignores @emph{everything} after column 72).
665 The above implements nearly exactly what is specified by
669 except it also provides automatic conversion of tabs
670 and ignoring of newline-related carriage returns,
671 as well as accommodating form-neutral INCLUDE files.
673 It also implements the ``pure visual'' model,
674 by which is meant that a user viewing his code
675 in a typical text editor
676 (assuming it's not preprocessed via @code{g77stripcard} or similar)
677 doesn't need any special knowledge
678 of whether spaces on the screen are really tabs,
679 whether lines end immediately after the last visible non-space character
680 or after a number of spaces and tabs that follow it,
681 or whether the last line in the file is ended by a newline.
683 Most editors don't make these distinctions,
684 the ANSI FORTRAN 77 standard doesn't require them to,
685 and it permits a standard-conforming compiler
686 to define a method for transforming source code to
687 ``standard form'' however it wants.
689 So, GNU Fortran defines it such that users have the best chance
690 of having the code be interpreted the way it looks on the screen
691 of the typical editor.
693 (Fancy editors should @emph{never} be required to correctly read code
694 written in classic two-dimensional-plaintext form.
695 By correct reading I mean ability to read it, book-like, without
696 mistaking text ignored by the compiler for program code and vice versa,
697 and without having to count beyond the first several columns.
698 The vague meaning of ASCII TAB, among other things, complicates
699 this somewhat, but as long as ``everyone'', including the editor,
700 other tools, and printer, agrees about the every-eighth-column convention,
701 the GNU Fortran ``pure visual'' model meets these requirements.
702 Any language or user-visible source form
703 requiring special tagging of tabs,
704 the ends of lines after spaces/tabs,
705 and so on, fails to meet this fairly straightforward specification.
706 Fortunately, Fortran @emph{itself} does not mandate such a failure,
707 though most vendor-supplied defaults for their Fortran compilers @emph{do}
708 fail to meet this specification for readability.)
710 Further, this model provides a clean interface
711 to whatever preprocessors or code-generators are used
712 to produce input to this phase of @code{g77}.
713 Mainly, they need not worry about long lines.
739 @node Gotchas (Transforming)
740 @subsection Gotchas (Transforming)
742 This section is not about transforming ``gotchas'' into something else.
743 It is about the weirder aspects of transforming Fortran,
744 however that's defined,
745 into a more modern, canonical form.
747 @subsubsection Multi-character Lexemes
749 Each lexeme carries with it a pointer to where it appears in the source.
751 To provide the ability for diagnostics to point to column numbers,
752 in addition to line numbers and names,
753 lexemes that represent more than one (significant) character
754 in the source code need, generally,
755 to provide pointers to where each @emph{character} appears in the source.
757 This provides the ability to properly identify the precise location
758 of the problem in code like
767 which, in fixed-form source, would result in single lexemes
768 consisting of the strings @samp{SUBROUTINEX} and @samp{BLOCKDATAX}.
769 (The problem is that @samp{X} is defined twice,
770 so a pointer to the @samp{X} in the second definition,
771 as well as a follow-up pointer to the corresponding pointer in the first,
772 would be preferable to pointing to the beginnings of the statements.)
774 This need also arises when parsing (and diagnosing) @code{FORMAT}
777 Further, it arises when diagnosing
778 @code{FMT=} specifiers that contain constants
779 (or partial constants, or even propagated constants!)
780 in I/O statements, as in:
783 PRINT '(I2, 3HAB)', J
786 (A pointer to the beginning of the prematurely-terminated Hollerith
787 constant, and/or to the close parenthese, is preferable to a pointer
788 to the open-parenthese or the apostrophe that precedes it.)
790 Multi-character lexemes, which would seem to naturally include
791 at least digit strings, alphanumeric strings, @code{CHARACTER}
792 constants, and Hollerith constants, therefore need to provide
793 location information on each character.
794 (Maybe Hollerith constants don't, but it's unnecessary to except them.)
796 The question then arises, what about @emph{other} multi-character lexemes,
797 such as @samp{**} and @samp{//},
798 and Fortran 90's @samp{(/}, @samp{/)}, @samp{::}, and so on?
800 Turns out there's a need to identify the location of the second character
801 of these two-character lexemes.
802 For example, in @samp{I(/J) = K}, the slash needs to be diagnosed
803 as the problem, not the open parenthese.
804 Similarly, it is preferable to diagnose the second slash in
805 @samp{I = J // K} rather than the first, given the implicit typing
806 rules, which would result in the compiler disallowing the attempted
807 concatenation of two integers.
808 (Though, since that's more of a semantic issue,
809 it's not @emph{that} much preferable.)
811 Even sequences that could be parsed as digit strings could use location info,
812 for example, to diagnose the @samp{9} in the octal constant @samp{O'129'}.
813 (This probably will be parsed as a character string,
814 to be consistent with the parsing of @samp{Z'129A'}.)
816 To avoid the hassle of recording the location of the second character,
817 while also preserving the general rule that each significant character
818 is distinctly pointed to by the lexeme that contains it,
819 it's best to simply not have any fixed-size lexemes
820 larger than one character.
822 This new design is expected to make checking for two
823 @samp{*} lexemes in a row much easier than the old design,
824 so this is not much of a sacrifice.
825 It probably makes the lexer much easier to implement
826 than it makes the parser harder.
828 @subsubsection Space-padding Lexemes
830 Certain lexemes need to be padded with virtual spaces when the
831 end of the line (or file) is encountered.
833 This is necessary in fixed form, to handle lines that don't
834 extend to column 72, assuming that's the line length in effect.
836 @subsubsection Bizarre Free-form Hollerith Constants
838 Last I checked, the Fortran 90 standard actually required the compiler
839 to silently accept something like
842 FORMAT ( 1 2 Htwelve chars )
845 as a valid @code{FORMAT} statement specifying a twelve-character
848 The implication here is that, since the new lexer is a zero-feedback one,
849 it won't know that the special case of a @code{FORMAT} statement being parsed
850 requires apparently distinct lexemes @samp{1} and @samp{2} to be treated as
853 (This is a horrible misfeature of the Fortran 90 language.
854 It's one of many such misfeatures that almost make me want
855 to not support them, and forge ahead with designing a new
856 ``GNU Fortran'' language that has the features,
857 but not the misfeatures, of Fortran 90,
858 and provide utility programs to do the conversion automatically.)
860 So, the lexer must gather distinct chunks of decimal strings into
861 a single lexeme in contexts where a single decimal lexeme might
862 start a Hollerith constant.
864 (Which probably means it might as well do that all the time
865 for all multi-character lexemes, even in free-form mode,
866 leaving it to subsequent phases to pull them apart as they see fit.)
868 Compare the treatment of this to how
880 must be treated---the former must be diagnosed, due to the separation
881 between lexemes, the latter must be accepted as a proper declaration.
883 @subsubsection Hollerith Constants
885 Recognizing a Hollerith constant---specifically,
886 that an @samp{H} or @samp{h} after a digit string begins
887 such a constant---requires some knowledge of context.
889 Hollerith constants (such as @samp{2HAB}) can appear after:
902 @samp{+}, @samp{-}, @samp{/}
905 @samp{*}, except as noted below
908 Hollerith constants don't appear after:
913 which can be treated generally as
914 any @samp{*} that is the second lexeme of a statement
917 @subsubsection Confusing Function Keyword
925 must be a @code{FUNCTION} statement and
928 REAL FUNCTION FOO (5)
931 must be a type-definition statement,
934 REAL FUNCTION FOO (@var{names})
937 where @var{names} is a comma-separated list of names,
938 can be one or the other.
940 The only way to disambiguate that statement
941 (short of mandating free-form source or a short maximum
942 length for name for external procedures)
943 is based on the context of the statement.
945 In particular, the statement is known to be within an
946 already-started program unit
947 (but not at the outer level of the @code{CONTAINS} block),
948 it is a type-declaration statement.
950 Otherwise, the statement is a @code{FUNCTION} statement,
951 in that it begins a function program unit
952 (external, or, within @code{CONTAINS}, nested).
954 @subsubsection Weird READ
962 is equivalent to either
974 depending on which would be valid in context.
976 Specifically, if @samp{N} is type @code{INTEGER},
977 @samp{READ (FMT=(N))} would not be valid,
978 because parentheses may not be used around @samp{N},
979 whereas they may around it in @samp{READ (UNIT=(N))}.
981 Further, if @samp{N} is type @code{CHARACTER},
982 the opposite is true---@samp{READ (UNIT=(N))} is not valid,
983 but @samp{READ (FMT=(N))} is.
985 Strictly speaking, if anything follows
991 in the statement, whether the first lexeme after the close
992 parenthese is a comma could be used to disambiguate the two cases,
993 without looking at the type of @samp{N},
994 because the comma is required for the @samp{READ (FMT=(N))}
995 interpretation and disallowed for the @samp{READ (UNIT=(N))}
998 However, in practice, many Fortran compilers allow
999 the comma for the @samp{READ (UNIT=(N))}
1000 interpretation anyway
1001 (in that they generally allow a leading comma before
1002 an I/O list in an I/O statement),
1003 and much code takes advantage of this allowance.
1005 (This is quite a reasonable allowance, since the
1006 juxtaposition of a comma-separated list immediately
1007 after an I/O control-specification list, which is also comma-separated,
1008 without an intervening comma,
1009 looks sufficiently ``wrong'' to programmers
1010 that they can't resist the itch to insert the comma.
1011 @samp{READ (I, J), K, L} simply looks cleaner than
1012 @samp{READ (I, J) K, L}.)
1014 So, type-based disambiguation is needed unless strict adherence
1015 to the standard is always assumed, and we're not going to assume that.
1017 @node TBD (Transforming)
1018 @subsection TBD (Transforming)
1020 Continue researching gotchas, designing the transformational process,
1021 and implementing it.
1023 Specific issues to resolve:
1027 Just where should (if it was implemented) @code{USE} processing take place?
1029 This gets into the whole issue of how @code{g77} should handle the concept
1031 I think GNAT already takes on this issue, but don't know more than that.
1032 Jim Giles has written extensively on @code{comp.lang.fortran}
1033 about his opinions on module handling, as have others.
1034 Jim's views should be taken into account.
1036 Actually, Richard M. Stallman (RMS) also has written up
1037 some guidelines for implementing such things,
1038 but I'm not sure where I read them.
1039 Perhaps the old @email{gcc2@@cygnus.com} list.
1041 If someone could dig references to these up and get them to me,
1042 that would be much appreciated!
1043 Even though modules are not on the short-term list for implementation,
1044 it'd be helpful to know @emph{now} how to avoid making them harder to
1045 implement them @emph{later}.
1048 Should the @code{g77} command become just a script that invokes
1049 all the various preprocessing that might be needed,
1050 thus making it seem slower than necessary for legacy code
1051 that people are unwilling to convert,
1052 or should we provide a separate script for that,
1053 thus encouraging people to convert their code once and for all?
1055 At least, a separate script to behave as old @code{g77} did,
1056 perhaps named @code{g77old}, might ease the transition,
1057 as might a corresponding one that converts source codes
1058 named @code{g77oldnew}.
1060 These scripts would take all the pertinent options @code{g77} used
1061 to take and run the appropriate filters,
1062 passing the results to @code{g77} or just making new sources out of them
1063 (in a subdirectory, leaving the user to do the dirty deed of
1064 moving or copying them over the old sources).
1067 Do other Fortran compilers provide a prefix syntax
1068 to govern the treatment of backslashes in @code{CHARACTER}
1069 (or Hollerith) constants?
1071 Knowing what other compilers provide would help.
1074 Is it okay to drop support for the @samp{-fintrin-case-initcap},
1075 @samp{-fmatch-case-initcap}, @samp{-fsymbol-case-initcap},
1076 and @samp{-fcase-initcap} options?
1078 I've asked @email{info-gnu-fortran@@gnu.org} for input on this.
1079 Not having to support these makes it easier to write the new front end,
1080 and might also avoid complicated its design.
1082 The consensus to date (1999-11-17) has been to drop this support.
1083 Can't recall anybody saying they're using it, in fact.
1086 @node Philosophy of Code Generation
1087 @section Philosophy of Code Generation
1089 Don't poke the bear.
1091 The @code{g77} front end generates code
1092 via the @code{gcc} back end.
1094 @cindex GNU Back End (GBE)
1096 @cindex @code{gcc}, back end
1097 @cindex back end, gcc
1098 @cindex code generator
1099 The @code{gcc} back end (GBE) is a large, complex
1100 labyrinth of intricate code
1101 written in a combination of the C language
1102 and specialized languages internal to @code{gcc}.
1104 While the @emph{code} that implements the GBE
1105 is written in a combination of languages,
1107 to the front end for a language like Fortran,
1108 best viewed as a @emph{compiler}
1109 that compiles its own, unique, language.
1111 The GBE's ``source'', then, is written in this language,
1112 which consists primarily of
1113 a combination of calls to GBE functions
1114 and @dfn{tree} nodes
1115 (which are, themselves, created
1116 by calling GBE functions).
1118 So, the @code{g77} generates code by, in effect,
1119 translating the Fortran code it reads
1120 into a form ``written'' in the ``language''
1121 of the @code{gcc} back end.
1124 @cindex GNU Back End Language (GBEL)
1125 This language will heretofore be referred to as @dfn{GBEL},
1126 for GNU Back End Language.
1128 GBEL is an evolving language,
1129 not fully specified in any published form
1131 It offers many facilities,
1132 but its ``core'' facilities
1133 are those that corresponding most directly
1134 to those needed to support @code{gcc}
1135 (compiling code written in GNU C).
1137 The @code{g77} Fortran Front End (FFE)
1138 is designed and implemented
1139 to navigate the currents and eddies
1140 of ongoing GBEL and @code{gcc} development
1141 while also delivering on the potential
1142 of an integrated FFE
1143 (as compared to using a converter like @code{f2c}
1144 and feeding the output into @code{gcc}).
1146 Goals of the FFE's code-generation strategy include:
1150 High likelihood of generation of correct code,
1151 or, failing that, producing a fatal diagnostic or crashing.
1154 Generation of highly optimized code,
1155 as directed by the user
1156 via GBE-specific (versus @code{g77}-specific) constructs,
1157 such as command-line options.
1160 Fast overall (FFE plus GBE) compilation.
1163 Preservation of source-level debugging information.
1166 The strategies historically, and currently, used by the FFE
1167 to achieve these goals include:
1171 Use of GBEL constructs that most faithfully encapsulate
1172 the semantics of Fortran.
1175 Avoidance of GBEL constructs that are so rarely used,
1176 or limited to use in specialized situations not related to Fortran,
1177 that their reliability and performance has not yet been established
1178 as sufficient for use by the FFE.
1181 Flexible design, to readily accommodate changes to specific
1182 code-generation strategies, perhaps governed by command-line options.
1186 @cindex Poking the bear
1187 ``Don't poke the bear'' somewhat summarizes the above strategies.
1188 The GBE is the bear.
1189 The FFE is designed and implemented to avoid poking it
1190 in ways that are likely to just annoy it.
1191 The FFE usually either tackles it head-on,
1192 or avoids treating it in ways dissimilar to how
1193 the @code{gcc} front end treats it.
1195 For example, the FFE uses the native array facility in the back end
1196 instead of the lower-level pointer-arithmetic facility
1197 used by @code{gcc} when compiling @code{f2c} output).
1198 Theoretically, this presents more opportunities for optimization,
1199 faster compile times,
1200 and the production of more faithful debugging information.
1201 These benefits were not, however, immediately realized,
1202 mainly because @code{gcc} itself makes little or no use
1203 of the native array facility.
1205 Complex arithmetic is a case study of the evolution of this strategy.
1206 When originally implemented,
1207 the GBEL had just evolved its own native complex-arithmetic facility,
1208 so the FFE took advantage of that.
1210 When porting @code{g77} to 64-bit systems,
1211 it was discovered that the GBE didn't really
1212 implement its native complex-arithmetic facility properly.
1214 The short-term solution was to rewrite the FFE
1215 to instead use the lower-level facilities
1216 that'd be used by @code{gcc}-compiled code
1217 (assuming that code, itself, didn't use the native complex type
1218 provided, as an extension, by @code{gcc}),
1219 since these were known to work,
1220 and, in any case, if shown to not work,
1221 would likely be rapidly fixed
1222 (since they'd likely not work for vanilla C code in similar circumstances).
1224 However, the rewrite accommodated the original, native approach as well
1225 by offering a command-line option to select it over the emulated approach.
1226 This allowed users, and especially GBE maintainers, to try out
1227 fixes to complex-arithmetic support in the GBE
1228 while @code{g77} continued to default to compiling more code correctly,
1229 albeit producing (typically) slower executables.
1231 As of April 1999, it appeared that the last few bugs
1232 in the GBE's support of its native complex-arithmetic facility
1234 The FFE was changed back to default to using that native facility,
1235 leaving emulation as an option.
1237 Later during the release cycle
1238 (which was called EGCS 1.2, but soon became GCC 2.95),
1239 bugs in the native facility were found.
1240 Reactions among various people included
1241 ``the last thing we should do is change the default back'',
1242 ``we must change the default back'',
1243 and ``let's figure out whether we can narrow down the bugs to
1244 few enough cases to allow the now-months-long-tested default
1245 to remain the same''.
1246 The latter viewpoint won that particular time.
1247 The bugs exposed other concerns regarding ABI compliance
1248 when the ABI specified treatment of complex data as different
1249 from treatment of what Fortran and GNU C consider the equivalent
1250 aggregation (structure) of real (or float) pairs.
1252 Other Fortran constructs---arrays, character strings,
1253 complex division, @code{COMMON} and @code{EQUIVALENCE} aggregates,
1254 and so on---involve issues similar to those pertaining to complex arithmetic.
1256 So, it is possible that the history
1257 of how the FFE handled complex arithmetic
1258 will be repeated, probably in modified form
1259 (and hopefully over shorter timeframes),
1260 for some of these other facilities.
1262 @node Two-pass Design
1263 @section Two-pass Design
1265 The FFE does not tell the GBE anything about a program unit
1266 until after the last statement in that unit has been parsed.
1267 (A program unit is a Fortran concept that corresponds, in the C world,
1268 mostly closely to functions definitions in ISO C.
1269 That is, a program unit in Fortran is like a top-level function in C.
1270 Nested functions, found among the extensions offered by GNU C,
1271 correspond roughly to Fortran's statement functions.)
1273 So, while parsing the code in a program unit,
1274 the FFE saves up all the information
1275 on statements, expressions, names, and so on,
1276 until it has seen the last statement.
1278 At that point, the FFE revisits the saved information
1279 (in what amounts to a second @dfn{pass} over the program unit)
1280 to perform the actual translation of the program unit into GBEL,
1281 ultimating in the generation of assembly code for it.
1283 Some lookahead is performed during this second pass,
1284 so the FFE could be viewed as a ``two-plus-pass'' design.
1292 @subsection Two-pass Code
1294 Most of the code that turns the first pass (parsing)
1295 into a second pass for code generation
1296 is in @file{@value{path-g77}/std.c}.
1298 It has external functions,
1299 called mainly by siblings in @file{@value{path-g77}/stc.c},
1300 that record the information on statements and expressions
1301 in the order they are seen in the source code.
1302 These functions save that information.
1304 It also has an external function that revisits that information,
1305 calling the siblings in @file{@value{path-g77}/ste.c},
1306 which handles the actual code generation
1307 (by generating GBEL code,
1308 that is, by calling GBE routines
1309 to represent and specify expressions, statements, and so on).
1311 @node Why Two Passes
1312 @subsection Why Two Passes
1314 The need for two passes was not immediately evident
1315 during the design and implementation of the code in the FFE
1316 that was to produce GBEL.
1317 Only after a few kludges,
1318 to handle things like incorrectly-guessed @code{ASSIGN} label nature,
1319 had been implemented,
1320 did enough evidence pile up to make it clear
1321 that @file{std.c} had to be introduced to intercept,
1322 save, then revisit as part of a second pass,
1323 the digested contents of a program unit.
1325 Other such missteps have occurred during the evolution of the FFE,
1326 because of the different goals of the FFE and the GBE.
1328 Because the GBE's original, and still primary, goal
1329 was to directly support the GNU C language,
1330 the GBEL, and the GBE itself,
1331 requires more complexity
1332 on the part of most front ends
1333 than it requires of @code{gcc}'s.
1336 the GBEL offers an interface that permits the @code{gcc} front end
1337 to implement most, or all, of the language features it supports,
1338 without the front end having to
1339 make use of non-user-defined variables.
1340 (It's almost certainly the case that all of K&R C,
1341 and probably ANSI C as well,
1342 is handled by the @code{gcc} front end
1343 without declaring such variables.)
1345 The FFE, on the other hand, must resort to a variety of ``tricks''
1346 to achieve its goals.
1348 Consider the following C code:
1356 if ((c = bar (c)) == 0)
1366 Note what kinds of objects are declared, or defined, before their use,
1367 and before any actual code generation involving them
1368 would normally take place:
1372 Return type of function
1375 Entry point(s) of function
1384 Initial values for variables
1387 Whereas, the following items can, and do,
1388 suddenly appear ``out of the blue'' in C:
1398 Not surprisingly, the GBE faithfully permits the latter set of items
1399 to be ``discovered'' partway through GBEL ``programs'',
1400 just as they are permitted to in C.
1402 Yet, the GBE has tended, at least in the past,
1403 to be reticent to fully support similar ``late'' discovery
1404 of items in the former set.
1406 This makes Fortran a poor fit for the ``safe'' subset of GBEL.
1410 FUNCTION X (A, ARRAY, ID1)
1412 DOUBLE PRECISION X, Y, Z, TMP, EE, PI
1419 IF (I .EQ. 0) PRINT *, A(0)
1431 DATA EE, PI /2.71D0, 3.14D0/
1435 Here are some observations about the above code,
1436 which, while somewhat contrived,
1437 conforms to the FORTRAN 77 and Fortran 90 standards:
1441 The return type of function @samp{X} is not known
1442 until the @samp{DOUBLE PRECISION} line has been parsed.
1445 Whether @samp{A} is a function or a variable
1446 is not known until the @samp{PRINT *, A(0)} statement
1450 The bounds of the array of argument @samp{ARRAY}
1451 depend on a computation involving
1452 the subsequent argument @samp{ID1}
1453 and the blank-common member @samp{ID2}.
1456 Whether @samp{Y} and @samp{Z} are local variables,
1457 additional function entry points,
1458 or dummy arguments to additional entry points
1460 until the @code{ENTRY} statement is parsed.
1463 Similarly, whether @samp{TMP} is a local variable is not known
1464 until the @samp{READ *, TMP} statement is parsed.
1467 The initial values for @samp{EE} and @samp{PI}
1468 are not known until after the @code{DATA} statement is parsed.
1471 Whether @samp{FRED} is a function returning type @code{REAL}
1473 (which can be thought of as returning type @code{void}
1474 @emph{or}, to support alternate returns in a simple way,
1477 until the @samp{CALL FRED} statement is parsed.
1480 Whether @samp{100} is a @code{FORMAT} label
1481 or the label of an executable statement
1483 until the @samp{X =} statement is parsed.
1484 (These two types of labels get @emph{very} different treatment,
1485 especially when @code{ASSIGN}'ed.)
1488 That @samp{J} is a local variable is not known
1489 until the first @code{ASSIGN} statement is parsed.
1490 (This happens @emph{after} executable code has been seen.)
1493 Very few of these ``discoveries''
1494 can be accommodated by the GBE as it has evolved over the years.
1495 The GBEL doesn't support several of them,
1496 and those it might appear to support
1497 don't always work properly,
1498 especially in combination with other GBEL and GBE features,
1499 as implemented in the GBE.
1501 (Had the GBE and its GBEL originally evolved to support @code{g77},
1502 the shoe would be on the other foot, so to speak---most, if not all,
1503 of the above would be directly supported by the GBEL,
1504 and a few C constructs would probably not, as they are in reality,
1506 Both this mythical, and today's real, GBE caters to its GBEL
1507 by, sometimes, scrambling around, cleaning up after itself---after
1508 discovering that assumptions it made earlier during code generation
1510 That's not a great design, since it indicates significant code
1511 paths that might be rarely tested but used in some key production
1514 So, the FFE handles these discrepancies---between the order in which
1515 it discovers facts about the code it is compiling,
1516 and the order in which the GBEL and GBE support such discoveries---by
1517 performing what amounts to two
1518 passes over each program unit.
1520 (A few ambiguities can remain at that point,
1521 such as whether, given @samp{EXTERNAL BAZ}
1522 and no other reference to @samp{BAZ} in the program unit,
1523 it is a subroutine, a function, or a block-data---which, in C-speak,
1524 governs its declared return type.
1525 Fortunately, these distinctions are easily finessed
1526 for the procedure, library, and object-file interfaces
1527 supported by @code{g77}.)
1529 @node Challenges Posed
1530 @section Challenges Posed
1532 Consider the following Fortran code, which uses various extensions
1533 (including some to Fortran 90):
1539 INTEGER*2 CLOCKS(200)
1542 CALL SYSTEM_CLOCK (CLOCKS (IFUNC (CFUNC ('('//A//')'))))
1545 The above poses the following challenges to any Fortran compiler
1546 that uses run-time interfaces, and a run-time library, roughly similar
1547 to those used by @code{g77}:
1551 Assuming the library routine that supports @code{SYSTEM_CLOCK}
1552 expects to set an @code{INTEGER*4} variable via its @code{COUNT} argument,
1553 the compiler must make available to it a temporary variable of that type.
1556 Further, after the @code{SYSTEM_CLOCK} library routine returns,
1557 the compiler must ensure that the temporary variable it wrote
1558 is copied into the appropriate element of the @samp{CLOCKS} array.
1559 (This assumes the compiler doesn't just reject the code,
1560 which it should if it is compiling under some kind of a ``strict'' option.)
1563 To determine the correct index into the @samp{CLOCKS} array,
1564 (putting aside the fact that the index, in this particular case,
1565 need not be computed until after
1566 the @code{SYSTEM_CLOCK} library routine returns),
1567 the compiler must ensure that the @code{IFUNC} function is called.
1569 That requires evaluating its argument,
1570 which requires, for @code{g77}
1571 (assuming @code{-ff2c} is in force),
1572 reserving a temporary variable of type @code{COMPLEX}
1573 for use as a repository for the return value
1574 being computed by @samp{CFUNC}.
1577 Before invoking @samp{CFUNC},
1578 is argument must be evaluated,
1579 which requires allocating, at run time,
1580 a temporary large enough to hold the result of the concatenation,
1581 as well as actually performing the concatenation.
1584 The large temporary needed during invocation of @code{CFUNC}
1585 should, ideally, be deallocated
1586 (or, at least, left to the GBE to dispose of, as it sees fit)
1587 as soon as @code{CFUNC} returns,
1588 which means before @code{IFUNC} is called
1589 (as it might need a lot of dynamically allocated memory).
1592 @code{g77} currently doesn't support all of the above,
1593 but, so that it might someday, it has evolved to handle
1594 at least some of the above requirements.
1596 Meeting the above requirements is made more challenging
1597 by conforming to the requirements of the GBEL/GBE combination.
1599 @node Transforming Statements
1600 @section Transforming Statements
1602 Most Fortran statements are given their own block,
1603 and, for temporary variables they might need, their own scope.
1604 (A block is what distinguishes @samp{@{ foo (); @}}
1605 from just @samp{foo ();} in C.
1606 A scope is included with every such block,
1607 providing a distinct name space for local variables.)
1609 Label definitions for the statement precede this block,
1610 so @samp{10 PRINT *, I} is handled more like
1611 @samp{fl10: @{ @dots{} @}} than @samp{@{ fl10: @dots{} @}}
1612 (where @samp{fl10} is just a notation meaning ``Fortran Label 10''
1613 for the purposes of this document).
1616 * Statements Needing Temporaries::
1617 * Transforming DO WHILE::
1618 * Transforming Iterative DO::
1619 * Transforming Block IF::
1620 * Transforming SELECT CASE::
1623 @node Statements Needing Temporaries
1624 @subsection Statements Needing Temporaries
1626 Any temporaries needed during, but not beyond,
1627 execution of a Fortran statement,
1628 are made local to the scope of that statement's block.
1630 This allows the GBE to share storage for these temporaries
1631 among the various statements without the FFE
1632 having to manage that itself.
1634 (The GBE could, of course, decide to optimize
1635 management of these temporaries.
1636 For example, it could, theoretically,
1637 schedule some of the computations involving these temporaries
1638 to occur in parallel.
1639 More practically, it might leave the storage for some temporaries
1640 ``live'' beyond their scopes, to reduce the number of
1641 manipulations of the stack pointer at run time.)
1643 Temporaries needed across distinct statement boundaries usually
1644 are associated with Fortran blocks (such as @code{DO}/@code{END DO}).
1645 (Also, there might be temporaries not associated with blocks at all---these
1646 would be in the scope of the entire program unit.)
1648 Each Fortran block @emph{should} get its own block/scope in the GBE.
1649 This is best, because it allows temporaries to be more naturally handled.
1650 However, it might pose problems when handling labels
1651 (in particular, when they're the targets of @code{GOTO}s outside the Fortran
1652 block), and generally just hassling with replicating
1653 parts of the @code{gcc} front end
1654 (because the FFE needs to support
1655 an arbitrary number of nested back-end blocks
1656 if each Fortran block gets one).
1658 So, there might still be a need for top-level temporaries, whose
1659 ``owning'' scope is that of the containing procedure.
1661 Also, there seems to be problems declaring new variables after
1662 generating code (within a block) in the back end, leading to, e.g.,
1663 @samp{label not defined before binding contour} or similar messages,
1664 when compiling with @samp{-fstack-check} or
1665 when compiling for certain targets.
1667 Because of that, and because sometimes these temporaries are not
1668 discovered until in the middle of of generating code for an expression
1669 statement (as in the case of the optimization for @samp{X**I}),
1670 it seems best to always
1671 pre-scan all the expressions that'll be expanded for a block
1672 before generating any of the code for that block.
1674 This pre-scan then handles discovering and declaring, to the back end,
1675 the temporaries needed for that block.
1677 It's also important to treat distinct items in an I/O list as distinct
1678 statements deserving their own blocks.
1679 That's because there's a requirement
1680 that each I/O item be fully processed before the next one,
1681 which matters in cases like @samp{READ (*,*), I, A(I)}---the
1682 element of @samp{A} read in the second item
1683 @emph{must} be determined from the value
1684 of @samp{I} read in the first item.
1686 @node Transforming DO WHILE
1687 @subsection Transforming DO WHILE
1689 @samp{DO WHILE(expr)} @emph{must} be implemented
1690 so that temporaries needed to evaluate @samp{expr}
1691 are generated just for the test, each time.
1693 Consider how @samp{DO WHILE (A//B .NE. 'END'); @dots{}; END DO} is transformed:
1703 libg77_catenate (temp1, a, b);
1704 temp0 = libg77_ne (temp1, 'END');
1714 In this case, it seems like a time/space tradeoff
1715 between allocating and deallocating @samp{temp1} for each iteration
1716 and allocating it just once for the entire loop.
1718 However, if @samp{temp1} is allocated just once for the entire loop,
1719 it could be the wrong size for subsequent iterations of that loop
1720 in cases like @samp{DO WHILE (A(I:J)//B .NE. 'END')},
1721 because the body of the loop might modify @samp{I} or @samp{J}.
1723 So, the above implementation is used,
1724 though a more optimal one can be used
1725 in specific circumstances.
1727 @node Transforming Iterative DO
1728 @subsection Transforming Iterative DO
1730 An iterative @code{DO} loop
1731 (one that specifies an iteration variable)
1732 is required by the Fortran standards
1733 to be implemented as though an iteration count
1734 is computed before entering the loop body,
1735 and that iteration count used to determine
1736 the number of times the loop body is to be performed
1737 (assuming the loop isn't cut short via @code{GOTO} or @code{EXIT}).
1739 The FFE handles this by allocating a temporary variable
1740 to contain the computed number of iterations.
1741 Since this variable must be in a scope that includes the entire loop,
1742 a GBEL block is created for that loop,
1743 and the variable declared as belonging to the scope of that block.
1745 @node Transforming Block IF
1746 @subsection Transforming Block IF
1752 CHARACTER*(*) A, B, C
1755 IF (LFUNC (A//B)) THEN
1757 ELSE IF (LFUNC (A//C)) THEN
1764 The arguments to the two calls to @samp{LFUNC}
1765 require dynamic allocation (at run time),
1766 but are not required during execution of the @code{CALL} statements.
1768 So, the scopes of those temporaries must be within blocks inside
1769 the block corresponding to the Fortran @code{IF} block.
1771 This cannot be represented ``naturally''
1772 in vanilla C, nor in GBEL.
1773 The @code{if}, @code{elseif}, @code{else},
1774 and @code{endif} constructs
1775 provided by both languages must,
1776 for a given @code{if} block,
1777 share the same C/GBE block.
1779 Therefore, any temporaries needed during evaluation of @samp{expr}
1780 while executing @samp{ELSE IF(expr)}
1781 must either have been predeclared
1782 at the top of the corresponding @code{IF} block,
1783 or declared within a new block for that @code{ELSE IF}---a block that,
1784 since it cannot contain the @code{else} or @code{else if} itself
1785 (due to the above requirement),
1786 actually implements the rest of the @code{IF} block's
1787 @code{ELSE IF} and @code{ELSE} statements
1788 within an inner block.
1790 The FFE takes the latter approach.
1792 @node Transforming SELECT CASE
1793 @subsection Transforming SELECT CASE
1795 @code{SELECT CASE} poses a few interesting problems for code generation,
1796 if efficiency and frugal stack management are important.
1798 Consider @samp{SELECT CASE (I('PREFIX'//A))},
1799 where @samp{A} is @code{CHARACTER*(*)}.
1800 In a case like this---basically,
1801 in any case where largish temporaries are needed
1802 to evaluate the expression---those temporaries should
1803 not be ``live'' during execution of any of the @code{CASE} blocks.
1805 So, evaluation of the expression is best done within its own block,
1806 which in turn is within the @code{SELECT CASE} block itself
1807 (which contains the code for the CASE blocks as well,
1808 though each within their own block).
1810 Otherwise, we'd have the rough equivalent of this pseudo-code:
1816 libg77_catenate (temp, 'prefix', a);
1826 And that would leave temp[large] in scope during the CASE blocks
1827 (although a clever back end *could* see that it isn't referenced
1828 in them, and thus free that temp before executing the blocks).
1830 So this approach is used instead:
1839 libg77_catenate (temp1, 'prefix', a);
1851 Note how @samp{temp1} goes out of scope before starting the switch,
1852 thus making it easy for a back end to free it.
1854 The problem @emph{that} solution has, however,
1855 is with @samp{SELECT CASE('prefix'//A)}
1856 (which is currently not supported).
1858 Unless the GBEL is extended to support arbitrarily long character strings
1859 in its @code{case} facility,
1860 the FFE has to implement @code{SELECT CASE} on @code{CHARACTER}
1861 (probably excepting @code{CHARACTER*1})
1863 @code{if}, @code{elseif}, @code{else}, and @code{endif} constructs
1866 To prevent the (potentially large) temporary,
1867 needed to hold the selected expression itself (@samp{'prefix'//A}),
1868 from being in scope during execution of the @code{CASE} blocks,
1869 two approaches are available:
1873 Pre-evaluate all the @code{CASE} tests,
1874 producing an integer ordinal that is used,
1875 a la @samp{temp0} in the earlier example,
1876 as if @samp{SELECT CASE(temp0)} had been written.
1878 Each corresponding @code{CASE} is replaced with @samp{CASE(@var{i})},
1879 where @var{i} is the ordinal for that case,
1880 determined while, or before,
1881 generating the cascade of @code{if}-related constructs
1882 to cope with @code{CHARACTER} selection.
1885 Make @samp{temp0} above just
1886 large enough to hold the longest @code{CASE} string
1887 that'll actually be compared against the expression
1888 (in this case, @samp{'prefix'//A}).
1890 Since that length must be constant
1891 (because @code{CASE} expressions are all constant),
1892 it won't be so large,
1893 and, further, @samp{temp1} need not be dynamically allocated,
1894 since normal @code{CHARACTER} assignment can be used
1895 into the fixed-length @samp{temp0}.
1898 Both of these solutions require @code{SELECT CASE} implementation
1899 to be changed so all the corresponding @code{CASE} statements
1900 are seen during the actual code generation for @code{SELECT CASE}.
1902 @node Transforming Expressions
1903 @section Transforming Expressions
1905 The interactions between statements, expressions, and subexpressions
1906 at program run time can be viewed as:
1909 @var{action}(@var{expr})
1912 Here, @var{action} is the series of steps
1913 performed to effect the statement,
1914 and @var{expr} is the expression
1915 whose value is used by @var{action}.
1917 Expanding the above shows a typical order of events at run time:
1921 Perform @var{action}, using result of evaluation of @var{expr}
1922 Clean up after evaluating @var{expr}
1925 So, if evaluating @var{expr} requires allocating memory,
1926 that memory can be freed before performing @var{action}
1927 only if it is not needed to hold the result of evaluating @var{expr}.
1928 Otherwise, it must be freed no sooner than
1929 after @var{action} has been performed.
1931 The above are recursive definitions,
1932 in the sense that they apply to subexpressions of @var{expr}.
1934 That is, evaluating @var{expr} involves
1935 evaluating all of its subexpressions,
1936 performing the @var{action} that computes the
1937 result value of @var{expr},
1938 then cleaning up after evaluating those subexpressions.
1940 The recursive nature of this evaluation is implemented
1941 via recursive-descent transformation of the top-level statements,
1942 their expressions, @emph{their} subexpressions, and so on.
1944 However, that recursive-descent transformation is,
1945 due to the nature of the GBEL,
1946 focused primarily on generating a @emph{single} stream of code
1947 to be executed at run time.
1949 Yet, from the above, it's clear that multiple streams of code
1950 must effectively be simultaneously generated
1951 during the recursive-descent analysis of statements.
1953 The primary stream implements the primary @var{action} items,
1954 while at least two other streams implement
1955 the evaluation and clean-up items.
1957 Requirements imposed by expressions include:
1961 Whether the caller needs to have a temporary ready
1962 to hold the value of the expression.
1968 @node Internal Naming Conventions
1969 @section Internal Naming Conventions
1971 Names exported by FFE modules have the following (regular-expression) forms.
1972 Note that all names beginning @code{ffe@var{mod}} or @code{FFE@var{mod}},
1973 where @var{mod} is lowercase or uppercase alphanumerics, respectively,
1974 are exported by the module @code{ffe@var{mod}},
1975 with the source code doing the exporting in @file{@var{mod}.h}.
1976 (Usually, the source code for the implementation is in @file{@var{mod}.c}.)
1978 Identifiers that don't fit the following forms
1979 are not considered exported,
1980 even if they are according to the C language.
1981 (For example, they might be made available to other modules
1982 solely for use within expansions of exported macros,
1983 not for use within any source code in those other modules.)
1987 The single typedef exported by the module.
1989 @item FFE@var{umod}_[A-Z][A-Z0-9_]*
1990 (Where @var{umod} is the uppercase for of @var{mod}.)
1992 A @code{#define} or @code{enum} constant of the type @code{ffe@var{mod}}.
1994 @item ffe@var{mod}[A-Z][A-Z][a-z0-9]*
1995 A typedef exported by the module.
1997 The portion of the identifier after @code{ffe@var{mod}} is
1998 referred to as @code{ctype}, a capitalized (mixed-case) form
2001 @item FFE@var{umod}_@var{type}[A-Z][A-Z0-9_]*[A-Z0-9]?
2002 (Where @var{umod} is the uppercase for of @var{mod}.)
2004 A @code{#define} or @code{enum} constant of the type
2005 @code{ffe@var{mod}@var{type}},
2006 where @var{type} is the lowercase form of @var{ctype}
2007 in an exported typedef.
2009 @item ffe@var{mod}_@var{value}
2010 A function that does or returns something,
2011 as described by @var{value} (see below).
2013 @item ffe@var{mod}_@var{value}_@var{input}
2014 A function that does or returns something based
2015 primarily on the thing described by @var{input} (see below).
2018 Below are names used for @var{value} and @var{input},
2019 along with their definitions.
2023 A column number within a line (first column is number 1).
2026 An encapsulation of a file's name.
2029 Looks up an instance of some type that matches specified criteria,
2030 and returns that, even if it has to create a new instance or
2031 crash trying to find it (as appropriate).
2034 Initializes, usually a module. No type.
2037 A generic integer of type @code{int}.
2040 A generic integer that contains a true (non-zero) or false (zero) value.
2043 A generic integer that contains the length of something.
2046 A line number within a source file,
2047 or a global line number.
2050 Looks up an instance of some type that matches specified criteria,
2051 and returns that, or returns nil.
2054 A @code{text} that points to a name of something.
2057 Makes a new instance of the indicated type.
2058 Might return an existing one if appropriate---if so,
2059 similar to @code{find} without crashing.
2062 Pointer to a particular character (line, column pairs)
2063 in the input file (source code being compiled).
2066 Performs some herculean task. No type.
2069 Terminates, usually a module. No type.
2072 A @code{char *} that points to generic text.