CS 61C: Great Ideas in Computer Architecture Lecture 2 ...cs61c/fa17/lec/02/02 NumRep, C...
Transcript of CS 61C: Great Ideas in Computer Architecture Lecture 2 ...cs61c/fa17/lec/02/02 NumRep, C...
CS61C:GreatIdeasinComputerArchitecture
Lecture2:Numbers&CLanguage
KrsteAsanović &RandyKatz
http://inst.eecs.berkeley.edu/~cs61c
Agenda• Numberswrap-up• Thisisnotontheexam!• Break• CPrimer• Administrivia,Break• CTypedeclarations• AndinConclusion,…CS61c Lecture2:CProgrammingLanguage 2
Recap:BinaryNumberConversion
Binaryà Decimal
1001010two = ?ten
Decimalà Binary
74ten = ?two
9/6/17 3Fall2017 - Lecture#1
BinaryDigit
DecimalValue
0 0 x 20 = 0
1 1 x 21 = 2
0 0 x 22 = 0
1 1 x 23 = 8
0 0 x 24 = 0
0 0 x 25 = 0
1 1 x 26 = 64
S = 74ten
Decimal Binary(odd?)74 0
/2 = 37 1
/2 = 18 0
/2 = 9 1
/2 = 4 0
/2 = 2 0
/2 = 1 1
Collect à 1001010two
SignedIntegerRepresentationHowtorepresent-5?Sign&magnitude(8-bitexample):
Rulesforaddition,a+b:• If(a>0andb>0):addb toa• If(a>0andb<0):subtractb froma• …• +0,-0à aretheyequal?Ifso,comparatormusthandlespecialcase!(Ifnotequal???)
Cumbersome• ”Complicated”hardware:reducedspeed/increasedpower• Isthereabetterway?
9/6/17 4Fall2017 - Lecture#1
sign 7-bitmagnitude (0…127)
Goingbackwardsbygoingforwards• Howtoadd-1toafour-bitnumber?
9/6/17 5Fall2017 - Lecture#1
0111two = 7ten????two + = -1ten0110two = 6ten
Goingbackwardsbygoingforwards• Add10000two andthrowawayfifthbit,resultunchanged
– Resultwrapsaroundtosamevalue
9/6/17 6Fall2017 - Lecture#1
0111two = 7ten10000two + = 16ten10111two = 7ten+16ten0111two = 7ten
Goingbackwardsbygoingforwards• Add(10000two – 1two = 01111two)andthrowawayfifthbit– Onelessthanoriginalvalue
9/6/17 7Fall2017 - Lecture#1
0111two = 7ten01111two + = 16 - 1ten10110two = 16 + 6ten0110two = 6ten
4-bitExample
7+ -3
4
9/6/17 8
7+ -3 +16
4 +16
7+ 13
4 +16
0111+ 1101
10100 0100 +10000
Decimal Binary
• Mapnegativeà positivenumbers§ ExampleforN=4-bit:-3à 24– 3=13§ “Two’scomplement”§ Nospecialrulesforaddingpositiveandnegativenumbers
-8 -7 … -1 0 1 … 70 1 … 7 8 9 … 15
+24 =16
Extrabitisignoredasdoesn’tfitin4bits.
Two’sComplement(8-bitexample)
9/6/17 9Fall2017 - Lecture#1
AsSignedDecimal AsUnsignedDecimal
BinaryNumber
-128 128 1 0 0 0 0 0 0 0-127 129 1 0 0 0 0 0 0 1… … …-2 254 1 1 1 1 1 1 1 0-1 255 1 1 1 1 1 1 1 10 0 0 0 0 0 0 0 0 01 1 0 0 0 0 0 0 0 1… … . . .127 127 0 1 1 1 1 1 1 1
Most-significantbit(MSB)equalssignwheninterpretedasasignednumber
+256
+0
SignedversusUnsignedBinaryNumbers
• Botharestoredasacollectionofbits• Thesamesetofbitscanbeusedtorepresentasignednumberoranunsignednumber(orastring,orapicture,ora….)
• It’suptotheoperationinterpretingthebits
9/6/17 10Fall2017 - Lecture#1
1101two =+13ten (asanunsignednumber)1101two =-3ten(asasignednumber)1101two =orange(asacolor)1101two =cat(asatypeofanimal)1101two =whateveryouwantittomean…
UnaryNegation(Two’sComplement)4-bitExample(-8ten …+7ten)
BruteForce&Tedious Clever&Elegant
16ten 10000two- 3ten - 0011two13ten 1101two
16ten 10000two- 13ten - 1101two
3ten 0011two
”largest”4-bitnumber+1
9/6/17 Fall2017 - Lecture#1 11
15ten 01111two- 3ten - 0011two12ten 1100two invert
+1ten +0001two13ten 1101two
YourTurn
• Whatisthedecimalvalueofthefollowingbinary8-bit2’scomplementnumber?
11100001two
9/6/17 12Fall2017 - Lecture#1
Answer ValueRED 33ten
ORANGE -31tenGREEN 225tenYELLOW -33ten
Addition4-bitExample
Unsigned Signed(Two’sComplement)
9/6/17 13Fall2017 - Lecture#1
3ten 0011two+4ten +0100two
7ten 0111two
3ten 0011two+11ten +1011two
14ten 1110two
3ten 0011two+4ten +0100two
7ten 0111two
3ten 0011two+-5ten +1011two
-2ten 1110two
Nospecialrulesfortwo’scomplementsignedaddition
Overflow4-bitExample
Unsignedaddition Signedaddition(Two’sComplement)
9/6/17 14Fall2017 - Lecture#1
13ten 1101two+14ten +1110two
27ten 1 1011two
7ten 0111two+1ten +0001two
8ten 0 1000two
-3ten 1101two+-2ten +1110two
-5ten 1 1011two
7ten 0111two+1ten +0001two-8ten 01000two
Carry-outà Overflow Carry-outà Overflow
carry-outbutnooverflowcarry-outandoverflow
nocarry-outbutoverflownocarry-outandnooverflow
AdditionOverflowDetection4-bitExample
Unsignedaddition• Carry-outindicatesoverflow
Signedaddition(Two’sComplement)• Overflowif
– SignsofoperandsareequalAND
– Signofresultdiffersfromsignofoperands
• Nooverflowispossiblewhensignsofoperandsdiffer
9/6/17 15Fall2017 - Lecture#1
Overflowrulesdependontheoperation(signedvs unsignedaddition)
AddingNumbersofDifferentBitWidths
• Whatshouldweassumeforupperfourbitsoffirstoperand?• Treataszeros!• “Zero-extension”
9/6/17 16Fall2017 - Lecture#1
1101 (4-bit,13ten)10100101 + (8-bit,165ten)????0010 (8-bit,???ten)
Unsignedaddition
00001101 (4-bit,13ten)10100101 + (8-bit,165ten)10110010 (8-bit,178ten)
Zero extension
AddingSignedNumbersofDifferentBitWidths
• Whatshouldweassumeforupperfourbitsoffirstoperand?• Copysignbit(MSB)ofoperandintoupperbits– Ifsignis1,copy1s,ifsignis0copy0s
• “Sign-extension”
9/6/17 17Fall2017 - Lecture#1
1101 (4-bit,-3ten)10100101 + (8-bit,-91ten)????0010 (8-bit,???ten)
Signedaddition
11111101 (4-bit,-3ten)10100101 + (8-bit,-91ten)10100010 (8-bit,-94ten)
SignextensionSignbit
SignExtensionDecimal Binary
4-bit 8-bit 32-bit3ten 0011two 00000011two 0000000000000011two-3ten 1101two 11111101two 1111111111111101two
9/6/17 18Fall2017 - Lecture#1
• Whenisthisrelevant?• Anytimeyouneedawiderversionofanarroweroperand
e.g.,addingtwointegersofdifferentwidths
YourTurn
• Whichrangeofdecimalscanbeexpressedwitha6-bittwo’scomplementnumber?
9/6/17 19Fall2017 - Lecture#1
Answer RangeRED -32…32
GREEN -64…63ORANGE -31…32YELLOW -32…31
Agenda
• Numberswrap-up• Thisisnotontheexam!• Break• CPrimer• Administrivia,Break• CTypedeclarations• AndinConclusion,…
CS61c Lecture2:CProgrammingLanguage 20
HotChips 2017:Brains&Dinosaurs• Topconferenceintroducingnewprocessorchips
CS61c
Lecture2:CProgrammingLanguage
21
CS61c
Lecture2:CProgrammingLanguage
22
Z14,IBMMainframe,50+yearson
CS61c
Lecture2:CProgrammingLanguage
23
CS61c
Lecture2:CProgrammingLanguage
24
Break!
9/6/17 25Fall2017 - Lecture#2
Agenda• Numberswrap-up• Thisisnotontheexam!• Break• CPrimer• Administrivia,Break• CTypedeclarations• AndinConclusion,…CS61c Lecture2:CProgrammingLanguage 26
LevelsofRepresentation
lw t0,0(s2)lw t1,4(s2)sw t1,0(s2)sw t0,4(s2)
HighLevelLanguageProgram(e.g.,C)
AssemblyLanguageProgram(e.g.,RISC-V)
MachineLanguageProgram(RISC-V)
HardwareArchitectureDescription(e.g.,blockdiagrams)
Compiler
Assembler
MachineInterpretation
temp=v[k];v[k]=v[k+1];v[k+1]=temp;
0000 1001 1100 0110 1010 1111 0101 10001010 1111 0101 1000 0000 1001 1100 0110 1100 0110 1010 1111 0101 1000 0000 1001 0101 1000 0000 1001 1100 0110 1010 1111
LogicCircuitDescription(CircuitSchematicDiagrams)
ArchitectureImplementation
Anythingcanberepresentedasanumber,
i.e.,dataorinstructions
27
CurrentFocus
IntroductiontoC“TheUniversalAssemblyLanguage”
• Languagesusedin61C:• C• Assembly• Pythonusedintwolabs
• Priorprogrammingexperiencehelpful,e.g.• Java• C++
28CS61c Lecture2:CProgrammingLanguage
Survey
WhohasneverwrittenaprograminJavaor
C,C++,Objective-C?
CS61c Lecture2:CProgrammingLanguage 29
HelloWorldC
Java
CS61c Lecture2:CProgrammingLanguage 30
Compilation&Running$ gcc HelloWorld.c$ ./a.outHello World!$
CS61c Lecture2:CProgrammingLanguage 31
CCompilationSimplifiedOverview(morelaterincourse)
32
foo.c bar.c
Compiler Compiler
foo.o bar.o
Linker lib.o
a.out
Csourcefiles(text)
Machinecodeobjectfiles
Pre-builtobjectfilelibraries
Machinecodeexecutablefile
Compiler/assemblercombinedhere
CS61c Lecture2:CProgrammingLanguage
CompilationversusInterpretationC(compiled)
• Compiler(&linker)translatessourceintomachinelanguage• MachinelanguageprogramisloadedbyOSanddirectlyexecutedbythehardware
Python(interpreted)
• Interpreteriswritteninsomehigh-levellanguage(e.g.C)andtranslatedintomachinelanguage• LoadedbyOSanddirectlyexecutedbyprocessor• Interpreterreadssourcecode(e.g.Python)and“interprets”it
CS61c Lecture2:CProgrammingLanguage 33
Java“ByteCode”• Javacompiler(javac)translatessourceto“bytecode”• “Bytecode”isaparticularassemblylanguage
- Justlikei86,RISC-V,ARM,…- Canbedirectlyexecutedbyappropriatemachine
§ implementationsexist(ed),notcommerciallysuccessful- Moretypically,“bytecode”is
§ interpretedontargetmachine(e.g.i86)byjavaprogram§ compiledtotargetmachinecode(e.g.byJIT)
- Programrunsonanycomputerwitha“bytecode”interpreter(moreorless)
CS61c Lecture2:CProgrammingLanguage 34
Compilation• Excellentrun-timeperformance:
- Muchfasterthaninterpretedcode(e.g.Python)- UsuallyfasterthanJava(evenwithJIT)
• Note:Computersonlyrunmachinecode- Compiledapplicationprogram,or- Interpreter(thatinterpretssourcecode)
35CS61c Lecture2:CProgrammingLanguage
Compilation:Disadvantages• Compiledfiles,includingtheexecutable,are
- architecture-specific,dependingonprocessortype§ e.g.,RISC-Vvs.ARM
- andtheoperatingsystem§ e.g.,Windowsvs.Linux
• Executablemustberebuiltoneachnewsystem- I.e.,“portingyourcode”toanewarchitecture
• “Change® Compile® Run[repeat]”iterationcyclecanbeslowduringdevelopment- Recompileonlypartsofprogramthathavechanged- Tools(e.g.make)automatethis
36CS61c Lecture2:CProgrammingLanguage
CDialects$ gcc x.c
$ gcc –ansi –Wpedantic x.c
CS61c Lecture2:CProgrammingLanguage 37
CPre-Processor(CPP)
• Csourcefilespassthroughmacroprocessor,CPP,beforecompilation• CPPreplacescommentswithasinglespace• CPPcommandsbeginwith“#”• #include “file.h” /* Inserts file.h */• #include <stdio.h> /* Loads from standard loc */• #define M_PI (3.14159) /* Define constant */• #if/#endif /* Conditional inclusion of text */• Use–save-tempsoptiontogcc toseeresultofpreprocessing• Fulldocumentationat:http://gcc.gnu.org/onlinedocs/cpp/
38
foo.c CPP foo.i Compiler
CS61c Lecture2:CProgrammingLanguage
Agenda• Numberswrap-up• Thisisnotontheexam!• Break• CPrimer• Administrivia,Break• CTypedeclarations• AndinConclusion,…CS61c Lecture2:CProgrammingLanguage 39
Administratrivia• Notifyusofallknownvariances
- DSPspecialaccommodations:EmailheadTA(StevenHo)- Examconflicts:FillouttheformonPiazza(specialaccommodationscanbemadeonlyinexceptionalcases)
- Ifyoucannotgetaninstructionalaccount,emailheadTA
•NotifyheadTAbyTuesday,9/5/2017- seehttp://www-inst.eecs.berkeley.edu/~cs61c/fa17/
CS61c Lecture2:CProgrammingLanguage 40
Break!
9/6/17 41Fall2017 - Lecture#2
Agenda• Numberswrap-up• Thisisnotontheexam!• Break• CPrimer• Administrivia,Break• CTypedeclarations• AndinConclusion,…CS61c Lecture2:CProgrammingLanguage 42
TypedVariablesinCint a = 4;float f = 1.38e7;char c = ‘x’;
CS61c Lecture2:CProgrammingLanguage 43
• Declarebeforeuse• Typecannotchange• LikeJava
Type Description Examplesint integers,positiveornegative 0,82,-77,0xAB87unsignedint ditto, nonegatives 0,8, 37float (single precision)floatingpoint 3.2,-7.9e-10char textcharacterorsymbol ’x’,‘F’,‘?’double highprecision/range float 1.3e100long integerwithmorebits 427943
ConstantsandEnummerations inC• Constants
- Assignedintypeddeclaration,cannotchange- E.g.
§ const float pi = 3.1415;§ const unsigned long addr = 0xaf460;
• Enumerations
44
Integers:Pythonvs.Javavs.C
• C:int- integertypethattargetprocessorworkswithmostefficiently
• Onlyguarantee:- sizeof(longlong)≥sizeof(long)≥sizeof(int)≥sizeof(short)- Also,short >=16bits,long >=32bits- Allcouldbe64bits
• Impactsportabilitybetweenarchitectures45
Language sizeof(int)Python >=32bits(plainints),infinite (longints)Java 32bitsC Dependsoncomputer;16 or32or64
CS61c Lecture2:CProgrammingLanguage
VariableSizes:MachineDependent!sizeof ... (bytes) char: 1short: 2int: 4unsigned int: 4long: 8long long: 8float: 4double: 8
46CS61c Lecture2:CProgrammingLanguage
Boolean• Noboolean datatypeinC
- Declareifyouwish:typedef int boolean;const boolean false = 0;const boolean true = 1;
• WhatevaluatestoFALSEinC?- 0(integer)- NULL(aspecialkindofpointer:moreonthislater)
• WhatevaluatestoTRUEinC?- Anythingthatisn’tfalseistrue- SimilartoPython:
only0’soremptysequencesarefalse,everythingelseistrue!CS61c Lecture2:CProgrammingLanguage 47
FunctionsinCint number_of_people() {
return 3;
}
void news() {
printf(”no news”);
}
int sum(int x, int y) {
return x + y;
}
CS61c Lecture2:CProgrammingLanguage 48
• LikeJava• Declarereturn&argumenttypes• void fornovaluereturned• FunctionsMUSTbedeclaredbeforetheyareused
UninitializedVariablesCode Output
$ gcc test.c
$ ./a.outx = 0x = 16807x = -4x = 282475249x = -16
49CS61c Lecture2:CProgrammingLanguage
Struct’s inC• Struct’s arestructuredgroupsofvariables• AbitlikeJavaclasses,butnomethods• E.g.
50CS61c Lecture2:CProgrammingLanguage
MoreC…• LecturedoesnotcoverCcompletely
- You’llstillneedyourCreferenceforthiscourse- K&R,TheCProgrammingLanguage- &otherreferencesonthecoursewebsite
• Nextfewlectures’focus:- Pointers &Arrays- Memorymanagement
CS61c Lecture2:CProgrammingLanguage 51
AndInConclusion,…• Signedintegersrepresentedin2’scomplement• CProgrammingLanguage
- Popular(still!)- SimilartoJava,but
§ noclasses§ explicitpointers(nextlecture)
- Beware§ variablesnotinitialized§ variablesize(#ofbits)ismachine&compilerdependent
• Ciscompiledtomachinecode- UnlikePythonorJava,whichareinterpreted- Compilationisfasterthaninterpretation
52CS61c Lecture2:CProgrammingLanguage