Professional Documents
Culture Documents
Contents
[hide]
• 1 Key concepts
○ 1.1 Assembler
• 2 Language design
○ 2.2 Macros
• 4 Related terminology
• 6 Further details
• 8 See also
• 9 References
• 10 Further reading
• 11 External links
[edit]Key concepts
[edit]Assembler
[edit]Assembly language
A program written in assembly language consists of a series
of instructions--mnemonics that correspond to a stream of executable
instructions, when translated by an assembler, that can be loaded into
memory and executed.
Move (really a copy) the hexadecimal value '61' into the processor
register named "AL". (The h-suffix means hexadecimal; 61h = 97
in decimal)
Opcode mnemonics
Data sections
Assembly directives
[edit]Opcode mnemonics and pseudo-opcodes
[edit]Data sections
There are instructions used to define data elements to hold data and
variables. They define the type of data, the length and the alignment of
data. These instructions can also define whether the data is available
to outside programs (programs assembled separately) or only to the
program in which the data section is defined. Some assemblers
classify these as pseudo-ops.
[edit]Assembly directives
Wise use of these facilities can greatly simplify the problems of coding
and maintaining low-level code. Raw assembly source code as
generated by compilers or disassemblers—code without any
comments, meaningful symbols, or data definitions—is quite difficult to
read when changes must be made.
[edit]Macros
Since macros can have 'short' names but expand to several or indeed
many lines of code, they can be used to make assembly language
programs appear to be far shorter, requiring fewer lines of source code,
as with higher level languages. They can also be used to add higher
levels of structure to assembly programs, optionally introduce
embedded debugging code via parameters and other similar features.
Many assemblers have built-in (or predefined) macros for system calls
and other special code sequences, such as the generation and storage
of data realized through advanced bitwise and booleanoperations used
in gaming, software security, data management, and cryptography.
This was because, as was realized in the 1970s, the concept of "macro
processing" is independent of the concept of "assembly", the former
being in modern terms more word processing, text processing, than
generating object code. The concept of macro processing appeared,
and appears, in the C programming language, which supports
"preprocessor instructions" to set variables, and make conditional tests
on their values. Note that unlike certain previous macro processors
inside assemblers, the C preprocessor was not Turing-
complete because it lacked the ability to either loop or "go to", the latter
allowing programs to loop.
Despite the power of macro processing, it fell into disuse in many high
level languages (a major exception being C/C++) while remaining a
perennial for assemblers. This was because many programmers were
rather confused by macro parameter substitution and did not
disambiguate macro processing from assembly and
execution[dubious – discuss].
intention was that the caller would provide the name of a variable, and
the "global" variable or constant b would be used to multiply "a". If foo
is called with the parameter a-c, the macro expansion of load a-
c*b occurs. To avoid any possible ambiguity, users of macro
processors can parenthesize formal parameters inside macro
definitions, or callers can parenthesize the input parameters.[4]
PL/I and C/C++ feature macros, but this facility can only manipulate
text. On the other hand, homoiconic languages, such as Lisp, Prolog,
and Forth, retain the power of assembly language macros because
they are able to manipulate their own code as data.
The Assembler for the VIC-20 was written by Don French and
published by French Silk. At 1639 bytes in length, its author believes it
is the smallest symbolic assembler ever written. The assembler
supported the usual symbolic addressing and the definition
of character strings or hex strings. It also allowed address expressions
which could be combined
with addition, subtraction, multiplication,division, logical AND, logical
OR, and exponentiation operators.[9]
[edit]Current usage
There have always been debates over the usefulness and performance
of assembly language relative to high-level languages. Assembly
language has specific niche uses where it is important; see below. But
in general, modern optimizing compilers are claimed[citation needed] to
render high-level languages into code that can run as fast as hand-
written assembly, despite the counter-examples that can be found .[10]
[11][12]
The complexity of modern processors and memory sub-system
makes effective optimization increasingly difficult for compilers, as well
as assembly programmers .[13][14]Moreover, and to the dismay of
efficiency lovers, increasing processor performance has meant that
most CPUs sit idle most of the time, with delays caused by predictable
bottlenecks such as I/Ooperations and paging. This has made raw
code execution speed a non-issue for many programmers.
[edit]Typical applications
Hard-coded assembly language is typically used in a system's boot
ROM (BIOS on IBM-compatible PC systems). This low-level code is
used, among other things, to initialize and test the system hardware
prior to booting the OS, and is stored in ROM. Once a certain level of
hardware initialization has taken place, execution transfers to other
code, typically written in higher level languages; but the code running
immediately after power is applied is usually written in assembly
language. The same is true of most boot loaders.
[edit]Related terminology
Assembly language or assembler language is commonly
called assembly, assembler, ASM, or symbolic machine code.
A generation of IBM mainframe programmers called
it BAL for Basic Assembly Language.
The use of the word assembly dates from the early years of
computers (cf. short code, speedcode).
List of assemblers
[edit]Further details
Instruction (AT&T
Address Label Object code[24]
syntax)
.begin
.org 2048
2048 ld length,%
.org a_start
3000 a:
[edit]See also
Compiler
Disassembler
Instruction set
3. ^ http://www.z80.de/z80/z80code.htm
Retrieved 2008-07-25.
meanassembly language]"
termassembly program]
43664-7.
[edit]Further reading
ASM Community Book "An online book full of helpful ASM
info, tutorials and code examples" by the ASM Community
Look up assembly
language inWiktionary, the
free dictionary.
Subject:Assembly languages
NASM Manual
Z80/Z180/8085 Assembler
[hide]
v•d•e
Types of programming lan
Array · Aspect-oriented · Assembly · Class-based · Compiled · Concatenative · Concurrent · Data-structured · Dataflow · Declarative · Do
Logic · Low-level · Machine · Macro · Metaprogramming · Multi-paradigm · Non-English-based · Object-based · Object-oriented · Off-s
level · Visual
• New features
• Log in / create account
• Article
• Discussion
• Read
• Edit
• View history
Top of Form
Bottom of Form
• Main page
• Contents
• Featured content
• Current events
• Random article
• Donate
Interaction
• About Wikipedia
• Community portal
• Recent changes
• Contact Wikipedia
• Help
Toolbox
Print/export
Languages
• العربية
• বাংলা
• Bosanski
• Български
• Català
• Česky
• Dansk
• Deutsch
• Eesti
• Ελληνικά
• Español
• Esperanto
• فارسی
• Français
• 한국어
• िहनदी
• Hrvatski
• Bahasa Indonesia
• Íslenska
• Italiano
• עברית
• ქართული
• Latviešu
• Lietuvių
• Magyar
• Bahasa Melayu
• Nederlands
• 日本語
• Norsk (bokmål)
• Polski
• Português
• Română
• Русский
• Shqip
• සිංහල
• Simple English
• Slovenščina
• Српски / Srpski
• Srpskohrvatski / Српскохрватски
• Suomi
• Svenska
• ไทย
• Türkçe
• Українська
• Tiếng Việt
• 中文
License; additional terms may apply. See Terms of Use for details.
Wikipedia® is a registered trademark of the Wikimedia Foundation, Inc.,
a non-profit organization.
• Contact us
• Privacy policy
• About Wikipedia
• Disclaimers
•
Flat Assembler 1.56
Added: August 05, 2008 | Visits: 505
The flat assembler is a fast and efficient self-assembling 80x86 assembler for DOS, Windows and Linux
operating systems. Currently it supports all 8086-80486/Pentium instructions with MMX, SSE, SSE2,
SSE3 and 3DNow! extensions, can produce output in binary, MZ, PE, COFF or ELF format. It includes...
License: Freeware Cost: $0.00 USD Size: 143 KB Download (104): Flat Assembler Download
B::Assembler 5.8.8
Added: January 19, 2010 | Visits: 60
B::Assembler is a Perl module created to assemble Perl bytecode. SYNOPSIS use B::Assembler
qw(newasm endasm assemble); newasm(&printsub); # sets up for assembly assemble($buf); # assembles
one line endasm(); # closes down use B::Assembler qw(assemble_fh); assemble_fh($fh, &printsub); #...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 12 MB Download (4): B::Assembler Download
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 24 KB Download (7): MiniDV Assembler Download
GoAsm 0.43
Added: August 07, 2008 | Visits: 555
Win32+assembler is becoming more and more popular, you can use a low level language (assembler)
together with a very high level language (the Windows API) - a perfect combination! GoAsm is a fast, free,
assembler for producing Win32 files. It has a particularly clean syntax with a number of...
Platforms: Windows XP
License: Freeware Cost: $0.00 USD Size: 200 KB Download (117): GoAsm Download
DV Video
Assembler 0.93
Added: January 19, 2010 | Visits: 98
This application is particularly useful for owners of digital DV video cameras and other people who use the
Sony DV video format for high quality video production. DV Assembler allows you to append multiple Sony
DV files with nice looking transition effects for both audio and video. Multiple...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 23 KB Download (7): DV Video Assembler Download
Gif Assembler beta .96
Added: January 19, 2010 | Visits: 118
Gif Assembler is a Web-based frontend for Gifsicle which allows users to create GIF animations from
existing GIF images. With Gif Assembler you can upload up to 99 GIF images as the frames for the
animation. Whats New in This Release: · Changes some syntax for better path detection, changes...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 4 KB Download (20): Gif Assembler beta Download
Pyastra 0.0.4.1-preview
Added: January 19, 2010 | Visits: 114
Pyastra is a python to assembler translator. The project takes source file written in python and, if the code
contains no errors, generates an assembler file. Then you may comile it to hex-file using your favourite
PIC assembler (gpasm, mpasm, or any other compatible with them). Goals: · to...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 194 KB Download (8): Pyastra Download
Advanced
Assembler 0.9.0
Added: January 19, 2010 | Visits: 90
Aasm is an advanced assembler designed to support several target architectures. It has been designed to
be easily extended and, should be considered as a good alternative to monolithic assembler development
for each new target CPUs and binary file formats. Aasm should make assembly programming...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 30 KB Download (8): Advanced Assembler Download
binfmtc 0.10
Added: January 19, 2010 | Visits: 85
binfmtc implements handlers for C and other languages, which are usually compiled. The program utilizes
the Linux binfmt-misc feature to dynamically compile and execute C programs as if they were scripts.
binfmtc project supports C, C++, Java, Pascal, Fortran, and assembler. Whats New in...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 90 KB Download (5): binfmtc Download
emu8086 2.02
Released: August 08, 2002 | Added: December 22, 2006 | Visits: 4.501
Everything for learning assembly language in one pack! emu8086 combines an advanced source editor,
assembler, disassembler, software emulator (Virtual PC) with debugger, and step by step tutorials.
Platforms: Windows 95, Windows 98, Windows Me, Windows 2000, Windows XP
License: Shareware Cost: $12.50 USD Size: 2 MB Download (624): emu8086 Download
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 80 KB Download (49): GNU 8085 Simulator Download
Yasm 0.6.1
Added: January 19, 2010 | Visits: 67
Yasm is a complete rewrite of the NASM assembler under the "new" BSD License (some portions are
under other licenses, see COPYING for details). Yasm project is designed from the ground up to allow for
multiple assembler syntaxes to be supported (eg, TASM, GAS, NASM etc.) in addition to multiple...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 1 MB Download (8): Yasm Download
asfpga 1.00e
Added: January 19, 2010 | Visits: 62
asfpga is an assembler written for use in FPGA design. It can be easily modified for your instruction set.
The ultimate goal of this software is to allow a FPGA designer to easily write assembly code for a custom
instruction set. The current version allows to create a listing file, a memory...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 7 KB Download (3): asfpga Download
SX-IDE 0.08
Added: January 19, 2010 | Visits: 79
This is an application to compile assembler files and transfer them from Linux to the XGS (SX28/52
microcontrollers) with the SX-Key. It requires QT 4, WINE and the SASM assembler. The 0.02 version
contains just the transfer part. The newer versions also contain the rest of the IDE to compile...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 86 KB Download (6): SX-IDE Download
SVK-Protector
1.1
Released: July 01, 2002 | Added: December 22, 2006 | Visits: 2.425
SVK-Protector is a powerful tool offering both software developers and distributors a protection of their
software products against unauthorized copying, use and distribution. SVK-Protector is programmed in
Assembler, which is a synonym for high speed and special programming techniques that...
Platforms: Windows 95, Windows 98, Windows Me, Windows NT 4.x, Windows 2000, Windows XP
License: Commercial Cost: $89.00 USD Size: 1 MB Download (127): SVK-Protector Download
Platforms: Windows 95, Windows 98, Windows Me, Windows NT 4.x, Windows XP
License: Shareware Cost: $12.50 USD Size: 787 KB Download (89): Square Assembler Download
Platforms: Windows 98, Windows Me, Windows NT 4.x, Windows 2000, Windows XP
License: Shareware Cost: $0.00 USD Size: 4 KB Download (99): My Personal Translator Download
nonpareil 0.16
Added: January 25, 2010 | Visits: 62
nonpareil is a micro-assembler and simulator package for the calculators written originally for Linux by Eric
Smith.nonpareil for Mac OS X is pre-release software (beta version).nonpareil is made available under the
terms of the Free Software Foundation's General Public License, Version 2.
Platforms: Macintosh
License: Freeware Cost: $0.00 USD Size: 46 KB Download (4): nonpareil Download
nwbintools
0.1.1
Added: January 19, 2010 | Visits: 53
nwbintools is a machine code toolchain containing an assembler and various related development tools.
The project will thus be similar to GNU binutils, but no attempts are made to duplicate its functionality,
interfaces, or organization. nwbintools has been under development (on and off) since...
Platforms: Linux
License: Freeware Cost: $0.00 USD Size: 94 KB Download (2): nwbintools Download
CNW Home
Assembler Pseudocode.
2 pass assembler for SIC/XE
Pass 1:
BEGIN
initialize Scnt, Locctr, ENDval, and Errorflag to 0
WHILE Sourceline[Scnt] is a comment
BEGIN
increment Scnt
END {while}
Breakup Sourceline[Scnt]
IF Opcode = 'START' THEN
BEGIN
convert Operand from hex and save in Locctr and ENDval
IF Label not NULL THEN
Insert (Label, Locctr) into Symtab
ENDIF
increment Scnt
Breakup Sourceline[Scnt]
END
ENDIF
WHILE Opcode <> 'END'
BEGIN
IF Sourceline[Scnt] is not a comment THEN
BEGIN
IF Label not NULL THEN
Xsearch Symtab for Label
IF not found
Insert (Label, Locctr) into Symtab
ELSE
set errors flag in Errors[Scnt]
ENDIF
ENDIF
Xsearch Opcodetab for Opcode
IF found THEN
DO CASE
1. Opcode is 'RESW' or 'RESB'
BEGIN
increment Locctr by Storageincr
IF error THEN
set errors flag in Errors[Scnt]
ENDIF
END {case 1 (RESW or RESB)}
2. Opcode is 'WORD' or 'BYTE' THEN
BEGIN
increment Locctr by Storageincr
IF error THEN
set errors flag in Errors[Scnt]
ENDIF
END {case 2 (WORD or BYTE)}
3. OTHERWISE
BEGIN
increment Locctr by Opcodeincr
IF error THEN
set errors flag in Errors[Scnt]
ENDIF {case 3 (default)}
END
ENDCASE
ELSE
/* directives such as BASE handled here or */
set errors flag in Errors[Scnt]
ENDIF
END {IF block}
ENDIF
increment Scnt
Breakup Sourceline[Scnt]
END {while}
IF Label not NULL THEN
Xsearch Symtab for Label
IF not found
Insert (Label, Locctr) into Symtab
ELSE
set errors flag in Errors[Scnt]
ENDIF
ENDIF
IF Operand not NULL
Xsearch Symtab for Operand
IF found
install in ENDval
ENDIF
ENDIF
END {of Pass 1}
Pass 2:
BEGIN
initialize Scnt, Locctr, Skip, and Errorflag to 0
write assembler report headings
WHILE Sourceline[Scnt] is a comment
BEGIN
append to assembler report
increment Scnt
END {while}
Breakup Sourceline[Scnt]
IF Opcode = 'START' THEN
BEGIN
convert Operand from hex and save in Locctr
append to assembler report
increment Scnt
Breakup Sourceline[Scnt]
END
ENDIF
format and place the load point on object code array
format and place ENDval on object code array, index ENDloc
WHILE Opcode <> 'END'
BEGIN
IF Sourceline[Scnt] is not a comment THEN
BEGIN
Xsearch Opcodetab for Opcode
IF found THEN
DO CASE
1. Opcode is 'RESW' or 'RESB'
BEGIN
increment Locctr by Storageincr
place '!' on object code array
replace the value at index ENDloc with loader address
format and place Locctr on object code array
format and place ENDval on object code array, index ENDloc
set Skip to 1
END
2. Opcode is 'WORD' or 'BYTE'
BEGIN
increment Locctr by Storageincr
Dostorage to get Objline
IF error THEN
set errors flag in Errors[Scnt]
ENDIF
END
3. OTHERWISE
BEGIN
increment Locctr by Opcodeincr
Doinstruct to get Objline
IF error THEN
set errors flag in Errors[Scnt]
ENDIF
END
ENDCASE
ELSE
/* directives such as BASE handled here or */
set errors flag in Errors[Scnt]
ENDIF
END
ENDIF
append to assembler report
IF Errors[Scnt] <> 0 THEN
BEGIN
set Errorflag to 1
append error report to assembler report
END
ENDIF
IF Errorflag = 0 and Skip = 0 THEN
BEGIN
place Objline on object code array
END
ENDIF
IF Skip = 1 THEN
set Skip to 0
ENDIF
increment Scnt
Breakup Sourceline[Scnt]
END {while}
place '!' on object code array
IF Errorflag = 0 THEN
transfer object code array to file
ENDIF
END {of Pass 2}
How the assembler work
Meta commands
S2 Assembly language
S2 instruction format
Pass1
Pass2
Extended instructions
Syntax of the assembly language
Meta commands (.s .a .c .w .e)
There are three sections which can occur in any sequence: define symbols, code
section, data section. Each section starts with a meta command: .s for symbol section,
.c for code section, .w for data section. Each section ends with any meta command.
Other meta commands are: .a sets the current address, .e ends the assembly file. .e
must be the last line. The ';;' starts the comment to the end of the current line.
Comments are not interpreted by the assembler.
In symbol definition section, symbols are defined with their associated values. The
data section defined constant values. Lables can be defined in any section and they
can be referred to by other assembly instructions.
;; comment
.s ;; define symbol
symbol n ;; n is value
. . .
.a n ;; set address to n
.c ;; code segment
:label op opr1 opr2 ...
. . .
.w ;; data segment
v v ... ;; v is number or sym
.e ;; end of program
The convention for operand ordering is: op dest source. The operands are written in
such a way to simplify the assembler using prefix to identify the addressing mode.
ld r1, 10(r2) is written as ld r1 @10 r2 ;; displacement
ld r1, (r2+r3) " ld r1 +r2 r3 ;; index
ld r1, #200 " ld r1 #200 ;; immediate
add r1, r2, r3 " add r1 r2 r3 ;; reg-reg
add r1, r2, #20 add r1 r2 #20 ;; reg-immediate
The assembler does not check for all possible illegal combination of opcode,
addressing mode and operands. The forms of assembly language for each S2
instruction are:
ld rd source
st source rd
aop rd rs1 rs2
aop rd rs #n
sop rd rs
jmp cond dest
jal rd dest
jr rs
trap num rs
where
rd is r1..r31
rs is r0..r31
source -> absolute | disp | index | immediate (as shown above)
aop -> add | sub | mul | div | and | or | xor (ALU op)
sop -> shl | shr (shift op)
cond -> always | eq | neq | le | lt | gt | ge (conditional)
dest -> label | number
The assembler
The assembler works in two passes:
pass1
input scanning, collect symbols, generate token list
pass2
generate object code from the token list
input scanning
symbol table
The predefined symbols are: opcode, r0..r31, conditional. opcode are ld st jmp jal jr
add sub mul div and or xor shl shr trap. conditional are: always eq neq lt le ge gt.
pass 1
collect symbols and resolve reference
build symbol table
store token list
token list is an array of token. Each token stores type, mode, reference and line
number (refer to source code line number). line number is used in reporting error.
Type is: sym num op dot. Mode is addressing mode: absolute, displacement, index,
immediate, reg-reg, reg-imm, special.
For example ld r1 @lv1 base will generate the list of four tokens:
( notation : {type,mode,ref} )
{ {op,disp,ld}, {sym,reg,r1}, {sym,disp,lv1}, {sym,reg,base} }
pass 2
generate code from token list
output format is suitable for a loader of the simulator
a num set address
{l,d,x} num+ instruction
w num defined word
e end of file
4 December 2001
Extended instructions
To enable creation of new instructions, three extended instructions aer provided: xl,
xd, xx, associated with three instruction formats: L, D, X. The assembly language can
not have the notation of addressing as usual because the meaning of instruction will be
defined by users. Therefore the operands of the instruction have to be written out
without any decoration:
XL op r1 disp:22
XD op r1 r2 disp:17
XX op r1 r2 r3 xop:12
The simulator must be extended accordingly to interpret this new instruction. See
more example on assembly form of extended instruction in the file "as2\testx.txt":
;; test extended instruction
.s
inc 14
ldd 15
addx 16
addx2 17
.a 10
.c
xd inc r1 r2 1 ;; new instruction D-format
xl ldd r7 data ;; L-format
xx addx r3 r4 r5 addx2 ;; X-format
.w 48230 ;; raw 32-bit
.c ;; back to code
add r1 r3 #4
add r1 r2 r3
:data ;; data segment
.w 11 22 33
.e
Compiler
From Wikipedia, the free encyclopedia
This article is about the computing term. For the anime, see Compiler (anime).
This article needs attention from an expert on the subject. See the talk page for
details. WikiProject Computer science or the Computer science Portal may be able to
help recruit an expert. (December 2008)
A compiler is a computer program (or set of programs) that transforms source code written in a programming
language (the source language) into another computer language (the target language, often having a binary
form known as object code). The most common reason for wanting to transform source code is to create
an executable program.
The name "compiler" is primarily used for programs that translate source code from a high-level programming
language to a lower level language (e.g., assembly language or machine code). If the compiled program can
only run on a computer whose CPU or operating system is different from the one on which the compiler runs
the compiler is known as a cross-compiler. A program that translates from a low level language to a higher
level one is a decompiler. A program that translates between high-level languages is usually called alanguage
translator, source to source translator, or language converter. A language rewriter is usually a program that
translates the form of expressions without a change of language.
A compiler is likely to perform many or all of the following operations: lexical analysis, preprocessing, parsing,
semantic analysis(Syntax-directed translation), code generation, and code optimization.
Program faults caused by incorrect compiler behavior can be very difficult to track down and work around and
compiler implementors invest a lot of time ensuring the correctness of their software.
The term compiler-compiler is sometimes used to refer to a parser generator, a tool often used to help create
the lexer and parser.
Contents
[hide]
• 1 History
• 2 Compilation
• 3 Compiler output
languages
• 4 Compiler design
compilers
• 5 Compiler correctness
• 6 Related techniques
organizations
• 8 See also
• 9 Notes
• 10 References
• 11 External links
Structure of compiler
he diagram below gives a simplified view of what compiler does
Compilers bridge source programs in high-level languages with the underlying hardwares. A compiler
requires 1) to recognize legitimacy of programs, 2) to generate correct and efficient code, 3) run-time
organization, 4) to format output according to assembler or linker conventions. A compiler consists of
three main parts: frontend, middle-end, and backend.
Frontend checks whether the program is correctly written in terms of the programming language syntax
and semantics. Here legal and illegal programs are recognized. Errors are reported, if any, in a useful
way. Type checking is also performed by collecting type information. Frontend generates IR (intermediate
representation) for the middle-end. Optimization of this part is almost complete so much are already
automated. There are efficient algorithms typically in O(n) or O(n log n).
Middle-end is where the optimizations for performance take place. Typical transformations for
optimization are removal of useless or unreachable code, discovering and propagating constant values,
relocation of computation to a less frequently executed place (e.g., out of a loop), or specializing a
computation based on the context. Middle-end generates IR for the following backend. Most optimization
efforts are focused on this part.
Backend is responsible for translation of IR into the target assembly code. The target instruction(s) are
chosen for each IR instruction. Variables are also selected for the registers. Backend utilizes the
hardware by figuring out how to keep parallel FUs busy, filling delay slots, and so on. Although most
algorithms for optimization are in NP, heuristic techniques are well-developed.
Compiler design
In the early days, the approach taken to compiler design used to be directly affected by the complexity of
the processing, the experience of the person(s) designing it, and the resources available.
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. 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).
The division of the compilation processes into phases was championed by the Production Quality
Compiler-Compiler Project (PQCC) at Carnegie Mellon University. This project introduced the termsfront
end, middle end, 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 which these two ends meet is 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).
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.
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.
This front-end/middle/back-end approach makes it possible to combine front ends for
different languages with back ends for different CPUs. Practical examples of this approach are the GNU
Compiler Collection, LLVM, and the Amsterdam Compiler Kit, which have multiple front-ends, shared
analysis and multiple back-ends.
[edit]One-pass versus multi-pass compilers
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 has classically been seen as a benefit because it simplifies the job
of writing a compiler and one pass compilers generally compile faster than multi-pass compilers. Thus,
partly driven by the resource limitations of early systems, many early languages were specifically
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 requires 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 DOALLstatements).
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.
[edit]Front end
The front end analyzes 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 one 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.
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.
[edit]Back end
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.
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.
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 alsoSethi-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.
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.
Lexical analysis
From Wikipedia, the free encyclopedia
In computer science, lexical analysis is the process of converting a sequence of characters into a sequence of
tokens. A program or function which performs lexical analysis is called a lexical analyzer, lexer or scanner. A
lexer often exists as a single function which is called by a parser or another function.
Contents
[hide]
• 1 Lexical grammar
• 2 Token
• 3 Scanner
• 4 Tokenizer
• 5 Lexer generator
• 6 Lexical analyzer
generators
• 7 See also
• 8 References
[edit]Lexical grammar
The specification of a programming language will often include a set of rules which defines the lexer. These
rules are usually called regular expressions and they define the set of possible character sequences that are
used to form tokens or lexemes, whitespace, (i.e. characters that are ignored), are also defined in the regular
expressions.
[edit]Token
A token is a string of characters, categorized according to the rules as a symbol (e.g. IDENTIFIER, NUMBER,
COMMA, etc.). The process of forming tokens from an input stream of characters is called tokenization and
the lexer categorizes them according to a symbol type. A token can look like anything that is useful for
processing an input text stream or text file.
A lexical analyzer generally does nothing with combinations of tokens, a task left for a parser. For example, a
typical lexical analyzer recognizes parenthesis as tokens, but does nothing to ensure that each '(' is matched
with a ')'.
sum=3+2;
sum Identifier
Assignment
=
operator
3 Number
+ Addition operator
2 Number
; End of statement
Tokens are frequently defined by regular expressions, which are understood by a lexical analyzer
generator such as lex. The lexical analyzer (either generated automatically by a tool like lex, or hand-
crafted) reads in a stream of characters, identifies the lexemes in the stream, and categorizes them into
tokens. This is called "tokenizing." If the lexer finds an invalid token, it will report an error.
Following tokenizing is parsing. From there, the interpreted data may be loaded into data structures for
general use, interpretation, or compiling.
[edit]Scanner
The first stage, the scanner, is usually based on a finite state machine. It has encoded within it
information on the possible sequences of characters that can be contained within any of the tokens it
handles (individual instances of these character sequences are known as lexemes). For instance,
an integer token may contain any sequence of numerical digit characters. In many cases, the first non-
whitespace character can be used to deduce the kind of token that follows and subsequent input
characters are then processed one at a time until reaching a character that is not in the set of characters
acceptable for that token (this is known as the maximal munch rule, or longest match rule). In some
languages[which?] the lexeme creation rules are more complicated and may involvebacktracking over
previously read characters.
[edit]Tokenizer
Tokenization is the process of demarcating and possibly classifying sections of a string of input
characters. The resulting tokens are then passed on to some other form of processing. The process can
be considered a sub-task of parsing input.
The string isn't implicitly segmented on spaces, as an English speaker would do. The raw input, the
43 characters, must be explicitly split into the 9 tokens with a given space delimiter (i.e. matching
the string " " or regular expression /\s{1}/.
The tokens could be represented in XML,
<sentence>
<word>The</word>
<word>quick</word>
<word>brown</word>
<word>fox</word>
<word>jumps</word>
<word>over</word>
<word>the</word>
<word>lazy</word>
<word>dog</word>
</sentence>
Or an s-expression,
(sentence . (The quick brown fox jumps over the lazy dog))
A lexeme, however, is only a string of characters known to be of a certain kind (e.g., a string literal,
a sequence of letters). In order to construct a token, the lexical analyzer needs a second stage,
theevaluator, which goes over the characters of the lexeme to produce a value. The lexeme's type
combined with its value is what properly constitutes a token, which can be given to a parser. (Some
tokens such as parentheses do not really have values, and so the evaluator function for these can
return nothing. The evaluators for integers, identifiers, and strings can be considerably more
complex. Sometimes evaluators can suppress a lexeme entirely, concealing it from the parser,
which is useful for whitespace and comments.)
might be converted (with whitespace suppressed) into the lexical token stream:
NAME "net_worth_future"
EQUALS
OPEN_PARENTHESIS
NAME "assets"
MINUS
NAME "liabilities"
CLOSE_PARENTHESIS
SEMICOLON
Though it is possible and sometimes necessary[specify] to write a lexer by hand, lexers are often
generated by automated tools. These tools generally accept regular expressions that describe
the tokens allowed in the input stream. Each regular expression is associated with a
production in the lexical grammar of the programming language that evaluates the lexemes
matching the regular expression. These tools may generate source code that can be compiled
and executed or construct a state table for a finite state machine (which is plugged into
template code for compilation and execution).
Regular expressions compactly represent patterns that the characters in lexemes might
follow. For example, for an English-based language, a NAME token might be any English
alphabetical character or an underscore, followed by any number of instances of any ASCII
alphanumeric character or an underscore. This could be represented compactly by the
string [a-zA-Z_][a-zA-Z_0-9]*. This means "any character a-z, A-Z or _, followed by 0
Regular expressions and the finite state machines they generate are not powerful enough to
handle recursive patterns, such as "n opening parentheses, followed by a statement, followed
by n closing parentheses." They are not capable of keeping count, and verifying that n is the
same on both sides — unless you have a finite set of permissible values for n. It takes a full-
fledged parser to recognize such patterns in their full generality. A parser can push
parentheses on a stack and then try to pop them off and see if the stack is empty at the end.
(see example in the SICP book)
The Lex programming tool and its compiler is designed to generate code for fast lexical
analysers based on a formal description of the lexical syntax. It is not generally considered
sufficient for applications with a complicated set of lexical rules and severe performance
requirements; for instance, the GNU Compiler Collection uses hand-written lexers.
[edit]Lexer generator
Lexical analysis can often be performed in a single pass if reading is done a character at a
time. Single-pass lexers can be generated by tools such as the classic flex.
The lex/flex family of generators uses a table-driven approach which is much less efficient
than the directly coded approach[dubious – discuss]. With the latter approach the generator produces
an engine that directly jumps to follow-up states via goto statements. Tools
like re2c and Quex have proven (e.g. RE2C - A More Versatile Scanner Generator (1994)) to
produce engines that are between two to three times faster than flex produced engines.[citation
needed]
It is in general difficult to hand-write analyzers that perform better than engines
generated by these latter tools.
The simple utility of using a scanner generator should not be discounted, especially in the
developmental phase, when a language specification might change daily. The ability to
express lexical constructs as regular expressions facilitates the description of a lexical
analyzer. Some tools offer the specification of pre- and post-conditions which are hard to
program by hand. In that case, using a scanner generator may save a lot of development
time.
Ragel - A state machine and lexical scanner generator with output support for C, C++,
Objective-C, D, Java and Ruby source code.
Quex - (or 'Queχ') A Fast Universal Lexical Analyzer Generator for C++.
Preprocessor
From Wikipedia, the free encyclopedia
(Redirected from Preprocessing)
In computer science, a preprocessor is a program that processes its input data to produce output that is used
as input to another program. The output is said to be a preprocessed form of the input data, which is often
used by some subsequent programs like compilers. The amount and kind of processing done depends on the
nature of the preprocessor; some preprocessors are only capable of performing relatively simple textual
substitutions and macro expansions, while others have the power of fully-fledged programming languages.
A common example from computer programming is the processing performed on source code before the next
step of compilation. In some computer languages (e.g., C and PL/I ) there is a phase oftranslation known
as preprocessing.
Contents
[hide]
• 1 Lexical preprocessors
○ 1.1 C preprocessor
• 2 Syntactic preprocessors
○ 2.1 Customizing
syntax
○ 2.2 Extending a
language
○ 2.3 Specializing a
language
• 3 General purpose
preprocessor
• 4 See also
• 5 References
• 6 External links
[edit]Lexical preprocessors
Lexical preprocessors are the lowest-level of preprocessors, insofar as they only require lexical analysis, that
is, they operate on the source text, prior to any parsing, by performing simple substitution
of tokenized character sequences for other tokenized character sequences, according to user-defined rules.
They typically perform macro substitution, textual inclusion of other files, and conditionalcompilation or
inclusion.
[edit]C preprocessor
The most common example of this is the C preprocessor, which takes lines beginning with '#' as directives.
Because it knows nothing about the underlying language, its use has been criticized and many of its features
built directly into other languages. For example, macros replaced with aggressive inlining and templates,
includes with compile-time imports(this requires the preservation of type information in the object code, making
this feature impossible to retrofit into a language); conditional compilation is effectively accomplished with if-
then-else and dead code elimination in some languages.
Syntactic preprocessors were introduced with the Lisp family of languages. Their role is to transform syntax
trees according to a number of user-defined rules. For some programming languages, the rules are written in
the same language as the program (compile-time reflection). This is the case with Lisp and OCaml. Some other
languages rely on a fully external language to define the transformations, such as the XSLT preprocessor
for XML, or its statically typed counterpart CDuce.
Syntactic preprocessors are typically used to customize the syntax of a language, extend a language by adding
new primitives, or embed a Domain-Specific Programming Language inside a general purpose language.
[edit]Customizing syntax
A good example of syntax customization is the existence of two different syntaxes in the Objective
Caml programming language.[1] Programs may be written indifferently using the "normal syntax" or the "revised
syntax", and may be pretty-printed with either syntax on demand.
Similarly, a number of programs written in OCaml customize the syntax of the language by the addition of new
operators.
[edit]Extending a language
The best examples of language extension through macros are found in the Lisp family of languages. While the
languages, by themselves, are simple dynamically-typed functional cores, the standard distributions
of Scheme or Common Lisp permit imperative or object-oriented programming, as well as static typing. Almost
all of these features are implemented by syntactic preprocessing, although it bears noting that the "macro
expansion" phase of compilation is handled by the compiler in Lisp. This can still be considered a form of
preprocessing, since it takes place before other phases of compilation.
Similarly, statically-checked, type-safe regular expressions or code generation may be added to the syntax and
semantics of OCaml through macros, as well as micro-threads (also known ascoroutines or fibers), monads or
transparent XML manipulation.
[edit]Specializing a language
One of the unusual features of the Lisp family of languages is the possibility of using macros to create an
internal Domain-Specific Programming Language. Typically, in a large Lisp-based project, a module may be
written in a variety of such minilanguages, one perhaps using a SQL-based dialect of Lisp, another written in a
dialect specialized for GUIs or pretty-printing, etc. Common Lisp's standard library contains an example of this
level of syntactic abstraction in the form of the LOOP macro, which implements an Algol-like minilanguage to
describe complex iteration, while still enabling the use of standard Lisp operators.
The MetaOCaml preprocessor/language provides similar features for external Domain-Specific Programming
Languages. This preprocessor takes the description of the semantics of a language (i.e. an interpreter) and, by
combining compile-time interpretation and code generation, turns that definition into a compiler to
the OCaml programming language—and from that language, either to bytecode or to native code.`
Most preprocessors are specific to a particular data processing task (e.g., compiling the C language). A
preprocessor may be promoted as being general purpose, meaning that it is not aimed at a specific usage or
programming language, and is intended to be used for a wide variety of text processing tasks.
M4 is probably the most well known example of such a general purpose preprocessor, although
the C preprocessor is sometimes used in a non-C specific role. Examples:
using M4 (see on-article example) or C preprocessor [3] as a template engine, to HTML generation.
imake, a make interface using the C preprocessor, used in the X Window System but now deprecated in
favour of automake.
grompp, a preprocessor for simulation input files for GROMACS (a fast, free, open-source code for some
problems in computational chemistry which calls the system C preprocessor (or other preprocessor as
determined by the simulation input file) to parse the topology, using mostly the #define and #include
mechanisms to determine the effective topology at grompp run time.
Parsing
From Wikipedia, the free encyclopedia
"Parse" redirects here. For the ice hockey player, see Scott Parse. For the company, see Parsé Semiconductor
Co..
"Parser" redirects here. For the computer programming language, see Parser (CGI language).
In computer science and linguistics, parsing, or, more formally, syntactic analysis, is the process of analyzing
a text, made of a sequence of tokens (for example, words), to determine its grammatical structure with respect
to a given (more or less) formal grammar. Parsing can also be used as a linguistic term, especially in reference
to how phrases are divided up in garden path sentences.
Parsing is also an earlier term for the diagramming of sentences of natural languages, and is still used for the
diagramming of inflected languages, such as the Romance languages or Latin. The term parsing comes from
Latin pars (ōrātiōnis), meaning part (of speech).[1][2]
Parsing is a common term used in psycholinguistics when describing language comprehension. In this context,
parsing refers to the way that human beings, rather than computers, analyze a sentence or phrase (in spoken
language or text) "in terms of grammatical constituents, identifying the parts of speech, syntactic relations,
etc." [3] This term is especially common when discussing what linguistic cues help speakers to parse garden-
path sentences.
Parser
In computing, a parser is one of the components in an interpreter or compiler, which checks for correct
syntax and builds a data structure (often some kind of parse tree, abstract syntax tree or other
hierarchical structure) implicit in the input tokens. The parser often uses a separate lexical analyser to
create tokens from the sequence of input characters. Parsers may be programmed by hand or may be
(semi-)automatically generated (in some programming languages) by a tool.
Overview of process
The following example demonstrates the common case of parsing a computer language with two levels of
grammar: lexical and syntactic.
The first stage is the token generation, or lexical analysis, by which the input character stream is split into
meaningful symbols defined by a grammar of regular expressions. For example, a calculator program
would look at an input such as "12*(3+4)^2" and split it into the tokens 12, *, (, 3, +, 4, ), ^, and 2,
each of which is a meaningful symbol in the context of an arithmetic expression. The lexer would contain
rules to tell it that the characters *, +, ^, ( and ) mark the start of a new token, so meaningless tokens
like "12*" or "(3" will not be generated.
The next stage is parsing or syntactic analysis, which is checking that the tokens form an allowable
expression. This is usually done with reference to a context-free grammarwhich recursively defines
components that can make up an expression and the order in which they must appear. However, not all
rules defining programming languages can be expressed by context-free grammars alone, for example
type validity and proper declaration of identifiers. These rules can be formally expressed with attribute
grammars.
The final phase is semantic parsing or analysis, which is working out the implications of the expression
just validated and taking the appropriate action. In the case of a calculator or interpreter, the action is to
evaluate the expression or program; a compiler, on the other hand, would generate some kind of code.
Attribute grammars can also be used to define these actions.
Examples of parsers
[edit]Top-down parsers
Some of the parsers that use top-down parsing include:
Earley parser
Precedence parser
Operator-precedence parser
LALR parser
GLR parser
CYK parser
Syntax-directed translation
From Wikipedia, the free encyclopedia
This article is an orphan, as few or no other articles link to it. Please introduce
links to this page from related articles; suggestions are available. (January 2010)
[edit]General Explanation
Each symbol in the grammar can have an attribute, which is a value that is to be associated with the symbol.
Common attributes could include a variable type, the value of an expression, etc. Given a symbol X, with an
attribute t, that attribute is referred to as X.t
Thus, given actions and attributes, the grammar can be used for translating strings from its language by
applying the actions and carrying information through each symbol's attribute.
This article is about machine code generation with a compiler. For other uses, see Code generation
(disambiguation).
In computer science, code generation is the process by which a compiler's code generator converts
some intermediate representation of source code into a form (e.g., machine code) that can be readily executed
by a machine (often a computer).
Sophisticated compilers typically perform multiple passes over various intermediate forms. This multi-stage
process is used because many algorithms for code optimization are easier to apply one at a time, or because
the input to one optimization relies on the processing performed by another optimization. This organization also
facilitates the creation of a single compiler that can target multiple architectures, as only the last of the code
generation stages (the backend) needs to change from target to target. (For more information on compiler
design, see Compiler.)
The input to the code generator typically consists of a parse tree or an abstract syntax tree. The tree is
converted into a linear sequence of instructions, usually in an intermediate language such asthree address
code. Further stages of compilation may or may not be referred to as "code generation", depending on whether
they involve a significant change in the representation of the program. (For example, a peephole
optimization pass would not likely be called "code generation", although a code generator might incorporate a
peephole optimization pass.)
Contents
[hide]
generation
• 3 Related concepts
○ 3.1 Reflection
In addition to the basic conversion from an intermediate representation into a linear sequence of machine
instructions, a typical code generator tries to optimize the generated code in some way. The generator may try
to use faster instructions, use fewer instructions, exploit available registers, and avoid redundant computations.
Tasks which are typically part of a sophisticated compiler's "code generation" phase include:
Instruction scheduling: in which order to put those instructions. Scheduling is a speed optimization that can
have a critical effect on pipelined machines.
In a compiler that uses an intermediate language, there may be two instruction selection stages — one to
convert the parse tree into intermediate code, and a second phase much later to convert the intermediate code
into instructions from the instruction set of the target machine. This second phase does not require a tree
traversal; it can be done linearly, and typically involves a simple replacement of intermediate-language
operations with their corresponding opcodes. However, if the compiler is actually a language translator (for
example, one that converts Eiffel to C), then the second code-generation phase may involve building a tree
from the linear intermediate code.
When code generation occurs at runtime, as in just-in-time compilation (JIT), it is important that the entire
process be efficient with respect to space and time. For example, when regular expressionsare interpreted and
used to generate code at runtime, a non-determistic finite state machine is often generated instead of a
deterministic one, because usually the former can be created more quickly and occupies less memory space
than the latter. Despite its generally generating less efficient code, JIT code generation can take advantage
of profiling information that is available only at runtime.
[edit]Related concepts
The fundamental task of taking input in one language and producing output in a non-trivially different language
can be understood in terms of the core transformational operations of formal language theory. Consequently,
some techniques that were originally developed for use in compilers have come to be employed in other ways
as well. For example, YACC (Yet Another Compiler Compiler) takes input in Backus-Naur form and converts it
to a parser in C. Though it was originally created for automatic generation of a parser for a compiler, yacc is
also often used to automate writing code that needs to be modified each time specifications are changed. (For
example, see [1].)
Many integrated development environments (IDEs) support some form of automatic source code generation,
often using algorithms in common with compiler code generators, although commonly less complicated. (See
also: Program transformation, Data transformation.)
[edit]Reflection
In general, a syntax and semantic analyzer tries to retrieve the structure of the program from the source code,
while a code generator uses this structural information (e.g., data types) to produce code. In other words, the
former adds information while the latter loses some of the information. One consequence of this information
loss is that reflection becomes difficult or even impossible. To counter this problem, code generators often
embed syntactic and semantic information in addition to the code necessary for execution.
Program optimization
From Wikipedia, the free encyclopedia
(Redirected from Code optimization)
In computer science, program optimization or software optimization is the process of modifying a software
system to make some aspect of it work more efficiently or use fewer resources.[1] In general, a computer
program may be optimized so that it executes more rapidly, or is capable of operating with less memory
storage or other resources, or draw less power.
Although the word "optimization" shares the same root as "optimal," it is rare for the process of
optimization to produce a truly optimal system. The optimized system will typically only be optimal in one
application or for one audience. One might reduce the amount of time that a program takes to perform
some task at the price of making it consume more memory. In an application where memory space is at a
premium, one might deliberately choose a slower algorithm in order to use less memory. Often there is no
“one size fits all” design which works well in all cases, so engineers make trade-offs to optimize the
attributes of greatest interest. Additionally, the effort required to make a piece of software completely
optimal—incapable of any further improvement— is almost always more than is reasonable for the
benefits that would be accrued; so the process of optimization may be halted before a completely optimal
solution has been reached. Fortunately, it is often the case that the greatest improvements come early in
the process.
[edit]"Levels" of optimization
Optimization can occur at a number of "levels":
Design level
At the highest level, the design may be optimized to make best use of the available resources. The
implementation of this design will benefit from a good choice of efficient algorithms and the
implementation of these algorithms will benefit from writing good quality code. The architectural design of
a system overwhelmingly affects its performance. The choice of algorithm affects efficiency more than
any other item of the design and, since the choice of algorithm usually is the first thing that must be
decided, arguments against early or "premature optimization" may be hard to justify.
In some cases, however, optimization relies on using more elaborate algorithms, making use of 'special
cases' and special 'tricks' and performing complex trade-offs. A 'fully optimized' program might be more
difficult to comprehend and hence may contain more faults than unoptimized versions.
Avoiding poor quality coding can also improve performance, by avoiding obvious 'slowdowns'. After that,
however, some optimizations are possible that actually decrease maintainability. Some, but not all,
optimizations can nowadays be performed by optimizing compilers.
Compile level
Use of an optimizing compiler tends to ensure that the executable program is optimized at least as much
as the compiler can predict.
Assembly level
At the lowest level, writing code using an assembly language, designed for a particular hardware platform
can produce the most efficient and compact code if the programmer takes advantage of the full repertoire
of machine instructions. Many operating systems used on embedded systems have been traditionally
written in assembler code for this reason; when efficiency and size are less important large parts may be
written in a high-level language.
With more modern optimizing compilers and the greater complexity of recent CPUs, it is more difficult to
write code that is optimized better than the compiler itself generates, and few projects need resort to this
'ultimate' optimization step.
However, a large amount of code written today is still compiled with the intent to run on the greatest
percentage of machines possible. As a consequence, programmers and compilers don't always take
advantage of the more efficient instructions provided by newer CPUs or quirks of older models.
Additionally, assembly code tuned for a particular processor without using such instructions might still be
suboptimal on a different processor, expecting a different tuning of the code.
Run time
Just in time compilers and Assembler programmers may be able to perform run time optimization
exceeding the capability of static compilers by dynamically adjusting parameters according to the actual
input or other factors.
Platform dependent and independent optimizations
Code optimization can be also broadly categorized as platform-dependent and platform-independent
techniques. While the latter ones are effective on most or all platforms, platform-dependent techniques
use specific properties of one platform, or rely on parameters depending on the single platform or even on
the single processor. Writing or producing different versions of the same code for different processors
might therefore be needed. For instance, in the case of compile-level optimization, platform-independent
techniques are generic techniques (such as loop unrolling, reduction in function calls, memory efficient
routines, reduction in conditions, etc.), that impact most CPU architectures in a similar way. Generally,
these serve to reduce the total Instruction path length required to complete the program and/or reduce
total memory usage during the process. On the other hand, platform-dependent techniques involve
instruction scheduling, instruction-level parallelism, data-level parallelism, cache optimization techniques
(i.e. parameters that differ among various platforms) and the optimal instruction scheduling might be
different even on different processors of the same architecture.
Interpreter (computing)
From Wikipedia, the free encyclopedia
In computer science, an interpreter normally means a computer program that executes, i.e. performs,
instructions written in a programming language. An interpreter may be a program that either
2. translates source code into some efficient intermediate representation (code) and immediately
executes this
3. explicitly executes stored precompiled code[1] made by a compiler which is part of the interpreter
system
Perl, Python, MATLAB, and Ruby are examples of type 2, while UCSD Pascal and Java are type 3: Source
programs are compiled ahead of time and stored as machine independent code, which is then linked at run-
time and executed by an interpreter and/or compiler (for JIT systems). Some systems, such
as Smalltalk, BASIC and others, may also combine 2 and 3.
While interpreting and compiling are the two main means by which programming languages are implemented,
these are not fully distinct categories, one of the reasons being that most interpreting systems also perform
some translation work, just like compilers. The terms "interpreted language" or "compiled language" merely
mean that the canonical implementation of that language is an interpreter or a compiler; a high level language
is basically an abstraction which is (ideally) independent of particular implementations.
Bytecode interpreters
Main article: Bytecode
There is a spectrum of possibilities between interpreting and compiling, depending on the amount of
analysis performed before the program is executed. For example, Emacs Lisp is compiled tobytecode,
which is a highly compressed and optimized representation of the Lisp source, but is not machine code
(and therefore not tied to any particular hardware). This "compiled" code is then interpreted by a bytecode
interpreter (itself written in C). The compiled code in this case is machine code for a virtual machine,
which is implemented not in hardware, but in the bytecode interpreter. The same approach is used with
the Forth code used in Open Firmware systems: the source language is compiled into "F code" (a
bytecode), which is then interpreted by a virtual machine.
Control tables - that do not necessarily ever need to pass through a compiling phase - dictate appropriate
algorithmic control flow via customized interpreters in similar fashion to bytecode interpreters.
[edit]Development cycle
During program development, the programmer makes frequent changes to source code. A compiler
needs to make a compilation of the altered source files, and link the whole binary code before the
program can be executed. An interpreter usually just needs to translate to an intermediate representation
or not translate at all, thus requiring less time before the changes can be tested.
This often makes interpreted languages generally easier to learn and find bugs and correct problems.
Thus simple interpreted languages tend to have a friendlier environment for beginners.
[edit]Distribution
A compiler converts source code into binary instruction for a specific processor's architecture, thus
making it less portable. This conversion is made just once, on the developer's environment, and after that
the same binary can be distributed to the user's machines where it can be executed without further
translation.
An interpreted program can be distributed as source code. It needs to be translated in each final machine,
which takes more time but makes the program distribution independent to the machine's architecture.
[edit]Execution environment
An interpreter will make source translations during runtime. This means every line has to be converted
each time the program runs. This process slows down the program execution and is a major
disadvantage of interpreters over compilers. Another main disadvantage of interpreter is that it must be
present on the machine as additional software to run the program.