Wikiprojekt:Informatyka/en/Kompilator

Z Wikipedii, wolnej encyklopedii
 Osobny artykuł: Kompilator.
Diagram działania wieloplatformowego i wielojęzykowego kompilatora.

Kompilatorprogram komputerowy (lub zestaw programów), który tłumaczy jeden język komputera (kod źródłowy) na inny język (zwany kodem wynikowym). W standardowych przypadkach języki te nazywane są: kod źródłowy oraz kod obiektowy. W większości przypadków kod wynikowy jest zapisany w formie zrozumiałej dla procesora, ale czasami zdarzają się formy zrozumiałe dla człowieka.

Najbardziej powszechnym powodem, aby tłumaczyć kod jest chęć uzyskania pliku wykonywalnego. Nazwa kompilator jest najczęściej używana w stosunku do programów, które tłumaczą kod źródłowy z języka wysokiego poziomu do języka niższego poziomu (np. asembler lub kod maszynowy). Program tłumaczący z języka niższego poziomu do języka wyższego poziomu nazywamy dekompilatorem. Program tłumaczący pomiędzy językami wysokiego poziomu najczęściej nazywany jest programem tłumaczącym, tłumaczem źródeł, lub konwerterem języka. language rewriter jest zazwyczaj programem, który zmienia formę programu bez zmiany języka.

Proces kompilacji[edytuj | edytuj kod]

Kompilatory realizują zazwyczaj wszystkie, lub większość z następujących operacji:

 Osobny artykuł: Kompilacja_%28informatyka%29.

Historia[edytuj | edytuj kod]

Oprogramowanie pierwszych komputerów było przez wiele lat pisane jedynie w assemblerze. Języki wysokiego poziomu nie były stosowane, dopóki korzyści z użycia tych samych programów na różnych rodzajach procesorów nie stały się istotnie większe od kosztu pisania kompilatora. Bardzo ograniczona pojemność pamięci wczesnych komputerów sprawiała również wiele problemów przy implementacji kompilatorów.

Pod koniec lat pięćdziesiątych zaproponowano po raz pierwszy maszynowe języki programowania. W następstwie czego powstały pierwsze, eksperymentalne kompilatory. Pierwszy kompilator napisała Grace Hopper, w 1952 roku, dla języka A-0. Uznaje się, że ekipa FORTRAN z IBM prowadzona przez Johna Bacusa wprowadziła do użycia pierwszy, kompletny kompilator w roku 1957. W roku 1960, COBOL był jednym z pierwszych języków, który można było kompilować na różnych architekturach. [1]

W wielu dziedzinach zastosowań, idea programowania wysokopoziomowego szybko się przyjęła. Rozszerzanie funkcjonalności zapewnianej przez nowsze języki programowania, oraz wzrastająca złożoność architektur systemów komputerowych, spowodowały, że kompilatory stawały się coraz bardziej skomplikowane.

Wczesne kompilatory były pisane w assemblerze. Pierwszym kompilatorem zdolnym do skompilowania własnego kodu źródłowego napisanego w języku wysokiego poziomu był kompilator języka Lisp, stworzony przez Harta i Levina z MIT w roku 1962 [2]. Od lat siedemdziesiątych stało się powszechną praktyką implementowanie kompilatora w języku przezeń kompilowanym, pomimo, że zarówno Pascal jak i C były chętnie wybierane przy implementacji. Problem konstrukcji samokompilującego się kompilatora określa się mianem Bootstrappingu — pierwszy taki kompilator musi być albo skompilowany kompilatorem napisanym w innym języku, albo (jak w przypadku kompilatora języka Lisp autorstwa Harta i Levina) kompilowany przez uruchomienie kompilatora w interpreterze.

Kompilatory w edukacji[edytuj | edytuj kod]

