LFortran-Design

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

Allgemeine Übersicht

LFortran ist um zwei unabhängige Module herum aufgebaut, AST und ASR, die beide eigenständig sind (völlig unabhängig vom Rest von LFortran), und die Benutzer werden ermutigt, sie unabhängig für andere Anwendungen zu verwenden und darauf aufbauende Werkzeuge zu erstellen:

  • Abstrakter Syntaxbaum (abstract syntax tree, AST), Modul lfortran.ast: Stellt einen beliebigen Fortran-Quellcode dar, der ausschließlich auf der Syntax basiert und keine Semantik enthält. Das AST-Modul kann sich selbst in Fortran-Quellcode umwandeln.

  • Abstrakte semantische Repräsentation (abstract semantic representation, ASR), Modul lfortran.asr: Stellt einen gültigen Fortran-Quellcode dar, die gesamte Semantik ist enthalten. Ungültiger Fortran-Code ist nicht erlaubt (es wird ein Fehler ausgegeben). Das ASR-Modul kann sich selbst in einen AST umwandeln.

Der LFortran-Compiler setzt sich dann aus den folgenden unabhängigen Stufen zusammen:

  • Parsing: Konvertiert Fortran-Quellcode in einen AST

  • Semantisch: wandelt einen AST in eine ASR um

  • Optimierungen auf hoher Ebene: Optimierung der ASR zu einer möglicherweise schnelleren/einfacheren ASR (z. B. Inlining von Funktionen, Beseitigung redundanter Ausdrücke oder Anweisungen usw.)

  • LLVM IR-Code-Generierung und Optimierungen auf niedrigerer Ebene: wandelt eine ASR in eine LLVM IR um. In dieser Phase werden auch alle anderen Optimierungen durchgeführt, die keine ASR erzeugen, aber dennoch sinnvoll sind, bevor sie an LLVM IR übergeben werden.

  • Erzeugung von Maschinencode: LLVM führt dann alle Optimierungen durch und generiert Maschinencode (z. B. eine binäre ausführbare Datei, eine Bibliothek, eine Objektdatei, oder sie wird geladen und mit JIT als Teil der interaktiven LFortran-Sitzung oder in einem Jupyter-Kernel ausgeführt).

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 ist als Bibliothek strukturiert, und so kann man zum Beispiel den Parser verwenden, um einen AST zu erhalten und etwas damit zu tun, oder man kann dann den semantischen Analysator verwenden, um ASR zu erhalten und etwas damit zu tun. Man kann die ASR direkt generieren (z.B. aus SymPy) und dann entweder in AST und in einen Fortran-Quellcode konvertieren oder LFortran verwenden, um sie direkt in Maschinencode zu kompilieren. Mit anderen Worten, man kann LFortran verwenden, um einfach zwischen den drei äquivalenten Darstellungen zu konvertieren:

  • Fortran-Quellcode

  • Abstrakter Syntaxbaum (AST)

  • Abstrakte semantische Repräsentation (ASR)

Sie sind alle im folgenden Sinne gleichwertig:

  • Jeder ASR kann jederzeit in einen entsprechenden AST umgewandelt werden

  • Jeder AST kann jederzeit in einen entsprechenden Fortran-Quellcode konvertiert werden

  • Jeglicher Fortran-Quellcode kann immer entweder in einen äquivalenten AST konvertiert werden oder man bekommt einen Syntaxfehler

  • Jeder AST kann immer entweder in einen äquivalenten ASR umgewandelt werden oder man erhält einen semantischen Fehler

Wenn also eine Konvertierung möglich ist, sind sie gleichwertig, und die Konvertierung kann immer durchgeführt werden, es sei denn, der Code ist ungültig.

Details zum ASR-Design

