Diseño de LFortran

The native prompt and optional Xeus kernel share an interactive evaluation and runtime input API.

Descripción general de alto nivel

LFortran está estructurado en torno a dos módulos independientes, AST y ASR, los cuales son independientes (completamente independientes del resto de LFortran) y se anima a los usuarios a usarlos de forma independiente para otras aplicaciones y crear herramientas en la parte superior:

  • Árbol de sintaxis abstracta (AST), módulo lfortran.ast: representa cualquier código fuente de Fortran, basado estrictamente en la sintaxis, no se incluye semántica. El módulo AST puede convertirse en código fuente de Fortran.

  • Representación semántica abstracta (ASR), módulo lfortran.asr: Representa un código fuente de Fortran válido, se incluye toda la semántica. No se permite el código Fortran no válido (se dará un error). El módulo ASR puede convertirse en un AST.

El compilador LFortran está compuesto por las siguientes etapas independientes:

  • Análisis: convierte el código fuente de Fortran en un AST

  • Semántica: Convertir un AST para un ASR

  • Optimización de alto nivel: optimizar ASR para un ASR posiblemente mas simple y mas rápido (cosas como alinear funciones, eliminar expresiones o declaraciones redundantes, etc.)

  • Generación de código LLVM IR y optimizaciones de nivel inferior: convierte un ASR en un LLVM IR. Esta etapa también realiza todas las demás optimizaciones que no producen un ASR, pero que aún tiene sentido antes de pasar a LLVM IR.

  • Generación de código de máquina: LLVM luego realiza todas sus optimizaciones y genera código de máquina (como un ejecutable binario, una biblioteca, un archivo de objeto, o se carga y ejecuta usando JIT como parte de la sesión interactiva de LFortran o en un núcleo de Jupyter).

The function_result_scope ASR pass also gives a statement scope to scalar constructor temporaries assigned to allocatable targets when the type has only numeric/logical components, owns allocatable array storage, and has no final subroutines (including inherited ones). The existing BLOCK lifetime initializes their component descriptors only when the constructor executes and releases their private storage after the assignment. Descriptor layout and ownership are unchanged. Types with pointers, nested derived components or user finalization keep their existing lifetime.

LFortran está estructurado como una biblioteca, por lo que, por ejemplo, se puede usar el analizador para obtener un AST y hacer algo con él, o se puede usar el analizador semántico para obtener ASR y hacer algo con él. Uno puede generar la ASR directamente (por ejemplo, desde SymPy) y luego convertirlo a AST y a un código fuente de Fortran, o usar LFortran para compilarlo en código de máquina directamente. En otras palabras, uno puede usar LFortran para convertir fácilmente entre las tres representaciones equivalentes:

  • Código fuente de Fortran

  • Árbol de sintaxis abstracta (AST)

  • Representación semántica abstracta (ASR)

Estos son todos equivalentes en el siguiente sentido:

  • Cualquier ASR puede siempre ser convertido a un AST equivalente

  • Cualquier AST puede ser siempre convertido a un código fuente Fortran equivalente

  • Cualquier código fuente de Fortran siempre se puede convertir a un AST equivalente o se obtiene un error de sintaxis

  • Cualquier AST siempre se puede convertir a un ASR equivalente o se obtiene un error semántico

Así, cuando se puede realizar una conversión estos son equivalentes, y la conversión siempre se puede realizar a menos que el código no sea válido.

Detalles de diseño de una ASR

Una ASR está diseñada para tener las características siguientes:

  • Una ASR sigue siendo semánticamente equivalente al código Fortran original (esta no pierde información semántica). Una ASR puede ser convertida a un AST, y un AST a un código fuente Fortran que es funcionalmente equivalente al original.

  • Una ASR es lo más simple posible: no contiene ninguna información que no pueda deducirse de una ASR.

  • Las clases ASR C++ (en el futuro) están diseñadas de manera similar a SymEngine: se construyen una vez y luego son inmutables. El constructor verifica en modo depuración que se cumplan todos los requisitos (por ejemplo, que todas las variables en una función tengan un conjunto de argumentos ficticios, que las matrices de forma explícita no se puedan asignar y todos los demás requisitos de Fortran para que sea un código válido), pero en modo de lanzamiento, construye rápidamente la clase sin controles. Luego, hay clases de constructores que construyen las clases ASR C++ para cumplir con los requisitos (verificados en el modo de depuración) y el constructor da un mensaje de error si un código no es un código Fortran válido, y si no da un mensaje de error, entonces las clases ASR C++ están construidas correctamente. Así, por construcción, las clases ASR siempre contienen código Fortran válido y el resto de LFortran puede depender de él.