Konstrukcja kompilatorów i optymalizacja kompilatorów, są wykładane na uniwersytetach jako część programu studiów informatycznych. Takie kursy są zazwyczaj uzupełniane implementowaniem przez studentów kompilatora pewnego edukacyjnego języka programowania. Dobrze udokumentowanym przykładem jest kompilator języka PL/0, który był pierwotnie używany przez Niklausa Wirtha do nauczania metod konstrukcji kompilatorów w latach siedemdziesiątych. Pomimo swojej prostoty, kompilator PL/0 wprowadził do terminologii kilka pojęć, które odtąd stały się standardami w nauczaniu:

  1. Użycie Program Development by Stepwise Refinement
  2. Użycie Recursive descent parser
  3. Użycie notacji EBNF do specyfikowania składni języka
  4. Użycie P-Code podczas generowania przenośnego kodu wynikowego
  5. Użycie T-diagramów do formalnego opisu problemu Bootstrappingu


Rodzaje kompilatorów[edytuj | edytuj kod]

Kompilatory można sklasyfikować na różne sposoby, w zależności od wejścia i wyjścia, struktury wewnętrznej, bądź zachowania w czasie uruchomienia. Przykładowo,

  • Program tłumaczący z języka niskopoziomowego do wysokopoziomowego nazywamy dekompilatorem
  • Program tłumaczący między językami wysokiego poziomu nazywany jest w terminologii angielskiej: language translator, source to source translator, language converter, lub language rewriter (ostatni termin stosuje się w przypadku, gdy tłumaczenie odbywa się w obrębie tego samego języka)

Gdzie się wykonuje kod?[edytuj | edytuj kod]

One method used to classify compilers is by the platform on which the generated code they produce executes. Jedną z metod klasyfikacji kompilatorów jest określenie platformy, na której będzie wykonywany kod, wygenerowany podczas kompilacji.

A native or hosted compiler is one whose output is intended to directly run on the same type of computer and operating system as the compiler itself runs on. The output of a cross compiler is designed to run on a different platform. Cross compilers are often used when developing software for embedded systems that are not intended to support an environment intended for software development. Natywny kompilator to taki, którego wyjście jest przeznaczone do bezpośredniego uruchomienia na komputerze i systemie operacyjnym tego samego typu, na którym był uruchomiony kompilator. Wyjście kompilatora skrośnego jest zaprojektowane do uruchomienia na innej platformie. Kompilatory skrośne są często używane do tworzenia oprogramowania dla systemów wbudowanych które nie wspierają środowiska przeznaczonego do wytwarzania oprogramowanie.

The output of a compiler that produces code for a virtual machine (VM) may or may not be executed on the same platform as the compiler that produced it. For this reason such compilers are not usually classified as native or cross compilers. Wynik działania kompilatora, który tworzy kod dla maszyn wirtualnych, może być, ale nie musi, uruchamiany na platformie, na której sam kompilator był uruchomiony. Dlatego też nie są one zwykle klasyfikowane jako natywne, ani skrośne.

One-pass versus multi-pass compilers[edytuj | edytuj kod]

Classifying compilers by number of passes has its background in the hardware resource limitations of computers. Compiling involves performing lots of work and early computers did not have enough memory to contain one program that did all of this work. So compilers were split up into smaller programs which each made a pass over the source (or some representation of it) performing some of the required analysis and translations.

The ability to compile in a single pass is often seen as a benefit because it simplifies the job of writing a compiler and one pass compilers are generally faster than multi-pass compilers. Many languages were designed so that they could be compiled in a single pass (e.g., Pascal).

In some cases the design of a language feature may require a compiler to perform more than one pass over the source. For instance, consider a declaration appearing on line 20 of the source which affects the translation of a statement appearing on line 10. In this case, the first pass needs to gather information about declarations appearing after statements that they affect, with the actual translation happening during a subsequent pass.

The disadvantage of compiling in a single pass is that it is not possible to perform many of the sophisticated optimizations needed to generate high quality code. It can be difficult to count exactly how many passes an optimizing compiler makes. For instance, different phases of optimization may analyse one expression many times but only analyse another expression once.

Splitting a compiler up into small programs is a technique used by researchers interested in producing provably correct compilers. Proving the correctness of a set of small programs often requiring less effort than proving the correctness of a larger, single, equivalent program.

