Spec-Zone.ru › GNU Fortran 5

2.9 Параметры генерации кода

Эти независимые от машины параметры управляют соглашениями об интерфейсе, используемыми при генерации кода.

Большинство из них имеют положительную и отрицательную формы; отрицательная форма -ffoo будет -fno-foo. В таблице ниже представлена только одна из форм — та, которая не является стандартной. Вы можете определить другую форму, удалив no- или добавив её.

-fno-automatic
Treat each program unit (except those marked as RECURSIVE) as if the SAVE statement were specified for every local variable and array referenced in it. Does not affect common blocks. (Some Fortran compilers provide this option under the name -static or -save.) The default, which is -fautomatic, uses the stack for local variables smaller than the value given by -fmax-stack-var-size. Use the option -frecursive to use no static memory.
-ff2c
Generate code designed to be compatible with code generated by g77 and f2c.

The calling conventions used by g77 (originally implemented in f2c) require functions that return type default REAL to actually return the C type double, and functions that return type COMPLEX to return the values via an extra argument in the calling sequence that points to where to store the return value. Under the default GNU calling conventions, such functions simply return their results as they would in GNU C—default REAL functions return the C type float, and COMPLEX functions return the GNU C type complex. Additionally, this option implies the -fsecond-underscore option, unless -fno-second-underscore is explicitly requested.

This does not affect the generation of code that interfaces with the libgfortran library.

Caution: It is not a good idea to mix Fortran code compiled with -ff2c with code compiled with the default -fno-f2c calling conventions as, calling COMPLEX or default REAL functions between program parts which were compiled with different calling conventions will break at execution time.

Caution: This will break code which passes intrinsic functions of type default REAL or COMPLEX as actual arguments, as the library implementations use the -fno-f2c calling conventions.

-fno-underscoring
Do not transform names of entities specified in the Fortran source file by appending underscores to them.

With -funderscoring in effect, GNU Fortran appends one underscore to external names with no underscores. This is done to ensure compatibility with code produced by many UNIX Fortran compilers.

Caution: The default behavior of GNU Fortran is incompatible with f2c and g77, please use the -ff2c option if you want object files compiled with GNU Fortran to be compatible with object code created with these tools.

Use of -fno-underscoring is not recommended unless you are experimenting with issues such as integration of GNU Fortran into existing system environments (vis-à-vis existing libraries, tools, and so on).

For example, with -funderscoring, and assuming that j() and max_count() are external functions while my_var and lvar are local variables, a statement like

I = J() + MAX_COUNT (MY_VAR, LVAR)

is implemented as something akin to:

i = j_() + max_count__(&my_var__, &lvar);

With -fno-underscoring, the same statement is implemented as:

i = j() + max_count(&my_var, &lvar);

Use of -fno-underscoring allows direct specification of user-defined names while debugging and when interfacing GNU Fortran code with other languages.

Note that just because the names match does not mean that the interface implemented by GNU Fortran for an external name matches the interface implemented by some other language for that same name. That is, getting code produced by GNU Fortran to link to code produced by some other compiler using this or any other method can be only a small part of the overall solution—getting the code generated by both compilers to agree on issues other than naming can require significant effort, and, unlike naming disagreements, linkers normally cannot detect disagreements in these other areas.

Also, note that with -fno-underscoring, the lack of appended underscores introduces the very real possibility that a user-defined external name will conflict with a name in a system library, which could make finding unresolved-reference bugs quite difficult in some cases—they might occur at program run time, and show up only as buggy behavior at run time.

In future versions of GNU Fortran we hope to improve naming and linking issues so that debugging always involves using the names as they appear in the source, even if the names as seen by the linker are mangled to prevent accidental linking between procedures with incompatible interfaces.

-fsecond-underscore
By default, GNU Fortran appends an underscore to external names. If this option is used GNU Fortran appends two underscores to names with underscores and one underscore to external names with no underscores. GNU Fortran also appends two underscores to internal names with underscores to avoid naming collisions with external names.

This option has no effect if -fno-underscoring is in effect. It is implied by the -ff2c option.

Otherwise, with this option, an external name such as MAX_COUNT is implemented as a reference to the link-time external symbol max_count__, instead of max_count_. This is required for compatibility with g77 and f2c, and is implied by use of the -ff2c option.