C++ procedure arguments

The C++ backend represents source-ABI procedure dummies as callable template parameters. Actual procedures are wrapped in generic lambdas so that array descriptor templates are specialized when the callback is invoked. Each array dummy has its own template parameter: equal element kind and rank do not imply equal descriptor types or extents. This is a C++ representation choice; the Fortran interface and argument conversion remain determined by ASR.

Compilation Modes

We support two compilation modes:

  1. Monolithic Compilation Mode: The standard compilation mode. In this mode, LFortran produces empty object files (.o files) with -c flag (the only reason to produce those is to satisfy existing build systems that typically expect .o files to be created). The object code is generated only when main program is encountered: all modules are loaded from .mod files and everything compiled and linked at once. When a module is compiled, only a .mod file is generated with full code. For files with global procedures, LFortran identifies those automatically and sets generate_code_for_global_procedures compiler option to true (not exposed to user), which then generates object code only for global procedures (you must thus link these generated .o object files with the main program), and rest of the modules are serialized to .mod files which do not contain global procedure.

  2. Separate Compilation Mode: This mode is enabled with --separate-compilation flag. In this mode, LFortran generates full code for each file into object files (.o files) with full symbol information. This is usually the default mode used by most other Fortran compilers. We create object code, and we still create .mod files for modules and they contain everything just like for direct mode but when any .mod file is loaded, we change all symbols to ExternalUndefined ABI. We don’t change the ABI for bind(c) (since those are undefined already in object code, the user is responsible to provide an implementation at link time).

Note: If you enable separate compilation mode, you have to enable it for all the files.

Descriptor entry wrappers

The array-by-data pass can make a retained descriptor-ABI subroutine an entry wrapper for its existing data-ABI specialization. The exported signature and type-bound procedure/vtable references still name the original descriptor entry, including across separately compiled modules. The normal call conversion handles runtime contiguity and copies strided inputs while preserving bounds and extents. Only required, ordinary numeric assumed-shape intent(in) arrays qualify; pointer, allocatable, TARGET, VOLATILE, ASYNCHRONOUS and coarray dummies do not. Scalar arguments must be numeric or derived-type receivers. In particular, logical presence flags introduced by optional-argument lowering exclude an entry. Procedures with saved local state, contained procedures, observable array addresses/contiguity, or forwarding of an input descriptor are left unchanged. Unused automatic locals are removed from the wrapper, but declarations needed by its signature remain.

Repeated Pure Array Calls

With --fast, the array-temporary ASR pass can reuse a pure real-array function result within one ordinary arithmetic assignment. Calls must have the same procedure, receiver, and variable actuals; aliased, volatile, asynchronous, coarray, and unsafe dummy arguments are excluded. The pass uses the normal temporary allocation and call preparation paths, and does not reuse results across statements or hoist conditional evaluations. OpenMP, coarray, Metal, and CUDA modes disable this optimization because a pure procedure can still read nonlocal state.

LLVM Alias Information

With --fast, the LLVM backend uses Fortran dummy-argument restrictions to mark eligible parameters noalias. It also distinguishes array data from compiler-managed descriptors and struct pointer fields using TBAA. Numeric and logical elements share one data class, so this metadata does not claim that two data arrays cannot overlap.

For direct component accesses through nonpointer, non-TARGET CLASS variables, ASR storage facts distinguish inline numeric/logical components from elements of numeric/logical allocatable array components. These are sibling subclasses of data: allocated payload cannot overlap inline object storage, but generic pointer-array data remains their parent and may alias either. Scalar allocatable payloads, pointer members, nested component receivers, ordinary TYPE receivers, and byte/character accesses receive no new classification. VOLATILE, ASYNCHRONOUS (including scoped declarations), and coarray receivers or members are excluded. The backend records the component provenance while lowering ASR, before LLVM addresses lose it; it does not infer ownership from LLVM types.