While the typical multi-pass compiler outputs machine code from its final pass, there are several other types:

  • A "source-to-source compiler" is a type of compiler that takes a high level language as its input and outputs a high level language. For example, an automatic parallelizing compiler will frequently take in a high level language program as an input and then transform the code and annotate it with parallel code annotations (e.g. OpenMP) or language constructs (e.g. Fortran's DOALL statements).
  • Stage compiler that compiles to assembly language of a theoretical machine, like some Prolog implementations
    • This Prolog machine is also known as the Warren Abstract Machine (or WAM). Bytecode compilers for Java, Python, and many more are also a subtype of this.
  • Just-in-time compiler, used by Smalltalk and Java systems, and also by Microsoft .Net's Common Intermediate Language (CIL)
    • Applications are delivered in bytecode, which is compiled to native machine code just prior to execution.

Języki kompilowane kontra interpretowane[edytuj | edytuj kod]

Many people divide higher-level programming languages into compiled languages and interpreted languages. However, there is rarely anything about a language that requires it to be compiled or interpreted. Compilers and interpreters are implementations of languages, not languages themselves. The categorization usually reflects the most popular or widespread implementations of a language -- for instance, BASIC is thought of as an interpreted language, and C a compiled one, despite the existence of BASIC compilers and C interpreters. Wielu ludzi dzieli języki wysokiego poziomu na języki kompilowane, oraz interpretowane. W rzeczywistości rzadko język sam w sobie wymaga, aby był kompilowany lub interpretowany. Kompilatory oraz interpretery są implementacjami języków, nie językami samymi w sobie. Kategoryzacja zwykle odzwierciedla najbardziej popularne, lub powszechne implementacje języka -- na przykład BASIC is przemyślany jako język interpretowany, a C jako kompilowany, jednak istnieją kompilatory BASICa oraz interpretery C.

There are exceptions; some language specifications spell out that implementations must include a compilation facility (eg, Common Lisp), while other languages have features that are very easy to implement in an interpreter, but make writing a compiler much harder; for example, SNOBOL4, and many scripting languages are capable of constructing arbitrary source code at runtime with regular string operations, and then executing that code by passing it to a special evaluation function. To implement these features in a compiled language, programs must usually be shipped with a runtime environment that includes the compiler itself. Są jednak wyjątki. Specyfikacja niektórych języków zaznacza, że implementacja musi dokonywać kompilacji (np. Common Lisp), podczas gdy inne mają cechy bardzo proste do implementacji w interpreterze, ale bardzo utrudniają napisanie kompilatora (SNOBOL4), ponad to wiele języków skryptowych jest zdolnych do konstruowania samodzielnego kodu w trakcie wykonania za pomocą operacji na tekstach, a następnie wykonanie go przekazując do specjalnej funkcji. Aby zaimplementować taką cechę w języku kompilowanym, programy musiały by być dostarczane razem z środowiskiem uruchomieniowym zawierającym w sobie kompilator.

Hardware compilation[edytuj | edytuj kod]

The output of some compilers may target hardware at a very low level, eg a Field Programmable Gate Array (FPGA). Such compilers are said to be hardware compilers because the programs they compile effectively control the final configuration of the hardware and how it operates; there are no instructions that are executed in sequence. Wyjście niektórych kompilatorów może być wycelowane w sam sprzęt komputerowy na bardzo niskim poziomie, np. bezpośrednio programowalną macierz bramek (ang. FPGA - Field Programmable Gate Array). Tego typu kompilatory nazywa się kompilatorami sprzętowymi, ponieważ programy które kompilują faktycznie sprawują kontrolę nad ostateczną konfiguracją sprzętową, oraz jej działaniem.

Konstrukcja kompilatora[edytuj | edytuj kod]

The approach taken to compiler design is affected by the complexity of the processing that needs to be done, the experience of the person(s) designing it, and the resources (eg, people and tools) available. Podejście do projektowania kompilatorów jest podyktowane złożonością procesu przetwarzania, jakie ma być wykonywane, doświadczeniem osoby (osób) projektujących go, oraz dostępnymi zasobami.

A compiler for a relatively simple language written by one person might be a single, monolithic, piece of software. When the source language is large and complex, and high quality output is required the design may be split into a number of relatively independent phases, or passes. Having separate phases means development can be parceled up into small parts and given to different people. It also becomes much easier to replace a single phase by an improved one, or to insert new phases later (eg, additional optimizations). Kompilatory relatywnie prostych języków pisane przez jedną osobę mogą być pojedynczymi, monolitycznymi programami. Kiedy źródłowy język jest duży i złożony, a zarazem wymagane jest wyjście wysokiej jakości, niezbędny jest podział projektu na kilka relatywnie niezależnych faz lub przejść. Posiadanie odseparowanych faz pozwala na podział pracy i rozłożenie jej na wielu ludzi. Jednocześnie uproszcza to podmianę pojedynczej fazy lepszą implementacją, lub dodanie nowej fazy później (np. dodatkowej optymalizacji).

The division of the compilation processes in phases (or passes) was championed by the Production Quality Compiler-Compiler Project (PQCC) at Carnegie Mellon University. This project introduced the terms front end, middle end (rarely heard today), and back end.

All but the smallest of compilers have more than two phases. However, these phases are usually regarded as being part of the front end or the back end. The point at where these two ends meet is always open to debate. The front end is generally considered to be where syntactic and semantic processing takes place, along with translation to a lower level of representation (than source code). Wszystkie poza najmniejszymi kompilatorami przeprowadzają kompilację w więcej niż dwóch fazach. Zwykle te fazy są uważane za bycie częścią front-endu, lub back-endu. Miejsce w którym oba endy się spotykają, zawsze jest otwarte na dyskusję. Front-end jest generalnie przemyślany jako miejsce, gdzie przetwarza się syntaktykę oraz semantykę kodu, wraz z tłumaczeniem go na reprezentację niższego poziomu.

The middle end is usually designed to perform optimizations on a form other than the source code or machine code. This source code/machine code independence is intended to enable generic optimizations to be shared between versions of the compiler supporting different languages and target processors. Middle-end jest zwykle miejscem gdzie następują optymalizacje na czymś pomiędzy kodem źródłowym i maszynowym. Kod tej jest zaprojektowany aby umożliwić ogólne optymalizacje tak, aby mogły być współdzielone przez różne wersje kompilatorów różnych języków programowania, przeznaczonych na różne procesory.

The back end takes the output from the middle. It may perform more analysis, transformations and optimizations that are for a particular computer. Then, it generates code for a particular processor and OS. Back-end zajmuje się wyjściem z middle-endu. Ma za zadanie analizę, transformację oraz optymalizację dla szczególnych komputerów. Następnie generuje kod dla konkretnych procesorów i systemów operacyjnych.

This front-end/middle/back-end approach makes it possible to combine front ends for different languages with back ends for different CPUs. A practical example of this approach is the GNU Compiler Collection and the Amsterdam Compiler Kit, which have multiple front-ends, shared analysis and multiple back-ends. Podejście front-end/middle-end/back-end umożliwia mieszanie front-endów różnych języków z back-endami dla różnych procesorów. Praktycznym przykładem tego podejście jest GNU Compiller Collection i Amsterdam Compiler Kit, które mają wiele front-endów, oraz wiele back-endów.

Front end[edytuj | edytuj kod]

The front end analyses the source code to build an internal representation of the program, called the intermediate representation or IR. It also manages the symbol table, a data structure mapping each symbol in the source code to associated information such as location, type and scope. This is done over several phases, which includes some of the following:

  1. Line reconstruction. Languages which strop their keywords or allow arbitrary spaces within identifiers require a phase before parsing, which converts the input character sequence to a canonical form ready for the parser. The top-down recursive-descent table-driven parsers used in the 1960s typically read the source a character at a time and did not require a separate tokenizing phase. Atlas Autocode, and Imp (and some implementations of Algol and Coral66) are examples of stropped languages whose compilers would have a Line Reconstruction phase.
  2. Lexical analysis breaks the source code text into small pieces called tokens. Each token is a single atomic unit of the language, for instance a keyword, identifier or symbol name. The token syntax is typically a regular language, so a finite state automaton constructed from a regular expression can be used to recognize it. This phase is also called lexing or scanning, and the software doing lexical analysis is called a lexical analyzer or scanner.
  3. Preprocessing. Some languages, e.g., C, require a preprocessing phase which supports macro substitution and conditional compilation. Typically the preprocessing phase occurs before syntactic or semantic analysis; e.g. in the case of C, the preprocessor manipulates lexical tokens rather than syntactic forms. However, some languages such as Scheme support macro substitutions based on syntactic forms.
  4. Syntax analysis involves parsing the token sequence to identify the syntactic structure of the program. This phase typically builds a parse tree, which replaces the linear sequence of tokens with a tree structure built according to the rules of a formal grammar which define the language's syntax. The parse tree is often analyzed, augmented, and transformed by later phases in the compiler.
  5. Semantic analysis is the phase in which the compiler adds semantic information to the parse tree and builds the symbol table. This phase performs semantic checks such as type checking (checking for type errors), or object binding (associating variable and function references with their definitions), or definite assignment (requiring all local variables to be initialized before use), rejecting incorrect programs or issuing warnings. Semantic analysis usually requires a complete parse tree, meaning that this phase logically follows the parsing phase, and logically precedes the code generation phase, though it is often possible to fold multiple phases into one pass over the code in a compiler implementation.

Back end[edytuj | edytuj kod]

The term back end is sometimes confused with code generator because of the overlapped functionality of generating assembly code. Some literature uses middle end to distinguish the generic analysis and optimization phases in the back end from the machine dependent code generators.

The main phases of the back end include the following:

  1. Analysis - This is the gathering of program information from the intermediate representation derived from the input. Typical analyses are data flow analysis to build use-define chains, dependence analysis, alias analysis, pointer analysis, escape analysis etc. Accurate analysis is the basis for any compiler optimization. The call graph and control flow graph are usually also built during the analysis phase.
  2. Optimization - the intermediate language representation is transformed into functionally equivalent but faster (or smaller) forms. Popular optimizations are inline expansion, dead code elimination, constant propagation, loop transformation, register allocation or even automatic parallelization.
  3. Code generation - the transformed intermediate language is translated into the output language, usually the native machine language of the system. This involves resource and storage decisions, such as deciding which variables to fit into registers and memory and the selection and scheduling of appropriate machine instructions along with their associated addressing modes (see also Sethi-Ullman algorithm).

Compiler analysis is the prerequisite for any compiler optimization, and they tightly work together. For example, dependence analysis is crucial for loop transformation.

In addition, the scope of compiler analysis and optimizations vary greatly, from as small as a basic block to the procedure/function level, or even over the whole program (interprocedural optimization). Obviously, a compiler can potentially do a better job using a broader view. But that broad view is not free: large scope analysis and optimizations are very costly in terms of compilation time and memory space; this is especially true for interprocedural analysis and optimizations.

The existence of interprocedural analysis and optimizations is common in modern commercial compilers from IBM, SGI, Intel, Microsoft, and Sun Microsystems. The open source GCC was criticized for a long time for lacking powerful interprocedural optimizations, but it is changing in this respect. Another good open source compiler with full analysis and optimization infrastructure is Open64, which is used by many organizations for research and commercial purposes.

Due to the extra time and space needed for compiler analysis and optimizations, some compilers skip them by default. Users have to use compilation options to explicitly tell the compiler which optimizations should be enabled.

Przykład kompilatora[edytuj | edytuj kod]

Następujący program implementuje bardzo prosty jednoprzebiegowy kompilator napisany w języku C. Ten kompilator kompiluje wyrażenia zdefiniowane w notacji infiksowej do ONP a także do assemblera. Kompilator realizuje strategię rekurencyjnego zagłębiania się w wyrażenie. Każde wywołanie funkcji odpowiada napotkaniu symbolu nieterminalnego należącego do gramatyki języka.

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define MODE_POSTFIX 	0
#define MODE_ASSEMBLY 	1

char    lookahead;
int     pos;
int	compile_mode;
char    expression[20+1];

void error()
{
        printf("Syntax error!\n");
}

void match( char t )
{
        if( lookahead == t )
        {
                pos++;
                lookahead = expression[pos];            
        }
        else
                error();
}

void digit()
{
        switch( lookahead )
        {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
			if( compile_mode == MODE_POSTFIX )
				printf("%c", lookahead);
			else
				printf("\tPUSH %c\n", lookahead);			
			
                        match( lookahead );
                        break;
                default:
                        error();
                        break;
        }
}

void term()
{
        digit();
        while(1)
        {
                switch( lookahead )
                {
                        case '*':
                                match('*');
                                digit();
                                                                
                                printf( "%s", compile_mode == MODE_POSTFIX ? "*" 
					: "\tPOP B\n\tPOP A\n\tMUL A, B\n\tPUSH A\n");
					
                                break;
                        case '/':
                                match('/');
                                digit();

                                printf( "%s", compile_mode == MODE_POSTFIX ? "/" 
					: "\tPOP B\n\tPOP A\n\tDIV A, B\n\tPUSH A\n");
                                break;
                        default:
                                return;
                }
        }
}

void expr()
{
        term();
        while(1)
        {
                switch( lookahead )
                {
                        case '+':
                                match('+');
                                term();
                                
                                printf( "%s", compile_mode == MODE_POSTFIX ? "+" 
					: "\tPOP B\n\tPOP A\n\tADD A, B\n\tPUSH A\n");
                                break;
                        case '-':
                                match('-');
                                term();

                                printf( "%s", compile_mode == MODE_POSTFIX ? "-" 
					: "\tPOP B\n\tPOP A\n\tSUB A, B\n\tPUSH A\n");
                                break;
                        default:
                                return;
                }
        }
}

int main ( int argc, char** argv )
{
        printf("Please enter an infix-notated expression with single digits:\n\n\t");
        scanf("%20s", expression);
        
        printf("\nCompiling to postfix-notated expression:\n\n\t");	
	compile_mode = MODE_POSTFIX;
        pos = 0;
        lookahead = *expression;
        expr();
                
        printf("\n\nCompiling to assembly-notated machine code:\n\n");        
        compile_mode = MODE_ASSEMBLY;
        pos = 0;
        lookahead = *expression;
        expr();

        return 0;
}

Przykład możliwego wyjścia, wygenerowanego podczas wykonania powyższego programu:

Please enter an infix-notated expression with single digits:

        3-4*2+2

Compiling to postfix-notated expression:

        342*-2+

Compiling to assembly-notated machine code:

        PUSH 3
        PUSH 4
        PUSH 2
        POP B
        POP A
        MUL A, B
        PUSH A
        POP B
        POP A
        SUB A, B
        PUSH A
        PUSH 2
        POP B
        POP A
        ADD A, B
        PUSH A


References[edytuj | edytuj kod]

  • Compiler textbook references A collection of references to mainstream Compiler Construction Textbooks
  • Compilers: Principles, Techniques and Tools by Alfred V. Aho, Ravi Sethi, and Jeffrey D. Ullman (ISBN 0-201-10088-6) is considered to be the standard authority on compiler basics (undergraduate level), and makes a good primer for the techniques mentioned above. (It is often called the Dragon Book because of the picture on its cover showing a Knight of Programming fighting the Dragon of Compiler Design.) link to publisher
  • Advanced Compiler Design and Implementation by Steven Muchnick (ISBN 1-55860-320-4). One of the widely-used text books for advanced compiler courses (graduate level).
  • Engineering a Compiler by Keith D. Cooper and Linda Torczon . Morgan Kaufmann 2004, ISBN 1-55860-699-8. This is a very practical compiler book.
  • Understanding and Writing Compilers: A Do It Yourself Guide (ISBN 0-333-21732-2) by Richard Bornat is an unusually helpful book, being one of the few that adequately explains the recursive generation of machine instructions from a parse tree. The authors experience from the early days of mainframes and minicomputers, provides useful insights that more recent books often fail to convey.
  • An Overview of the Production Quality Compiler-Compiler Project by Leverett, Cattel, Hobbs, Newcomer, Reiner, Schatz and Wulf. Computer 13(8):38-49 (August 1980)
  • Compiler Construction by Niklaus Wirth (ISBN 0-201-40353-6) Addison-Wesley 1996, 176 pages, also available at [3]. Step-by-step guide to using recursive descent parser. Describes a compiler for Oberon-0, a subset of the author's programming language, Oberon.
  • "Programming Language Pragmatics" by Michael Scott (ISBN 0-12-633951-1) Morgan Kaufmann 2005, 2nd edition, 912 pages. This book offers a broad and in-depth introduction to compilation techniques and programming languages, illustrated with many examples. More information on the book can be found at the author's site.
  • "A History of Language Processor Technology in IBM", by F.E. Allen, IBM Journal of Research and Development, v.25, no.5, September 1981.

See also[edytuj | edytuj kod]

External links[edytuj | edytuj kod]

Szablon:Wiktionary