-fcoarray=<keyword>
‘none’
Disable coarray support; using coarray declarations and image-control statements will produce a compile-time error. (Default)
‘single’
Single-image mode, i.e. num_images() is always one.
‘lib’
Library-based coarray parallelization; a suitable GNU Fortran coarray library needs to be linked.
-fcheck=<keyword>
Enable the generation of run-time checks; the argument shall be a comma-delimited list of the following keywords.
‘all’
Enable all run-time test of -fcheck.
‘array-temps’
Warns at run time when for passing an actual argument a temporary array had to be generated. The information generated by this warning is sometimes useful in optimization, in order to avoid such temporaries.

Note: The warning is only printed once per location.

‘bounds’
Enable generation of run-time checks for array subscripts and against the declared minimum and maximum values. It also checks array indices for assumed and deferred shape arrays against the actual allocated bounds and ensures that all string lengths are equal for character array constructors without an explicit typespec.

Some checks require that -fcheck=bounds is set for the compilation of the main program.

Note: In the future this may also include other forms of checking, e.g., checking substring references.

‘do’
Enable generation of run-time checks for invalid modification of loop iteration variables.
‘mem’
Enable generation of run-time checks for memory allocation. Note: This option does not affect explicit allocations using the ALLOCATE statement, which will be always checked.
‘pointer’
Enable generation of run-time checks for pointers and allocatables.
‘recursion’
Enable generation of run-time checks for recursively called subroutines and functions which are not marked as recursive. See also -frecursive. Note: This check does not work for OpenMP programs and is disabled if used together with -frecursive and -fopenmp.
-fbounds-check
Deprecated alias for -fcheck=bounds.
-fcheck-array-temporaries
Deprecated alias for -fcheck=array-temps.
-fmax-array-constructor=n
This option can be used to increase the upper limit permitted in array constructors. The code below requires this option to expand the array at compile time.
program test
implicit none
integer j
integer, parameter :: n = 100000
integer, parameter :: i(n) = (/ (2*j, j = 1, n) /)
print '(10(I0,1X))', i
end program test

Caution: This option can lead to long compile times and excessively large object files.

The default value for n is 65535.

-fmax-stack-var-size=n
This option specifies the size in bytes of the largest array that will be put on the stack; if the size is exceeded static memory is used (except in procedures marked as RECURSIVE). Use the option -frecursive to allow for recursive procedures which do not have a RECURSIVE attribute or for parallel programs. Use -fno-automatic to never use the stack.

This option currently only affects local arrays declared with constant bounds, and may not apply to all character variables. Future versions of GNU Fortran may improve this behavior.

The default value for n is 32768.

-fstack-arrays
Adding this option will make the Fortran compiler put all local arrays, even those of unknown size onto stack memory. If your program uses very large local arrays it is possible that you will have to extend your runtime limits for stack memory on some operating systems. This flag is enabled by default at optimization level -Ofast.
-fpack-derived
This option tells GNU Fortran to pack derived type members as closely as possible. Code compiled with this option is likely to be incompatible with code compiled without this option, and may execute slower.
-frepack-arrays
In some circumstances GNU Fortran may pass assumed shape array sections via a descriptor describing a noncontiguous area of memory. This option adds code to the function prologue to repack the data into a contiguous block at runtime.

This should result in faster accesses to the array. However it can introduce significant overhead to the function call, especially when the passed data is noncontiguous.

-fshort-enums
This option is provided for interoperability with C code that was compiled with the -fshort-enums option. It will make GNU Fortran choose the smallest INTEGER kind a given enumerator set will fit in, and give all its enumerators this kind.
-fexternal-blas
This option will make gfortran generate calls to BLAS functions for some matrix operations like MATMUL, instead of using our own algorithms, if the size of the matrices involved is larger than a given limit (see -fblas-matmul-limit). This may be profitable if an optimized vendor BLAS library is available. The BLAS library will have to be specified at link time.
-fblas-matmul-limit=n
Только если -fexternal-blas включено. Умножение матриц с размером, большим или равным n, будет выполняться с помощью функций BLAS, в то время как другие будут обрабатываться внутренними алгоритмами gfortran. Если участвующие матрицы не квадратные, сравнение размеров выполняется, используя геометрическое среднее измерений матриц аргумента и результата.

Значение по умолчанию для n составляет 30.