Lowered function results retain the explicit ResultArgument storage role; the backend does not infer that role from dummy position or type. A C_PTR passed as a C address is not a restricted Fortran object’s address and is not annotated noalias. Scoped ASYNCHRONOUS/VOLATILE redeclarations are represented by ScopedVariableAttribute, referring to the canonical host/use-associated variable without changing its declaration. Such regions also exclude the variable from whole-procedure alias promises and dead whole-array store elimination.

The data class also includes the elements of numeric and logical explicit-shape and assumed-size dummy arguments, TARGET ones too: a TARGET dummy argument is the one kind of dummy argument that is not noalias, and without the data class a store to its elements would force a loop to reload the descriptors of the allocatable arrays it reads, and keep it from vectorizing. The globals that hold the pointer to the descriptor of a module allocatable or pointer array are descriptor memory.

The data class includes owned local automatic and fixed-size arrays, but not raw local storage associated through EQUIVALENCE or COMMON, saved storage, or storage whose address is taken with C_LOC. Raw local VOLATILE, ASYNCHRONOUS, and coarray storage is excluded too. Ambiguous accesses, byte accesses, and memory-copy intrinsics remain untagged. Fresh _lfortran_malloc_alloc results are noalias; reallocations are not. These optimizer hints are disabled in default mode and for OpenMP, coarray, and GPU offload configurations.

COMMON Blocks

A COMMON block is storage that every scoping unit declaring it shares, while each unit gives it a layout of its own. The ASR keeps that layout with the unit: a scoping unit that declares a block owns a CommonBlock symbol, its view of the block, which lists the unit’s own variables in order (members) and places the variables that EQUIVALENCE connects to the block (associations). In interactive use, a block declared at the top level has its view in the global scope. Each of those variables points back to the view through Variable.common_block, and a Var refers to it like to any other variable. A module variable in a COMMON block is an ordinary module variable for the units that use the module: it is imported through an ExternalSymbol, and its view is stored in the module file together with it.

Views are connected only through link_name, the global symbol of the storage, which is the same in every view of a block. Nothing matches the variables of two views by name. The views in the ASR are the only persistent record of a block: the frontend makes up no module, derived type or module file for it, and keeps no side table of layouts across scoping units. A backend derives the layout of each link_name locally while it emits a translation unit: it combines the views of one link_name into a single definition and addresses every variable at the position its own view gives it. On targets with common symbols, the linker combines the definitions of different object files. The LLVM WebAssembly target has no common symbols and no way to size a block at run time, so it supports a program lowered as one translation unit: definitions of one block in separate objects conflict at link time.

The role of a view says what its definition is. A view whose variables have initializers is Initialized, even if every value is zero. These are the views of a BlockData unit: the unit has no statements, and its DATA values are the initializers of its own variables, so its object file defines the storage with those values, in both compilation modes. A view without initial values is Tentative, or External when the storage is defined elsewhere: by the object file of a module read from its module file, or by an earlier interactive cell, after which the block cannot grow or be given initial values. See CommonBlock.

Host Association

An internal procedure reaches the variables of its host by host association: it uses the same storage as the instance of the host that invoked it, not a copy (F2018 19.5.1.4). A recursive host has one instance per active call, so that storage cannot be a global variable. The ASR that the frontend produces keeps the internal procedure nested in its host, and its Vars refer directly to the variables of the host.

The nested_vars pass lowers this into ASR that every backend can emit without knowing about nesting. Every instance of a host gets a frame: a local variable of a derived type declared in the host, with one member per host variable that its internal procedures use. A member of Reference type holds the address of the host variable, which the host stores with BindReference at the start of its body. Nothing is copied, so allocation status, bounds, dynamic type, target identity and storage association are those of the host variable. An internal procedure gets the frame as its last dummy argument, and in it every host variable is replaced by a variable of HostAssociated storage: an alias with the type of the host variable, bound on entry to the variable that its symbolic_value designates through the frame. Such a variable has no storage of its own (ASRUtils::has_own_storage), so it is never allocated, initialized, finalized or deallocated by the internal procedure.