Die ASR ist mit den folgenden Merkmalen ausgestattet:

  • ASR ist immer noch semantisch äquivalent zum ursprünglichen Fortran-Code (und hat keine semantischen Informationen verloren). ASR kann in AST und AST in Fortran-Quellcode konvertiert werden, welcher funktional dem Original entspricht.

  • Die ASR ist so einfach wie möglich: sie enthält keine Informationen, die nicht aus der ASR abgeleitet werden könnten.

  • Die ASR C++-Klassen (in Zukunft) sind ähnlich wie die SymEngine konzipiert: Sie werden einmal konstruiert und sind danach unveränderlich. Der Konstruktor prüft im Debug-Modus eher, ob alle Anforderungen erfüllt sind (z.B., dass alle Variablen in einer Funktion ein Dummy-Argument haben, dass explizite Arrays nicht zuweisbar sind und alle anderen Fortran-Anforderungen, um es zu einem gültigen Code zu machen), aber im Release-Modus konstruiert er die Klasse schnell und ohne Prüfungen. Dann gibt es Builder-Klassen, die die ASR-C++-Klassen so konstruieren, dass sie die Anforderungen erfüllen (die im Debug-Modus überprüft werden), und der Builder gibt eine Fehlermeldung aus, wenn ein Code kein gültiger Fortran-Code ist, und wenn er keine Fehlermeldung ausgibt, dann sind die ASR-C++-Klassen korrekt konstruiert. Somit enthalten die ASR-Klassen konstruktionsbedingt immer gültigen Fortran-Code und der Rest von LFortran kann davon abhängen.

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(...).

Anmerkungen:

Informationen, die beim Parsen des Quelltextes in den AST verloren gehen: Leerzeichen, Unterscheidung zwischen mehrzeiligen und einzeiligen if-Anweisungen, Groß- und Kleinschreibung von Schlüsselwörtern.

Informationen, die beim Übergang von AST zu ASR verloren gehen: detaillierte Syntax, wie Variablen definiert wurden, und die Reihenfolge der Typattribute (ob die Arraydimension das Attribut dimension oder Klammern bei der Variablen verwendet; oder wie viele Variablen es pro Deklarationszeile gibt oder ihre Reihenfolge), da ASR nur die aggregierten Typinformationen in der Symboltabelle darstellt.

ASR ist der einfachste Weg, Fortran-Code zu erzeugen, da man sich nicht um die detaillierte Syntax (wie in AST) kümmern muss, wie und wo Dinge deklariert werden. Man spezifiziert die Symboltabelle für ein Modul, dann gibt man für jedes Symbol (Funktionen, globale Variablen, Typen, …) die lokalen Variablen an, und wenn es sich um ein Interface handelt, muss man angeben, wo man eine Implementierung finden kann, andernfalls wird ein Body mit Statements bereitgestellt, diese Knoten sind fast die gleichen wie in AST, außer dass jede Variable nur ein Verweis auf ein Symbol in der Symboltabelle ist (also kann man konstruktionsbedingt keine undefinierten Variablen haben). Die Symboltabelle für jeden Knoten, wie z. B. Funktion oder Modul, verweist auch auf seine Eltern (z. B. verweist eine Funktion auf ein Modul, ein Modul auf den globalen Bereich).

Der ASR kann direkt in einen AST umgewandelt werden, ohne dass weitere Informationen erfasst werden müssen. Und der AST direkt in Fortran-Quellcode.

Die ASR stellt immer einen semantisch gültigen Fortran-Code dar. Dies wird durch Überprüfungen in den ASR-C++-Konstruktoren (im Debug-Build) erzwungen. Wenn eine ASR eingesetzt wird, kann man davon ausgehen, dass sie gültig ist.

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 Standard Kapitel 2 „Fortran concepts“ left fest, dass Fortran Code eine Sammlung aus program units ist. (entweder alle in einer Datei oder in separaten Dateien), wobei jede program unit eine der folgenden ist:

  • Hauptprogramm (main program)

  • Modul oder Submodul

  • Funktion oder Subroutine

Beachte: Es kann auch eine block data-Programmeinheit sein, die verwendet wird, um Anfangswerte für Datenobjekte in benannten common blocks bereitzustellen, aber wir empfehlen die Verwendung von common blocks nicht (verwende stattdessen Module).

LFortran-Erweiterung