-frecursive
Разрешить косвенную рекурсию, принуждая все локальные массивы быть выделенными в стеке. Этот флаг не может использоваться вместе с -fmax-stack-var-size= или -fno-automatic.
-finit-local-zero
-finit-integer=n
-finit-real=<zero|inf|-inf|nan|snan>
-finit-logical=<true|false>
-finit-character=n
Опция -finit-local-zero указывает компилятору инициализировать локальные переменные типа INTEGER, REAL, и COMPLEX нулём, переменные типа LOGICAL значением false, и переменные типа CHARACTER строкой нулевых байтов. Более точные параметры инициализации предоставляются опциями -finit-integer=n, -finit-real=<zero|inf|-inf|nan|snan> (которая также инициализирует вещественную и мнимую части локальных переменных типа COMPLEX), -finit-logical=<true|false> и -finit-character=n (где n – значение ASCII символа). Эти опции не инициализируют
  • динамические массивы
  • компоненты переменных типа производного типа
  • переменные, которые появляются в инструкции EQUIVALENCE
(эти ограничения могут быть удалены в будущих версиях).

Обратите внимание, что опция -finit-real=nan инициализирует переменные REAL и COMPLEX типом quiet NaN. Для сигнализирующего NaN используйте -finit-real=snan; однако обратите внимание, что оптимизации времени компиляции могут преобразовать их в quiet NaN, и необходимо включить отслеживание (например, через -ffpe-trap).

Наконец, обратите внимание, что включение любой из опций -finit-* заглушит предупреждения, которые могли бы быть выведены -Wuninitialized для затронутых локальных переменных.

-falign-commons
По умолчанию gfortran обеспечивает правильное выравнивание всех переменных в блоке COMMON, добавляя необходимые дополнения. На некоторых платформах это обязательно, на других это увеличивает производительность. Если блок COMMON объявлен с несогласованными типами данных повсюду, это заполнение может вызвать проблемы, и -fno-align-commons может использоваться для отключения автоматического выравнивания. Один и тот же вид этой опции должен использоваться для всех файлов, которые используют блок COMMON. Чтобы избежать потенциальных проблем с выравниванием в блоках COMMON, рекомендуется упорядочивать объекты от наибольшего к наименьшему.
-fno-protect-parens
По умолчанию скобки в выражениях учитываются для всех уровней оптимизации, так что компилятор не выполняет перегруппировку. Использование -fno-protect-parens позволяет компилятору переупорядочивать выражения REAL и COMPLEX для создания более быстрого кода. Обратите внимание, что для оптимизации перегруппировки необходимо включить -fno-signed-zeros и -fno-trapping-math. Защита скобок включена по умолчанию, если не указана опция -Ofast .
-frealloc-lhs
Переменная слева от знака присваивания (allocatable left-hand side) автоматически (пере)выделяется, если она не выделена или имеет другую форму. Опция включена по умолчанию, за исключением случаев, когда указана опция -std=f95. См. также -Wrealloc-lhs.
-faggressive-function-elimination
Функции с идентичными списками аргументов устраняются внутри операторов, независимо от того, помечены ли эти функции как PURE или нет. Например, в
a = f(b,c) + f(b,c)

будет только один вызов функции f. Эта опция работает только в случае, если -ffrontend-optimize включена.

-ffrontend-optimize
Эта опция выполняет оптимизацию на стадии переднего плана, основанную на манипулировании частями синтаксического дерева Fortran. Включена по умолчанию с любой опцией -O. Оптимизации, включенные этой опцией, включают удаление идентичных вызовов функций внутри выражений, удаление ненужных вызовов TRIM в сравнениях и присваиваниях и замена TRIM(a) на a(1:LEN_TRIM(a)). Ее можно отключить, указав -fno-frontend-optimize.

См. Опции для генерации кода, для получения информации о дополнительных опциях, предлагаемых общим интерфейсом GBE, который используется gfortran, gcc, и другими компиляторами GNU.

© Free Software Foundation
Licensed under the GNU Free Documentation License, Version 1.3.
https://gcc.gnu.org/onlinedocs/gcc-5.4.0/gfortran/Code-Gen-Options.html

Spec-Zone.ru

Настройки Оффлайн Что нового Помощь О нас
Spec-Zone .ru
спецификации, руководства, описания, API