A non-allocatable, non-pointer array or character variable, whose representation the host fixes at run time, and a dummy procedure are reached through a pointer view: a local pointer of the host, associated with the variable at the start of its body, which the member then refers to. Named constants of the host are copied into the internal procedure. An internal procedure of an internal procedure (an extension) reaches the variables of the outer host through the aliases of the procedure it is nested in, whose own frame refers to them; the pass processes the hosts from the outside in. Calls between the internal procedures of a host pass on the frame dummy.

A procedure value of an internal procedure that needs the frame (an actual argument, a pointer target, the interface of a procedure variable, the callback of a defined output procedure) cannot pass it. It names instead a thunk: a procedure of the host with the interface of the internal procedure, which calls it with the frame that the host’s frame slot, a Save pointer of the host, points to. A statement that makes a procedure value points the slot at the frame of its instance first, and every instance of the host saves the slot when it starts and restores it before it returns. So a procedure value reaches the instance that made it, unless a newer instance of the same host has made a procedure value since and is still active; values that carry their frame would be exact in that case too. A call in an interface body to a procedure of the host that reads one of its variables for a bound or a length (import :: n) uses a thunk the same way. The thunks and the procedures that make procedure values read the slot directly, so a backend must resolve a saved variable of the host there (ASRUtils::is_frame_slot).

The ASR after this pass is not valid Fortran: a member of Reference type and a HostAssociated variable have no Fortran syntax, and --show-fortran prints them as reference, host_associated and bind_reference(...).

Notas:

Información que se pierde al analizar la fuente en un AST: espacios en blanco, distinción de declaración if de varias líneas/una sola línea, distinción entre mayúsculas y minúsculas de palabras clave.

Información que se pierde al pasar de un AST a una ASR: sintaxis detallada, cómo se definieron las variables y el orden de los atributos de tipo (si la dimensión de matriz usa el atributo dimensión o paréntesis en la variable, o cuántas variables hay por línea de declaración o su orden), ya que una ASR solo representa la información de tipo agregada en la tabla de símbolos.

Una ASR es la forma más sencilla de generar código Fortran, ya que uno no tiene que preocuparse por la sintaxis detallada (como en un AST) sobre cómo y dónde se declaran las cosas. Uno especifica la tabla de símbolos para un módulo, luego para cada símbolo (funciones, variables globales, tipos, …) uno especifica las variables locales y si se trata de una interfaz, entonces uno necesita especificar dónde puede encontrar una implementación, de lo contrario un cuerpo se suministra con declaraciones, esos nodos son casi los mismos que en un AST, excepto que cada variable es solo una referencia a un símbolo en la tabla de símbolos (por lo que, por construcción, uno no puede tener variables indefinidas). La tabla de símbolos para cada nodo, como Función o Módulo, también hace referencia a su padre (por ejemplo, una función hace referencia a un módulo, un módulo hace referencia al ámbito global).

Una ASR se puede convertir directamente en un AST sin recopilar ninguna otra información. Y un AST directamente al código fuente de Fortran.

Una ASR siempre representa un código Fortran semánticamente válido. Esto se aplica mediante comprobaciones en los constructores de una ASR C++ (en la compilación de depuración). Cuando se utiliza una ASR, se puede suponer que es válido.

Conditional Expressions and Conditional Arguments

A conditional expression (F2023 10.1.2.3), ( cond ? a : b ), is an ordinary expression and becomes the ConditionalExpr AST node. A conditional argument (15.5.1) has the same syntax but appears in an actual argument position, where it selects the actual argument itself rather than a value: a consequent that is a variable stays definable, and a consequent of .NIL. (6.2.1) means the dummy argument is not present.

Only the context tells the two apart (C1535), so the parser does not. .NIL. is a token of its own (6.2.1) rather than a named constant or a defined operator, matched ahead of the defined-operator rule in the tokenizer, and a single cond_consequent production — an expression, a variable or .NIL. — is shared by both places a conditional expression is parsed. .NIL. therefore reaches the AST as the Nil expression node from any consequent position.

