Lectures Section 3 Modified

Embed Size (px)

Citation preview

  • 8/3/2019 Lectures Section 3 Modified

    1/73

    Computer Architecturesand Principles

    M09CDE

  • 8/3/2019 Lectures Section 3 Modified

    2/73

    Sequence of Control

    A special group of machine code instructions areconcerned with taking decisions and altering theflow of activity in the processor.

    To do this they have to change the sequence ofinstructions which is actually quite simple.

    The Program Counter, PC, holds the address ofthe next instruction to execute so if a giveninstruction writes a new address to PC, then thenext instruction will be taken from this newlocation.

  • 8/3/2019 Lectures Section 3 Modified

    3/73

    In order to get to this address we can either :-

    1 overwrite PC with new value (called 'absolute' address)2 add/subtract an offset from PC (called 'relative' address)

    The instructions which cause changes of location are often

    called JUMPs or BRANCHes, and usually JUMPs areabsolute whereas BRANCHes are relative.

    However, this is not a fixed rule so beware of precisemeanings in low-level program definitions.

    Perhaps it is better to call them all jumps and put the

    words absolute or relative in front.

  • 8/3/2019 Lectures Section 3 Modified

    4/73

    Changes of place in the program can oftenbe 'conditional' (they depend on the

    outcome of some evaluation) but they aresometimes 'unconditional' (they take placeno matter what).

    For the conditional jumps and branches,some aspect of the latest result generatedby the ALU might be checked. A number ofpossibilities exist and each one causes a 1

    or a 0 to be placed in a special registercalled the condition codes (CC) or flagsregister.

  • 8/3/2019 Lectures Section 3 Modified

    5/73

    Each bit position of this register represents aparticular condition which may be true (in which

    case it will be set to 1) or false (in which case it willbe set to 0). Thus the outputs from the ALU are notconfined to the data lines but also include someextra signals indicating the condition of the result.

  • 8/3/2019 Lectures Section 3 Modified

    6/73

    The most important conditions are :-

    Zero (Z flag) - result of the last evaluation was zero

    Negative (N flag) - result of last evaluation had the most

    significant bit set to 1 (i.e. 2s-comp neg)

    Carry (C flag) - last evaluation caused a carry from themost significant bit

    Overflow (V flag) - an arithmetic overflow occurred such as

    in 2s complement when two positive

    numbers are added and carry into themost significant bit therefore appearing

    to be a negative result

  • 8/3/2019 Lectures Section 3 Modified

    7/73

    If the item to be tested was not generated asa result by the ALU, then a test instruction

    of some kind may be needed.

    This will simply put the value through oneleg of the ALU with no operation taking

    place and set the flags according to theoutput.

    Such a null operation is clearly arequirement in the ALUs repertoire.

  • 8/3/2019 Lectures Section 3 Modified

    8/73

    For example, we may have the following instruction in direct mode :-

    TST 1234Set flags according to value of item found at address location 1234

    Instruction fetch as usualPC MAR send a copy of PC contents to MAR(increment PC) PC has 1 added to it so it points to the next instructionMAR store the instruction is fetched from storestore MDR and placed in the MDR

    DecodeMDR IR instruction is moved to instruction register(decode) decoding of opcode occurs

    Operand fetchIRADDR MAR the address of the data required is put into MAR

    MAR store the data address is sent to the storestore MDR and the data there is fetched and placed in the MDR

    ExecuteMDR ALU(via bus) null operation sets flags

    Write nothing to do here

  • 8/3/2019 Lectures Section 3 Modified

    9/73

    Following an instruction which alters the conditioncodes register, a conditional jump or branch

    instruction would then determine whether or not tooverwrite PC.

    In practice, it sets up a write to PC and uses the

    combination of flags to decide whether or not tosuppress the PCs load signal.

    A very large set of conditional jump/branch

    instructions are possible which evaluate singleflags or combinations to cause changes in flow.

  • 8/3/2019 Lectures Section 3 Modified

    10/73

    A few examples are :-

    BEQ - branch if result equal to zero (Z=1)

    BNE - branch if result not equal to zero (Z=0)BMI - branch if result negative (N=1)BGE - branch if result greater than or equal to

    zero (Z=1 or N=0)

    BCS - branch if carry was caused (C=1)BCC - branch if carry was not caused (C=0)BRA - branch always (i.e. unconditional branch)JMP - jump always

    There are two examples (JMP and BEQ) given in theprinted notes on the web site.

  • 8/3/2019 Lectures Section 3 Modified

    11/73

    Can now describe the operation of the instruction decoder.

    - Each step in instruction cycle (RTL line) is actually adescription of data movement or action needing control

    - Individual intervals of time will all be of same length- usually called 'beats' or 'clock ticks'.

    Control signals may :-1. cause a register to load the value present on its inputs

    at the end of the 'beat',2. gate a register onto a bus3. cause a multiplexer to choose one of its inputs,4. select particular function for ALU or other units,5. set/clear individual bits in certain registers (e.g. CC).

    The Decoder

  • 8/3/2019 Lectures Section 3 Modified

    12/73

    - Each step in every cycle has pattern of controlsignals produced by the instruction decoder.

    - The patterns are produced in response to atiming signal or 'clock'.

    - Which pattern is produced at a particular point inthe cycle is governed by 'state counter'. This is aregister holding simple binary count which isincremented for each beat & reset at cycle end.

    - The value it holds at any time is called themachine state.

  • 8/3/2019 Lectures Section 3 Modified

    13/73

    Control signals will also be produced to govern theoperation and timing of activities outside the processor.

    These are distributed around the machine as part of thesystem bus whose other components are the systemaddress from MAR and data, to or from MDR.

    Examples of these signals include the read/write controls,

    valid memory address signals, resets, etc.

    The decoder itself has a number of inputs which determinethe control signal outputs. These inputs include the op-code from the instruction held in the instruction register, the

    state count and the condition codes.

    In addition to these inputs, the decoder receives signalsfrom outside the processor, notably the interrupt lines.

  • 8/3/2019 Lectures Section 3 Modified

    14/73

  • 8/3/2019 Lectures Section 3 Modified

    15/73

    The most obvious structure for the decoder is thusa complex mesh of gates permanently producing

    control signals as determined by the current :-- op-code,

    - machine state and

    - condition codes.

    Called a direct or hardwired decoder.

    Main advantage is that it is potentially the fastestcontrol system and hence ought to produce aprocessor with the highest performance.

  • 8/3/2019 Lectures Section 3 Modified

    16/73

    However, it has a serious inherent drawback. Inorder to build it, this type of decoder goes through

    2 main stages :-

    design definition where, by using a truth tablestyle of approach, the control signals produced forevery state in each op-codesequence under everyconditionare defined and

    realisation stage where the actual logic isdesigned and optimised.

    Because of second stage, this method has highcost and delay associated with design phase and itis rather difficult to make changes or corrections.

  • 8/3/2019 Lectures Section 3 Modified

    17/73

    How Complex is the Decoder?

    It is an instructive exercise to try to computethe complexity of the decoder needed for acomparatively simple machine.

    The next diagram is a simplified example ofthe data flow in a processor. We can use itto make an estimate of the controls to all

    parts of processor element, i.e. the outputsfrom the decoder.

  • 8/3/2019 Lectures Section 3 Modified

    18/73

    Assume that IR, PC, SP, X, Acc & OB have load and outputcontrols; do nothing is also needed so we need two lines each. IB and MAR need only a load each.

    MDR needs load, output and direction (in/out) making three. The ALU needs perhaps seven to give it a complete repertoire of

    functions. Finally at least two lines are needed to control store activity;possibly these could be read and write thus giving another donothing setting.

    This adds up to twenty six controls but it is a rather crude estimate.

  • 8/3/2019 Lectures Section 3 Modified

    19/73

    Now we can estimate the signals coming intothe decoder from :-

    the op-code part of IR (at least 8 bits to givea reasonable instruction set),

    the condition codes register ( 4 bits for a

    sensible set of conditionals, Z, N, C, V), the machine state counter (probably 5 bits

    minimum to give 32 [25] states but possiblymore) and

    interrupt lines - signals to the CPU fromelsewhere in the machine (~ 4 bits see later)

  • 8/3/2019 Lectures Section 3 Modified

    20/73

    This adds up to twenty one inputs and thus todesign the hardwired decoder we must begin

    with a truth table which has 221 states andtherefore over two million lines.

    This is a daunting task and if a mistake is madeor a late alteration required then the cost ofredesign from this point would be huge.

    Of course, we actually need twenty six suchtruth tables because we need one for eachpossible control output!

  • 8/3/2019 Lectures Section 3 Modified

    21/73

    Control Structuresat High and Low Level

    A machine-code program is a sequence ofinstructions held in memory.

    - executed one-by-one in sequence- next instruction coming from next location in memory- using Program Counter to step from one to the next

    We should therefore use the word program to meanthe sequence of instructions as written or as stored in

    memory.Such program structure is not very flexible nor useful -need very long programs to achieve any useful task.

  • 8/3/2019 Lectures Section 3 Modified

    22/73

    Useful programs contain repetitions of programsegments (called iterations or loops) and decisionmaking instructions which can alter the flow.

    Some instructions alter PC in order to changesequence; e.g. jumps and branches, etc.

    Because of alterations in flow, sequence ofinstructions actually executed (instruction stream)

    may not follow order of appearance in the program. Examples of loops can be seen in high-level

    programming languages.

    How they are implemented in machine code gives usan insight into :-

    how they work,

    why they are different and

    which one to choose.

  • 8/3/2019 Lectures Section 3 Modified

    23/73

    FOR Loop

    FORDOEND

    set a loop counter to the ;again: do the of instructions once;

    decrement (take one away from) the loop counter;if the loop count value is not zero, go back to again;

  • 8/3/2019 Lectures Section 3 Modified

    24/73

    Loop UNTIL

    DOUNTILEND

    again: do the of instructions once;

    evaluate and if not true go back to again;

  • 8/3/2019 Lectures Section 3 Modified

    25/73

    WHILE Loop

    WHILEDOEND

    again: evaluate and if not true go to end;

    do the of instructions once;

    go back to again;

    end:

  • 8/3/2019 Lectures Section 3 Modified

    26/73

    One of the most important issues forchoosing a loop type is deciding where in

    the sequence the test takes place.

    With until it takes place at the end of the

    loop so the sequence is always executed atleast once.

    With while it takes place at the start so thesequence might never be executed.

  • 8/3/2019 Lectures Section 3 Modified

    27/73

    For is only used when the number of loops is

    exactly known beforehand so that a counter can

    be set up.

    Counting down to zero and testing for zero (usingthe Zero flag) is easier than counting up to a value

    and doing a subtraction.

    Ways of implementing for may vary with the high-

    level language. The format shown means that thesequence is always done once becauseFOR would make no sense.

  • 8/3/2019 Lectures Section 3 Modified

    28/73

    All of these loops require some simple

    decision making. Based on an evaluation,the flow of control in the program may ormay not be changed.

    Another type of decision making constructalso exists in high-level languages.

  • 8/3/2019 Lectures Section 3 Modified

    29/73

    IFTHENELSEEND

    evaluate the ;

    if it is true go to true;do the instructions;

    go to end;

    true: do the instructions;end:

  • 8/3/2019 Lectures Section 3 Modified

    30/73

    These constructs are used in low-level programsand high-level languages

    It is to implement them that the flags register andconditional jump instructions exist.

    It helps to understand how low level programmingworks in order that we can understand thestructure of high level languages.

    Similarly, it is useful to have a look at how somesimple data structures are implemented and thiswill be covered later.

  • 8/3/2019 Lectures Section 3 Modified

    31/73

    Subroutines

    Loops cut down size of programs They do this by repetition of sequences

    Limited by repeats having to be sequential

    Sometimes the same sequence is neededat unconnected parts of a program

    This would still save space and time to write

    This is the idea behind a subroutine in low-level programming

  • 8/3/2019 Lectures Section 3 Modified

    32/73

    A subroutine is an instruction sequence which can bejumped to (called) from more than one place in program

    Uses special machine code instruction

    e.g. JSR (jump to subroutine) Jumped-to by overwriting PC in the usual way

    Have to have a way of jumping back to the place it wascalled from when the subroutine is completed

    JSR could copy current contents of PC (address ofinstruction following JSR) into a special location

    Could retrieve this at the end of the subroutine and write itinto PC

    Thus it returns to where it was called from

    A detailed explanation of this with diagramsappears in the written notes. Please read it carefully.

  • 8/3/2019 Lectures Section 3 Modified

    33/73

    With only one special location, you cant call one

    subroutine from within another and thus nest them

    Causes big restrictions on flexibility & space savingpotential of subroutines so it is not done this way.

    We need a place that we can write more than onereturn address to and retrieve them in the reverse

    order that they were written in. Need a last-in-first-out queue (LIFO queue)

    usually referred to as a stack.

    Good analogy is a pile of plates where we can onlyreally access the top one but once we haveremoved it, another top one appears.

  • 8/3/2019 Lectures Section 3 Modified

    34/73

    Within register set of CPU we need a Stack Pointer(SP) register

    Holds address of current front of LIFO queue

    Can use this to write the contents of PC to thestore

    We can change SP whenever we use it so that wecan write to it again

    At the end of subroutine we execute return

    instruction which returns program flow to the place

    the subroutine was called from

    Does this by getting the last value off the stack

  • 8/3/2019 Lectures Section 3 Modified

    35/73

    We retrieve items from stack in reverseorder in which they were written

    Also need to modify contents of SP in theopposite direction to that done when wewrite items to the stack

    Doesnt matter whether we grow stack

    up or down store nor whether we pointat topmost item or first free location

    We only need to choose a convention and

    keep to it!

    Please read detailed description in notes.

  • 8/3/2019 Lectures Section 3 Modified

    36/73

    Recursion Using stack mechanism, subroutine can call another

    subroutine from within itself almost without limit. It could even call itself!

    This last idea is called recursion

    Can be very useful but must be used with great care

    We must guarantee that eventually we will meet acondition in the recursive subroutine where the flow ofcontrol begins to return and will unstack all the queuedPC contents.

    The program must unravel itself before the amount ofstorage allocated to the stack is exceeded.

  • 8/3/2019 Lectures Section 3 Modified

    37/73

    One famous recursive process is to calculate

    the factorial of a number.

    Factorial 6 (written 6!) is 6 x 5 x 4 x 3 x 2 x 1

    This example is endlessly quoted in textbooks even though it is a terribly inefficient

    way of performing the calculation!

  • 8/3/2019 Lectures Section 3 Modified

    38/73

    First a routine is called with the number whos

    factorial is required in the accumulator.

    This routine stacks the number,

    checks that the number is greater than 1

    subtracts 1 from it

    calls itself with the new value.

    If the number is equal to 1, then

    it unstacks the latest number

    multiplies it by contents of accumulator puts the result in the accumulator

    returns

  • 8/3/2019 Lectures Section 3 Modified

    39/73

    FACTORIAL: PUSH (ACC)

    IF GO TO EXIT

    SUBTRACT 1 FROM ACC

    CALL FACTORIAL

    EXIT: MULTIPLY ACC BY & STORE IN ACC

    RETURN

    E hi k d ll b k d

  • 8/3/2019 Lectures Section 3 Modified

    40/73

    Everything stacked must eventually be unstacked.

    Otherwise stack will grow uncontrollably, overwrite

    other storage areas and the whole process will runout of control

    Some CPUs have more than one Stack Pointer

    Machine code instructions :-PUSH (put something on stack)POP (or PULL, take something off stack)

    When more than one stack, one is designatedsystem stack and used for automatic stackingfunctions such as subroutines and other similarprocesses (exception conditions - interrupts).

  • 8/3/2019 Lectures Section 3 Modified

    41/73

    ReflectionIt is now possible to see why we distinguish :-

    the program - the list of instructions aswritten by the programmer

    from the

    instruction stream - the sequence of

    instructions actually executed by the CPU.

    See notes for an example.

  • 8/3/2019 Lectures Section 3 Modified

    42/73

    Languages & Language Translation

    We have met a number of types of computer language and have formed some ideas how they are structured and what they do

    We need to have some clearer definitions of these and extend these ideas towards high-level languages

    This is :- essential working vocabulary of computing essential that we know and agree what terms mean

  • 8/3/2019 Lectures Section 3 Modified

    43/73

    Low-level languages

    Lowest level language is called machine code. The only language that the computer actually runs Consists of a large number of different instructions each one describing what the CPU should do (the opcode) and what data item(s) it should do it with (operand address(es)).

    Machine code is particular to a design of processor will not work on one of a different type because the instructions (represented as patterns of 1s and 0s)

    are directly decoded by the processor into control signals thatcause the data movements, transformation, etc.

    Collection of all permitted instructions is called instruction set Instruction set is most important physical characteristic

  • 8/3/2019 Lectures Section 3 Modified

    44/73

    From a human point of view, machine code israther impenetrable.

    It certainly is possible to write programsactually in machine code

    need list of all of the instructions as 1s an 0s

    Would be very slow unproductive tedious

    Humans do not work well with nor rememberpatterns of binary digits.

    Machine code languages sometimes referredto as first generation languages or 1GLs.

  • 8/3/2019 Lectures Section 3 Modified

    45/73

    At this low level of programming is easier torepresent each instruction opcode with amemorable, word-like symbolmnemonic

    means something to aid memory

    Abbreviated descriptions of instruction

    ld (load) st (store) add sub jmp

    Followed by more human-friendly version ofthe operand

    written in appropriate number base or as thename of a register or location in store.

  • 8/3/2019 Lectures Section 3 Modified

    46/73

    More human-friendly version of machine code iscalled assembly code.

    Because each assembly code instruction isexact equivalent of a machine code instruction(1-1 correspondence) machine code andassembly code often used interchangeably

    Shouldnt be!

    Extra refinement is to label some of the

    instructions (give a name to the place in storethat they occupy)

    Easier to represent jumps to the namedinstruction.

  • 8/3/2019 Lectures Section 3 Modified

    47/73

    Possible and quite easy for person to

    translate assembly code intomachine code by hand

    Still quite tedious

    Would be better to have a programthat does the translation for us.

    This program is an assembler.

  • 8/3/2019 Lectures Section 3 Modified

    48/73

    Because of absolute addresses, labelshave to be translated into numericaladdresses in memory.

    Low level programs can usually be placedat (we say loaded into) any part of the

    main store.

  • 8/3/2019 Lectures Section 3 Modified

    49/73

    Assemblers work in two possible waysbecause of forward reference problem.

    When assembly code is assembled, somejumps and branches refer to places notassembled yet.

    - address is not yet known.

    Two solutions give rise to the two types of

    assembler.

  • 8/3/2019 Lectures Section 3 Modified

    50/73

    Single pass assemblers

    leave a space in assembled code right size forthe address

    also save in a table information about where this

    space is. After main translation, all addresses known -

    assembler uses table to go back and fill-inspaces with correct absolute address or branchdistance.

    This is a bit complicated.

  • 8/3/2019 Lectures Section 3 Modified

    51/73

    Two pass assemblers

    read code twice

    In first, simply work out how much spaceeach instruction needs

    every time they meet a label, put this in atable with the corresponding address.

    On second pass, actually assemble code,

    filling in the addresses from the table. Easier system and nearly always is the

    way an assembler will work.

  • 8/3/2019 Lectures Section 3 Modified

    52/73

    After assembly, symbol reference tableis no longer needed

    Machine code can be loaded into thecorrect place in the main store.

  • 8/3/2019 Lectures Section 3 Modified

    53/73

    Good idea to use previously written bits of code toavoid having to write them again.

    Can be incorporated in a process called linking Similar to forward reference system except care

    must be taken because

    same ref names may be used in both main

    program and previously written segments. Main program could also refer to items in

    segments

    Problems resolved by program called linker orlink editor.

    Produces both code to be run and a link table.

  • 8/3/2019 Lectures Section 3 Modified

    54/73

    The Loader

    A program called a loader used to transferrun-able machine code into store at givenplaces with the correct references inserted

    Does by looking at the link table.

    Linking/loading has to be redone if code isto be put somewhere else in memory.

  • 8/3/2019 Lectures Section 3 Modified

    55/73

    Desirable to produce code which has noabsolute address references.

    To do this, relative addressing must be used Code is then termed relocatable or

    position independent code

    Needs no complicated address resolution. Rich instruction set & address modes

    needed

    Poorly architectured CPUs (first generationPCs) cannot do this

    Structure/convenience of software suffers.

  • 8/3/2019 Lectures Section 3 Modified

    56/73

    Tiny snippet of assembly code (68000 family)thanks to Alan Clements from Teeside University.

    Labels Instructions or directives CommentsOpcode OperandsORG $400 Start of program areaMOVE.B Value1,D0MOVE.B Value2,D1

    ADD.B D0,D1MOVE.B D1,ResultSTOP #$2700 Stop executionORG $1000 Start of data area

    Value1 DC.B 12 Store 12 in memory

    Value2 DC.B 24Result DS.B 1 Reserve a byte for ResultEND $400 End of program and entry point

    assembled code might look like :-

  • 8/3/2019 Lectures Section 3 Modified

    57/73

    g

    1 00400 ORG $400

    2 00400 103900001000 MOVE.B VALUE1,D0

    3 00406 123900001001 MOVE.B VALUE2,D14 0040C D200 ADD.B D0,D1

    5 0040E 13C100001002 MOVE.B D1,RESULT

    6 00414 4E722700 STOP #$2700

    7 01000 ORG $10008 01000 0C VALUE1: DC.B 12

    9 01001 18 VALUE2: DC.B 24

    10 01002 00000001 RESULT: DS.B 1

    11 00400 END $400

    After line number, see address where instruction or data will beplaced and then the actual machine code in hex notation.

    E l d ll d

  • 8/3/2019 Lectures Section 3 Modified

    58/73

    Early stored program computers all programmedin machine code - was no other way.

    Code often input using punched hole paper tapealready in use for teleprinters.

    Sections of program (routines) often added bysplicing a length of paper tape into main tape.

    A type of notation for programmers wasdeveloped and looked very like assembly code

    Had to be translated by hand into machine code.

    Systems to automatically translate thesenotations were the first assembly languages

    known as second generation languages, 2GLs.

  • 8/3/2019 Lectures Section 3 Modified

    59/73

    High-level languages Assembly language takes some tedium out of

    machine code programming

    Invention of subroutines by Maurice Wilkes ledto thoughts of more high level languages.

    Subroutines can be prewritten to do useful tasksand then reused in many different programs.

    Can be called by main program and have therelevant data passed over to them.

    On completion, they have carried out the taskand may hand back some data.

    H h d l d h id f

  • 8/3/2019 Lectures Section 3 Modified

    60/73

    He then developed the idea of a macro.

    Looks like assembly level instruction but is

    automatically translated by assembler(macro-assembler) into series ofinstructions.

    Possible to express complicated processin a single instruction.

    Breaks 1-1 linkage previously seen

    between assembly code instruction andmachine code instruction.

  • 8/3/2019 Lectures Section 3 Modified

    61/73

    Gradually, concept of high-level languagedeveloped

    specially selected keywords with definedmeanings are put together using simplerules (syntax)

    whole can be translated into very manylow-level language instructions.

    Since it is more expressive and readableby humans, it is much easier and moreefficient to program in these high levellanguages than in low-level ones.

  • 8/3/2019 Lectures Section 3 Modified

    62/73

    Translation of high-level languages into low-levelones is called compilation

    done by a compiler - quite complex program Sometimes compilation directly to machine code

    But strategic reasons why this is not preferred.

    Compilation normally into assembly code thenassembler can do next part into machine code.

    Often, this two-part process hidden from user

    only sees single compilation process

    but can specifically request intermediate codeoutput stage.

    M hi / bl d hi ifi

  • 8/3/2019 Lectures Section 3 Modified

    63/73

    Machine/assembly codes are machine specific

    (will only work on a particular design of processor)

    so compilers are also machine specific since theyproduce a specific machine or assembly code.

    Although much design will be common frommachine to machine, lots of work goes into finalcode generation stage costly!

    Portable compiler would be one which could work

    on many different machine designs In order for this to work all the machines would

    have to be able to run the code it produced.

  • 8/3/2019 Lectures Section 3 Modified

    64/73

    Not all high-level languages are compiled.

    Also possible to :-

    take each line of high-level language,

    work out what it wants to do,

    then do it and

    return for next line of high-level language.

    This process is called interpretation,

    Program to carry this out is interpreter

    such high-level languages are said to beinterpreted.

  • 8/3/2019 Lectures Section 3 Modified

    65/73

    Interpretation is a useful technique but has

    severe performance problems.

    Loops in the program (always lots) will be

    interpreted line-by-line on every pass through.

    Quite slow compared with compilation where

    translation to machine code is done only onceand loops run entirely in machine code.

    C d i h h ff f i i il

  • 8/3/2019 Lectures Section 3 Modified

    66/73

    Compared with the effort of writing a compiler,writing an interpreter is an easier task

    not necessary for interpreter to translate into low-level program but merely to carry out actions.

    Interpreters are useful for simple, short programswhere performance is not important.

    Changes can be made to the program veryrapidly which may have advantages.

    BASIC is the most famous such language

    though there are also compilers for BASIC and anuncountable number of varieties of BASIC.

    Th i t l hi id

  • 8/3/2019 Lectures Section 3 Modified

    67/73

    The virtual machine idea

    Simple, standardised machine design with simple low-levelassembly language

    often called an intermediate code. Virtual machine does not really need to exist in hardware it is simply a design.

    A compiler can be written to produce assembly code for VM. Interpreter then written to carry out tasks of VM assembly

    language instructions by interpretation.

    This interpreter will be reasonably easy to write because working at a low level, will be reasonably efficient and the program will run quickly.

  • 8/3/2019 Lectures Section 3 Modified

    68/73

    Compiler for VM (difficult/expensive to create) isonly written once and is, in a sense, portable.

    Added-to by set of intermediate code interpreters,one for each processor design

    These are relatively straightforward to write and runefficiently.

    A form of portability has been created, saving costs.

    More use if a number of different high-level

    languages all compile into the intermediate code. All of the languages on a single machine can then

    use the same intermediate code interpreter.

    I di d i i ll d P d

  • 8/3/2019 Lectures Section 3 Modified

    69/73

    Intermediate code is sometimes called P-code

    stands for pseudo (false) code

    dangerous name since pseudo code hasanother meaning for program designers.

    Early language that used this idea was Pascal

    intermediate language actually named P-code! Pascal could run on a big variety of computers.

    Final amusing step - was so successful that a

    processor was designed (Pascal MicroEngine)that actually had P-code as its real low-levellanguage!

  • 8/3/2019 Lectures Section 3 Modified

    70/73

    A more immediate example isbytecode which is the intermediatecode that Java is compiled into.

    It then runs on the Java VirtualMachine (JVM).

    /**

  • 8/3/2019 Lectures Section 3 Modified

    71/73

    /* @author Lisa Payne* @version Jan 2007*/

    public class Rectangle

    {private double width;private double height;public Rectangle(double w, double h){

    width = w;height = h;

    }public double getArea(){

    return width * height;}

    public void printArea(){

    System.out.println("Rectangle area is: " + this.getArea() );}

    }

    Fi l h h 1

  • 8/3/2019 Lectures Section 3 Modified

    72/73

    Final thoughts - 1

    What exactly is a program? When we look at a program written in high-level

    language we are really only looking at text whichcan be compiled into runnable low-level code.

    Some purists therefore only refer to low-levellanguage code as program since only this can

    be run on a computer.

    When we edit high-level programs we are onlymodifying the text with something like a wordprocessor.

  • 8/3/2019 Lectures Section 3 Modified

    73/73

    Final thoughts - 2

    A compiler is itself a program and a quitecomplicated one.

    We would therefore rather like to write it in

    a high-level language.

    It would then need to be compiled by acompiler which is itself a program written

    in a high-level language and compiled by acompiler which