Wir erweitern die Fortran-Sprache, indem wir einen global scope, welcher nicht nur die Liste der program units (wie in F2008) ist, sondern auch include-Anweisungen, Deklarationen, use-Anweisungen und Ausdrücke enthalten kann.Wir definieren den global scope als eine Sammlung der folgenden Elemente:

  • Hauptprogramm (main program)

  • Modul oder Submodul

  • Funktion oder Subroutine

  • use Statement

  • Deklarationen (declaration)

  • Anweisung (statement)

  • Ausdruck (expression)

Zusätzlich wird, wenn eine Variable in einer Zuweisung (wie beispielsweise x = 5+3) nicht definiert ist, der Typ der Variablen aus der rechten Seite abgeleitet (z. B. wäre x in x = 5+3 vom Typ integer und y in y = 5._dp vom Typ real(dp)). Diese Regel gilt nur auf der obersten Ebene des global scope. Innerhalb von Hauptprogrammen, Modulen, Funktionen und Unterprogrammen müssen die Typen vollständig angegeben werden, genau wie in F2008.

Der global scope hat seine eigene Symboltabelle. Das Hauptprogramm und das Modul/Submodul sehen keine Symbole aus dieser Symboltabelle. Aber Funktionen, Unterprogramme, Anweisungen und Ausdrücke auf der obersten Ebene des global scope verwenden und operieren mit dieser Symboltabelle.

Für den global scope sind die folgenden Symbole in der Symboltabelle vordefiniert:

  • den üblichen Standardsatz von Fortran-Funktionen (wie size, sin, cos, …)

  • das Symbol dp für doppelte Genauigkeit, so dass man 5._dp für doppelte Genauigkeit verwenden kann.

Jedes Element im global scope wird wie folgt interpretiert: Das Hauptprogramm wird in eine ausführbare Datei mit demselben Namen kompiliert und ausgeführt; Module, Funktionen und Unterprogramme werden kompiliert und geladen; use-Anweisungen und Deklarationen fügen die Symbole mit dem richtigen Typ in die Symboltabelle des global scope ein, erzeugen aber keinen Code; Anweisungen werden in eine anonyme Unterroutine ohne Argumente übertragen, kompiliert, geladen und ausgeführt; Ausdrücke werden in eine anonyme Funktion, die den ursprünglichen Ausdruck zurückgibt, ohne Argumente übertragen kompiliert, geladen, ausgeführt und der Rückgabewert wird an den Benutzer zurückgegeben.

Der global scope wird immer Element für Element interpretiert, wie im vorherigen Absatz beschrieben. Er ist dazu gedacht, interaktive Nutzung, Experimente und das Schreiben einfacher Skripte zu ermöglichen. Code im global scope muss mit lfortran interpretiert werden. Für komplexeren (produktiven) Code wird empfohlen, ihn in Module und Programme umzuwandeln (indem man lose Anweisungen in Unterprogramme oder Funktionen umwandelt und Typdeklarationen hinzufügt) und ihn mit lfortran oder einem anderen Fortran-Compiler zu kompilieren.

Hier sind einige Beispiele für gültigen Code im global scope:

Beispiel 1

a = 5
print *, a

Beispiel 2

a = 5

subroutine p()
print *, a
end subroutine

call p()

Beispiel 3

module a
implicit none
integer :: i
end module

use a, only: i
i = 5

Beispiel 4

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

Design Entscheidungen

Die LFortran-Erweiterung von Fortran wurde so gewählt, dass die Zahl der Änderungen möglichst gering ist. Insbesondere wurden nur auf der obersten Ebene des global scope einige der Fortran-Regeln gelockert (z.B. die optionale Angabe von Typen), um eine einfache und schnelle interaktive Nutzung zu ermöglichen.

Die Anzahl der Änderungen wurde so gering wie möglich gehalten, um die Umwandlung von global scope-Code in standardkonformen Fortran-Code mit Hilfe von Programmen und Modulen so einfach wie möglich zu gestalten, so dass er von jedem Fortran-Compiler kompiliert werden kann.