Computer Organization 33

41
CS 33: Computer Organization Some notes adopted from Bryant and O’Hallaron Glenn Reinman 4731G Boelter Hall [email protected]

description

programmers perspective

Transcript of Computer Organization 33

  • CS33:

    Computer Organization

    SomenotesadoptedfromBryantandOHallaron

    GlennReinman4731GBoelter Hall

    [email protected]

  • Course Components Lectures

    Higherlevelconcepts

    Discussions Appliedconcepts,importanttoolsandskillsforlabs,clarificationoflectures,examcoverage

    Labs Theheartofthecourse Provideindepthunderstandingofanaspectofsystems Programmingandmeasurement

  • More Info Web

    ClasswebpagehostedbyCourseWeb Copiesoflectures,assignments,exams,solutions Forum

    OfficeHours Textbook

    RandalE.BryantandDavidR.OHallaron.ComputerSystems:AProgrammersPerspective,2nd Edition,PrenticeHall2010.

  • Grading Exams(45%)

    Twoinclassexams(15%each) Final(15%) Allexamsareopenbook/opennotes.

    Labs(50%) 5labs(10%each) Youmustworkaloneonalllabs

    Homework(5%) 5assignments(1%each) Electronicsubmissiononly

  • Week M T W R F

    1 Intro+BitsandBytes(1,2) Integers(2)

    2 MachineLevelRep(3) MachineLevelRep(3) DataLabDue

    3 HW#1Due MachineLevelRep(3) MachineLevelRep(3)

    4 HW#2Due MachineLevelRep(3) Exam#1 BombLabDue

    5 HW#3Due FloatingPoint(2) CodeOptimization(5)

    6 Concurrency(12+handouts) Memory(6) BufferLabDue

    7 HW#4Due Concurrency(12+handouts) Exam#2

    8 Concurrency(12+handouts) I/O(10) OpenMP LabDue

    9 HW#5Due VirtualMemory(9) Linking+Exceptions(7,8)

    10 MIPS(handouts) Review CUDALabDue

    Tentative Calendar

    HomeworkandLabsDueviaCourseWeb byMidnight

  • Cheating Whatischeating?

    Sharingcode:eitherbycopying,retyping,lookingat,orsupplyingacopyofafile.

    WhatisNOTcheating? Helpingothersusesystemsortools. Helpingotherswithhighleveldesignissues. Helpingothersdebugtheircode.

    Penaltyforcheating: AtthediscretionoftheAssociateDean

  • Lab Facilities SEASAdministeredLinuxMachine

    lnxsrv.seas.ucla.edu

    Remoteaccessonly Usessh tologinwithyourSEASaccount

    PleasedirectanyaccountissuestotheSEAShelpdeskastheyaretheonlyoneswithrootaccessonthismachine

    Alternatives(NotRecommended) Youmayuseotheralternativestodevelopyourcode BUT:WewilltestontheSEASmachines

    Yourcodemustworkcorrectlyonthesemachinesforcredit

  • Course Theme Abstractionisgood,butdontforgetreality! Abstractionshavelimits

    ThingsaremorecomplexinhardwarethantheylookinC/Java!! Bugsarehardtotrack/understandiflookingonlyfromahighlevelpointofview

    Usefuloutcomes Becomemoreeffectiveprogrammers

    Abletofindandeliminatebugsefficiently Abletotuneprogramperformance

    PrepareforlatersystemsclassesinCS Compilers,OperatingSystems,Networks,ComputerArchitecture,ParallelProgramming

  • The Compilation System#includeint main(){printf(hello,world\n);

    }

    Pre-processor

    (cpp)hello.i Compiler

    (cc1)hello.s Assembler

    (as)hello.o Linker

    (ld)hellohello.c

    Sourceprogram

    (text)

    Modifiedsource

    program(text)

    Assemblyprogram

    (text)

    Relocatableobject

    programs(binary)

    Executableobject

    program(binary)

    printf.o

  • SomenotesadoptedfromBryantandOHallaron

    Bits and Bytes

    Chapter2ofB&O

  • Why Dont Computers Use Base 10? Base10NumberRepresentation

    Thatswhyfingersareknownasdigits Naturalrepresentationforfinancialtransactions

    Floatingpointnumbercannotexactlyrepresent$1.20

    Evencarriesthroughinscientificnotation 1.5213X104

    ImplementingElectronically Hardtostore

    ENIAC(Firstelectroniccomputer)used10vacuumtubes/digit

    Hardtotransmit Needhighprecisiontoencode10signallevelsonsinglewire

    Messytoimplementdigitallogicfunctions Addition,multiplication,etc.

  • Binary Representations Base2NumberRepresentation

    Represent1521310 as111011011011012 Thats1x20+0x21 +1x22 +1x23 +0x24 +

    ElectronicImplementation Easytostorewithbistable elements Reliablytransmittedonnoisyandinaccuratewires

    0.0V

    0.5V

    2.8V

    3.3V

    0 1 0

  • Byte-Oriented Memory Organization ProgramsRefertoVirtualAddresses

    Conceptuallyverylargearrayofbytes Actuallyimplementedwithhierarchyofdifferentmemorytypes Systemprovidesaddressspaceprivatetoparticularprocess

    Programbeingexecuted Programcanclobberitsowndata,butnotthatofothers

    Compiler+RunTimeSystemControlAllocation Wheredifferentprogramobjectsshouldbestored Inanycase,allallocationwithinsinglevirtualaddressspace

  • Encoding Byte Values Byte=8bits

    Binary 000000002 to 111111112 Decimal: 010 to 25510 Hexadecimal 0016 to FF16

    Base16numberrepresentation Usecharacters0to9andAtoF WriteFA1D37B16 inCas0xFA1D37B

    Or0xfa1d37b

    0 0 00001 1 00012 2 00103 3 00114 4 01005 5 01016 6 01107 7 01118 8 10009 9 1001A 10 1010B 11 1011C 12 1100D 13 1101E 14 1110F 15 1111

  • Machine Words MachineHasWordSize

    Nominalsizeofintegervalueddata Includingaddresses

    32bitSystems(4bytes) Limitsaddressesto4GB Becomingtoosmallformemoryintensiveapplications

    64bitSystems(8bytes) Potentiallyaddress 1.8X1019 bytes x8664machinessupport48bitaddresses:256Terabytes

    Machinessupportmultipledataformats Fractionsormultiplesofwordsize Alwaysintegralnumberofbytes

  • Word-Oriented Memory Organization

    Wordsarechunksofbits AddressesSpecifyByteLocations Addressoffirstbyteinword

    Addressesofsuccessivewordsdifferby4(32bit)or8(64bit)

    000000010002000300040005000600070008000900100011

    32-bitWords

    Bytes Addr.

    0012001300140015

    64-bitWords

    Addr =??

    Addr =??

    Addr =??

    Addr =??

    Addr =??

    Addr =??

    0000

    0004

    0008

    0012

    0000

    0008

  • Data Representations SizesofCObjects(inBytes)

    CDataType Typical32bit IA32 x8664 char 1 1 1 short 2 2 2 int 4 4 4 long 4 4 8 longlong 8 8 8 float 4 4 4 double 8 8 8 longdouble 8 10/12 10/16 char* 4 4 8

    Oranyotherpointer

    #include int main() {

    printf ("%lu %lu %lu\n", sizeof(int), sizeof(long), sizeof(char*));}

  • Byte Ordering Howshouldbyteswithinmultibytewordbeorderedinmemory?

    Conventions OlderSuns,PowerPCsareBigEndianmachines

    Leastsignificantbytehashighestaddress

    x86sareLittleEndianmachines Leastsignificantbytehaslowestaddress

    SPARCV9,MIPS,AlphaareBiEndianmachines CanappeartobeconfigurableasBigorLittleEndian

    Internalsmaystillbeonewayortheotherthough

  • Byte Ordering Example BigEndian(naturallanguage,M68k,IBMPower)

    Leastsignificantbytehashighestaddress decreasesignificancewithincreasingaddress

    LittleEndian(arithmeticlanguage,x86) Leastsignificantbytehaslowestaddress increasesignificancewithincreasingaddress

    Example Variablex has4byterepresentation0x01234567 Addressgivenby&x is0x100

    0x100 0x101 0x102 0x10301 23 45 67

    0x100 0x101 0x102 0x10367 45 23 01

    Big Endian

    Little Endian

    01 23 45 67

    67 45 23 01

  • Reading Byte-Reversed Listings Disassembly

    Textrepresentationofbinarymachinecode Generatedbyprogramthatreadsthemachinecode

    ExampleFragmentAddress Instruction Code Assembly Rendition8048365: 5b pop %ebx8048366: 81 c3 ab 12 00 00 add $0x12ab,%ebx804836c: 83 bb 28 00 00 00 00 cmpl $0x0,0x28(%ebx)

    DecipheringNumbers Value: 0x12ab Padto4bytes: 0x000012ab Splitintobytes: 00 00 12 ab Reverse: ab 12 00 00

  • Examining Data Representations CodetoPrintByteRepresentationofData

    Castingpointertounsignedchar*createsbytearray

    typedef unsigned char* pointer;void show_bytes(pointer start, int len){int i;for (i = 0; i < len; i++)printf("0x%p\t0x%.2x\n",

    start+i, start[i]);printf("\n");

    }

    Printf directives:%p: Print pointer%x: Print Hexadecimal

  • show_bytes Execution Example

    int a = 15213;printf("int a = 15213;\n");show_bytes((pointer) &a, sizeof(int));

    Result (Linux):int a = 15213;0x11ffffcb8 0x6d0x11ffffcb9 0x3b0x11ffffcba 0x000x11ffffcbb 0x00

  • Representing Integers int A = 15213; int B = -15213; long int C = 15213;

    Decimal: 15213Binary: 0011 1011 0110 1101Hex: 3 B 6 D

    6D3B0000

    Linux/x86-64 A

    3B6D

    0000

    Sun A

    93C4FFFF

    Linux/x86-64 B

    C493

    FFFF

    Sun B

    Twos complement representation(Covered next lecture)

    00000000

    6D3B0000

    x86-64 C

    3B6D

    0000

    Sun C6D3B0000

    Linux C

  • Representing Pointers int B = -15213; int *P = &B;

    01000000

    A0FCFFFF

    x86-64 P

    Different compilers & machines assign different locations to objects

    FB2C

    EFFF

    Sun P

    FFBF

    D4F8

    IA32 P

  • Representing Floats Float F = 15213.0;

    IEEE Single Precision Floating Point RepresentationHex: 4 6 6 D B 4 0 0 Binary: 0100 0110 0110 1101 1011 0100 0000 000015213: 1110 1101 1011 01

    Not same as integer representation, but consistent across machines

    00B46D46

    IA32/x86-64 F

    B400

    466D

    Sun F

    Can see some relation to integer representation, but not obvious

    IEEE Single Precision Floating Point RepresentationHex: 4 6 6 D B 4 0 0 Binary: 0100 0110 0110 1101 1011 0100 0000 000015213: 1110 1101 1011 01

    IEEE Single Precision Floating Point RepresentationHex: 4 6 6 D B 4 0 0 Binary: 0100 0110 0110 1101 1011 0100 0000 000015213: 1110 1101 1011 01

  • char S[6] = "15213";

    Representing Strings StringsinC

    Representedbyarrayofcharacters EachcharacterencodedinASCIIformat

    Standard7bitencodingofcharacterset Otherencodingsexist,butuncommon Character0hascode0x30

    Digitihascode0x30+i

    Stringshouldbenullterminated Finalcharacter=0

    Compatibility Byteorderingnotanissue

    Dataaresinglebytequantities

    Textfilesgenerallyplatformindependent Exceptfordifferentconventionsoflineterminationcharacter(s)!

    IA32/x86-64 S Sun S

    3231

    3135

    3300

    3231

    3135

    3300

  • Machine-Level Code Representation EncodeProgramasSequenceofInstructions

    Eachsimpleoperation Arithmeticoperation Readorwritememory Conditionalbranch

    Instructionsencodedasbytes Alphas,Suns,Macsuse4byteinstructions

    ReducedInstructionSetComputer(RISC) PCsusevariablelengthinstructions

    ComplexInstructionSetComputer(CISC)

    Differentinstructiontypesandencodingsfordifferentmachines Mostcodenotbinarycompatible

    ProgramsareByteSequencesToo!

  • Representing Instructionsint sum(int x, int y){

    return x+y;}

    Different machines use totally different instructions and encodings

    00003042

    Alpha sum

    0180FA6B

    E008

    81C3

    Sun sum

    90020009

    Forthisexample,Alpha&Sunusetwo4byteinstructions Usedifferingnumbersofinstructionsinothercases

    PCuses7instructionswithlengths1,2,and3bytes

    E58B

    5589

    PC sum

    450C03450889EC5DC3

  • Boolean Algebra DevelopedbyGeorgeBoolein19thCentury

    Algebraicrepresentationoflogic EncodeTrueas1andFalseas0

    And A&B=1whenbothA=1andB=1

    & 0 10 0 01 0 1

    ~0 11 0

    Not ~A=1whenA=0

    Or A|B=1wheneitherA=1orB=1

    | 0 10 0 11 1 1

    ^ 0 10 0 11 1 0

    ExclusiveOr(Xor) A^B=1wheneitherA=1orB=1,

    butnotboth

  • General Boolean Algebras OperateonBitVectors

    Operationsappliedbitwise01101001

    & 0101010101000001

    01101001| 01010101

    0111110101101001

    ^ 0101010100111100

    ~ 010101011010101001000001 01111101 00111100 10101010

  • Bit-Level Operations in C Operations&,|,~,^AvailableinC

    Applytoanyintegraldatatype long,int,short,char,unsigned

    Viewargumentsasbitvectors Argumentsappliedbitwise

    Examples(Chardatatype) ~0x41>0xBE

    ~010000012 > 101111102 ~0x00>0xFF

    ~000000002 > 111111112 0x69&0x55>0x41

    011010012 &010101012 >010000012 0x69|0x55>0x7D

    011010012 |010101012 >011111012

  • Contrast: Logic Operations in C ContrasttoLogicalOperators

    &&,||,! View0asFalse AnythingnonzeroasTrue Alwaysreturn0or1 Earlytermination

    Examples(chardatatype) !0x41>0x00 !0x00>0x01 !!0x41>0x01

    0x69&&0x55>0x01 0x69||0x55>0x01 p&&*p (avoidsnullpointeraccess)

  • Shift Operations LeftShift: xy Shiftbitvectorxrightypositions

    Throwawayextrabitsonright

    Logicalshift Fillwith0sonleft

    Arithmeticshift Replicatemostsignificantbitonright Usefulwithtwoscomplementintegerrepresentation

    UndefinedBehavior Shiftamount 200011000Arith. >> 2

    10100010Argument x00010000> 211101000Arith. >> 2

    000100000001000000011000000110000001100000011000

    000100000010100011101000

    000100000010100011101000

  • Cool Stuff with Xor

    void funny(int *x, int *y){

    *x = *x ^ *y; /* #1 */*y = *x ^ *y; /* #2 */*x = *x ^ *y; /* #3 */

    }

    BitwiseXorisformofaddition

    WithextrapropertythateveryvalueisitsownadditiveinverseA^A=0

    BABeginBA^B1

    (A^B)^B = AA^B2A(A^B)^A = B3ABEnd

    *y*x

  • Representing & Manipulating Sets Representation

    Widthwbitvectorrepresentssubsetsof{0,,w1} aj =1ifj A

    01101001 {0,3,5,6}76543210

    01010101 {0,2,4,6}76543210

    Operations & Intersection 01000001 {0,6} | Union 01111101 {0,2,3,4,5,6} ^ Symmetricdifference 00111100 {2,3,4,5} ~ Complement 10101010 {1,3,5,7}

  • replaceByte/**replaceByte(x,n,c) Replacebyteninxwithc*Bytesnumberedfrom0(LSB)to3(MSB)*Examples:replaceByte(0x12345678,1,0xab)=0x1234ab78*Youcanassume0
  • replaceByte/**replaceByte(x,n,c) Replacebyteninxwithc*Bytesnumberedfrom0(LSB)to3(MSB)*Examples:replaceByte(0x12345678,1,0xab)=0x1234ab78*Youcanassume0
  • Boolean Algebra Integer Ring Commutativity

    A|B=B|A A+B=B+AA&B=B&A A*B=B*A

    Associativity(A|B)|C=A|(B|C) (A+B)+C=A+(B+C)(A&B)&C=A&(B&C) (A*B)*C=A*(B*C)

    ProductdistributesoversumA&(B|C)=(A&B)|(A&C) A*(B+C)=A*B+B*C

    SumandproductidentitiesA|0=A A+0=AA&1=A A*1=A

    ZeroisproductannihilatorA&0=0 A*0=0

    Cancellationofnegation~(~A)=A ( A)=A

  • Boolean Algebra Integer Ring Boolean:Sumdistributesoverproduct

    A|(B&C)=(A|B)&(A|C) A+(B*C) (A+B)*(B+C) Boolean:Idempotency

    A|A=A A+A AAistrueorAistrue=Aistrue

    A&A=A A*A A Boolean:Absorption

    A|(A&B)=A A+(A*B) AAistrueorAistrueandBistrue=Aistrue

    A&(A|B)=A A*(A+B) A Boolean:LawsofComplements

    A|~A=1 A+A 1 AistrueorAisfalse

    Ring:EveryelementhasadditiveinverseA|~A 0 A+A=0

  • Relations Between Operations DeMorgansLaws

    Express&intermsof|,andviceversa A&B=~(~A|~B)

    AandBaretrueifandonlyifneitherAnorBisfalse

    A|B=~(~A&~B) AorBaretrueifandonlyifAandBarenotbothfalse

    ExclusiveOrusingInclusiveOr A^B=(~A&B)|(A&~B)

    ExactlyoneofAandBistrue

    A^B=(A|B)&~(A&B) EitherAistrue,orBistrue,butnotboth

  • Main Points ItsAllAboutBits&Bytes

    Numbers Programs Text

    DifferentMachinesFollowDifferentConventions Wordsize Byteordering Representations

    BooleanAlgebraisMathematicalBasis Basicformencodesfalseas0,trueas1 GeneralformlikebitleveloperationsinC

    Goodforrepresenting&manipulatingsets