The semantic layer then rejects Nil wherever a value is required, and expands a conditional argument by duplicating the procedure reference into the arms of a selection, one copy per consequent, so that every copy is an ordinary reference that the existing argument checks apply to.

Fortran 2008

Fortran 2008 estándar capítulo 2 «Conceptos de Fortran» especifica que el código Fortran es una colección de unidades de programa (ya sea todo en un archivo , o en archivos separados), donde cada unidad de programa es una de:

  • programa principal

  • módulo o submódulo

  • función o subrutina

Nota: También puede ser una unidad de programa de bloques de datos, que se utiliza para proporcionar valores iniciales para objetos de datos en bloques comunes con nombre, pero no recomendamos el uso de bloques comunes (utilice módulos en su lugar).

Extensión LFortran

Extendemos el lenguaje Fortran introduciendo un alcance global, que no es sola la lista de unidades de programa (como en F2800) sino que puede también incluir declaraciones, expresiones y declaraciones de uso. Definimos alcance global como una colección de los elementos siguientes:

  • programa principal

  • módulo o submódulo

  • función o subrutina

  • declaración de uso

  • declaración

  • declaración

  • expresión

Además, si una variable no está definida en una instrucción de asignación (como x = 5+3), el tipo de variable se deduce del lado derecho (por ejemplo, x en x = 5+3). sería de tipointeger, y yeny = 5._dpsería de tiporeal(dp)`). Esta regla solo se aplica en el nivel superior de alcance global. Los tipos deben especificarse completamente dentro de los programas, módulos, funciones y subrutinas principales, al igual que en F2008.

El alcance global tiene su propia tabla de símbolos. El programa principal y el módulo/submódulo no ven ningún símbolo de esta tabla de símbolos. Pero las funciones, subrutinas, declaraciones y expresiones en el nivel superior del alcance global usan y operan en esta tabla de símbolos.

El alcance global tiene los siguientes símbolos predefinidos en la tabla de símbolos:

  • el conjunto estándar habitual de funciones de Fortran (como size, sin, cos, …)

  • el símbolo de doble precisión dp, por lo que se puede usar 5._dp para doble precisión.

Cada elemento del alcance global se interpreta de la siguiente manera: el programa principal se compila en un ejecutable con el mismo nombre y se ejecuta; se compilan y cargan módulos, funciones y subrutinas; use sentencia y declaración agrega esos símbolos con el tipo adecuado en la tabla de símbolos alcance global, pero no genera ningún código; la declaración se envuelve en una subrutina anónima sin argumentos, se compila, se carga y se ejecuta; expresión se envuelve en una función anónima sin argumentos que devuelven la expresión, compilada, cargada, ejecutada y el valor de retorno se devuelve al usuario.

El alcance global siempre se interpreta, elemento por elemento, según el párrafo anterior. Está destinado a permitir el uso interactivo, la experimentación y la escritura de scripts simples. El código en alcance global debe interpretarse usando lfortran. Para código más complejo (de producción), se recomienda convertirlo en módulos y programas (envolviendo sentencias sueltas en subrutinas o funciones y agregando declaraciones de tipo) y compilarlo con lfortran o cualquier otro compilador de Fortran.

Aquí algunos ejemplos de código válidos en alcance global:

Ejemplo 1

a = 5
print *, a

Ejemplo 2

a = 5

subroutine p()
print *, a
end subroutine

call p()

Ejemplo 3

module a
implicit none
integer :: i
end module

use a, only: i
i = 5

Ejemplo 4

x = [1, 2, 3]
y = [1, 2, 1]
call plot(x, y, "o-")

Consideraciones de diseño

La extensión LFortran de Fortran se eligió de manera que se minimice el número de cambios. En particular, solo el nivel superior del alcance global ha relajado algunas de las reglas de Fortran (como hacer que la especificación de tipos sea opcional) para permitir un uso interactivo simple y rápido, pero dentro de las funciones, subrutinas, módulos o programas, esta relajación no se aplica.

El número de cambios se mantuvo al mínimo para que sea sencillo convertir el código en alcance global en código Fortran compatible con el estándar utilizando programas y módulos, de modo que pueda ser compilado por cualquier compilador de Fortran.