Presentation is loading. Please wait.

Presentation is loading. Please wait.

Instructor Eric Chang Greet class… SLOOOOOOOOOOWWW DOOOOOWNNNNN

Similar presentations


Presentation on theme: "Instructor Eric Chang Greet class… SLOOOOOOOOOOWWW DOOOOOWNNNNN"— Presentation transcript:

1 inst.eecs.berkeley.edu/~cs61c CS61C : Machine Structures Lecture 15 – Review 2010-07-15
Instructor Eric Chang Greet class… SLOOOOOOOOOOWWW DOOOOOWNNNNN Got feedback slow down Remind about website Complaint about temp, possible move

2 Numbers: positional notation
Number Base B  B symbols per digit: Base 10 (Decimal): 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 Base 2 (Binary): 0, 1 Number representation: d31d d1d0 is a 32 digit number value = d31  B31 + d30  B d1  B1 + d0  B0 Binary: 0,1 (In binary digits called “bits”) 0b = 124 + 123 + 0 21 + 020 = = 26 Here 5 digit binary # turns into a 2 digit decimal # Can we find a base that converts to binary easily? Yes! Hexadecimal and Octal. #s often written 0b…

3 Integer representation schemes
Unsigned – ignore negative numbers. Sign and Magnitude – most significant bit denotes sign; 0 is positive, 1 is negative. One’s Complement – Flip all the bits to denote negative number. 0 in the most significant bit denotes positive number (not useful, why?) Two’s Complement – One’s complement then add 1 (standard representation). Bias – Pick a bias, and interpret numbers as unsigned numbers subtracted by the bias (used in floating point exponent). Representation consideration: hardware implementation, odometer, duplicate representations for certain numbers?

4 Two’s Complement Formula
Can represent positive and negative numbers in terms of the bit value times a power of 2: d31 x -(231) + d30 x d2 x 22 + d1 x 21 + d0 x 20 Example: 1101two in a nibble? = 1x-(23) + 1x22 + 0x21 + 1x20 = = = = -3ten Example: -3 to +3 to -3 (again, in a nibble): x : 1101two x’: 0010two +1: 0011two ()’: 1100two +1: 1101two

5 C gives us couple operators to let us manipulate bit by bit.
Bit Manipulation C gives us couple operators to let us manipulate bit by bit. >>, <<, |, &, ^, ~, etc. Normally use a “mask” (a number with a 1 in a specific bit) to access (with &), set to 1 (with |), or flip (with ^) the specified bit of a number. x ^= 1<<5 will flip the 5th bit of x. Incidentally, multiplying, dividing, and modding by powers of 2 can be done more efficiently with bitwise operations.

6 Pointer: A variable that contains the address of a variable.
Pointers An address refers to a particular memory location. In other words, it points to a memory location. Pointer: A variable that contains the address of a variable. 23 42 ... x y Location (address) name p 104

7 How to create a pointer:
Pointers How to create a pointer: & operator: get address of a variable int x; int *p; p ? x Note the “*” gets used 2 different ways in this example. In the declaration to indicate that p is going to be a pointer, and in the printf to get the value pointed to by p. x = 3; p ? x 3 p =&x; p x 3 How get a value pointed to? * “dereference operator”: get value pointed to use on left side of = to assign value to address pointed to printf(“p points to %d\n”,*p);

8 Pointers and Parameter Passing
Java and C pass parameters “by value” procedure/function/method gets a copy of the parameter, so changing the copy cannot change the original If you need to modify parameter, pass an address (pointer). void addOne (int x) { x = x + 1; } int y = 3; addOne(y); y is still = 3 3 4 ... y x address name printf(“What is y? %d\n”, y);

9 Arrays Key Concept: An array variable is a fixed “pointer” to the first element. Differences: Cannot re-assign arrays. Sizeof(array) returns number of bytes total in the array, sizeof(pointer) returns number of bytes in address (4). Reason: sizeof is a function done by the compiler. Multidimensional arrays occupy consecutive blocks in memory, pointer of pointers can point to discrete blocks in memory (affects parameter passing). Coding Advice: only use arrays for temporary memory storage (memory you don’t need after function finish).

10 Declared arrays are only allocated while the scope is valid
Arrays (cont.) Consequences: arr is an array variable but looks like a pointer in many respects (though not all) arr[0] is the same as *arr arr[2] is the same as *(arr+2) In fact, you can also write 2[arr] We can use pointer arithmetic to access arrays more conveniently. Declared arrays are only allocated while the scope is valid int *foo() { int arr[32]; ...; return arr; } is incorrect

11 C Strings A string in C is just an array of characters (which always ends in \0). char str[] = "abc"; // 4 elements Use functions such as strlen, strncmp, strncpy in string.h to manipulate strings. Since strings are just an array of characters, use the same judgment as before to decide whether to store it in char[] or char *.

12 After dynamically allocating space, we must dynamically free it:
Malloc and Free To allocate room for something new to point to, use malloc() (with the help of a typecast and sizeof): ptr = (int *) malloc (n*sizeof(int)); This allocates an array of n integers. After dynamically allocating space, we must dynamically free it: free(ptr); Every malloc’d memory MUST be freed!

13 Check malloc’s return value!
malloc() can fail! Requested something too large Out of memory! Random OS Error If malloc fails, NULL is returned Every time you call malloc(), you MUST check it’s return value against NULL. NO EXCEPTIONS! Note: I said in my sections that assert() can be used for quick error checking. However, it is a very bad practice to not make a program gracefully exit when it should (who wants their game to crash all the time when you can fix it by using a simple malloc check?) assert() should be used ONLY during development and not in actual code (i.e. your exam).

14 C structures : Overview
A struct is a data structure composed from simpler data types. Usually, more efficient to pass a pointer to the struct. ptr->y is shorthand for (*ptr).y struct point { /* type definition */ int x; int y; }; void PrintPoint(struct point p) { printf(“(%d,%d)”, p.x, p.y); } struct point p1 = {0,10}; /* x=0, y=10 */ PrintPoint(p1); As always in C, the argument is passed by “value” – a copy is made.

15 Pointer Exercise a) 0 b) 1 c) 4 d) 16 e) No idea
typedef struct vector { int *array; int array_size; } vector_t; typedef struct grid { vector_t **rows; int rows_size; } grid_t; grid_t g; // codes not shown … If &g = 20 and g.rows[0]->array[0] = 1, what is the value of X?? a) 0 b) 1 c) 4 d) 16 e) No idea Address: 4 8 12 16 20 24 28 32 X 1

16 Answer Red: grid_t Blue: vector_t *rows Green: vector_t
typedef struct vector { int *array; int array_size; } vector_t; typedef struct grid { vector_t **rows; int rows_size; } grid_t; grid_t g; // codes not shown … If &g = 20 and g.rows[0]->array[0] = 1, what is the value of X?? Red: grid_t Blue: vector_t *rows Green: vector_t Purple: int *array a) 0 b) 1 c) 4 d) 16 e) No idea Address: 4 8 12 16 20 24 28 32 X 1

17 Normal C Memory Management
~ FFFF FFFFhex stack A program’s address space contains 4 regions: stack: local variables, grows downward heap: space requested for pointers via malloc() ; resizes dynamically, grows upward static data: variables declared outside main, does not grow or shrink code: loaded when program starts, does not change heap static data code ~ 0hex For now, OS somehow prevents accesses between stack and heap (gray hash lines). Wait for virtual memory

18 Last In, First Out (LIFO) data structure
Stack Last In, First Out (LIFO) data structure stack main () { a(0); } Stack grows down Stack Pointer Stack Pointer void a (int m) { b(1); } Stack Pointer void b (int n) { c(2); } Stack Pointer void c (int o) { d(3); } Stack Pointer void d (int p) { }

19 Heap Memory Management
For small amounts of memory request, generally use slab allocator/buddy system For larger amounts of memory, use a free list with one of the three following policy for traversal: First fit (return first block of free space found) Next fit (keep track of where we left off next time instead of starting over every time) Best fit (find the block that fits best). Also, automatic memory management exists for strongly typed languages (not C). Examples are Mark and Sweep and Garbage Collection.

20 MIPS Assembly Language
Deals primarily with typeless registers (instead of memory) to perform tasks. Regular instructions that manipulates registers (add, addiu, slt, lui, ori, etc.) sltiu $t0, $a0, 5 Instructions that manipulates memory (lw, sw). sw $t0 4($sp) Equivalent to dereferencing and modifying pointers. Instructions that control data flow (j, jr, beq). beq $t0 $t1 label

21 MIPS Signed vs. Unsigned – diff meanings!
MIPS terms Signed/Unsigned “overloaded”: Do/Don't sign extend (lb, lbu) Do/Don't overflow (add, addi, sub, mult, div) (addu, addiu, subu, multu, divu) Do signed/unsigned compare (slt, slti/sltu, sltiu)

22 MIPS Registers The constant 0 $0 $zero Reserved for Assembler $1 $at Return Values $2-$3 $v0-$v1 Arguments $4-$7 $a0-$a3 Temporary $8-$15 $t0-$t7 Saved $16-$23 $s0-$s7 More Temporary $24-$25 $t8-$t9 Used by Kernel $26-27 $k0-$k1 Global Pointer $28 $gp Stack Pointer $29 $sp Frame Pointer $30 $fp Return Address $31 $ra Except for save registers, $0, and stack pointer, all other registers are volatile (might change after function call) and must be SAVED!!!

23 MIPS Function Layout Prologue: FunctionFoo:
addiu $sp, $sp, -FrameSize #reserve space on #the stack sw $s0, 0($sp) #store needed #registers sw $s1, 4($sp) … save the rest of the registers … sw $ra, (Framesize – 4)($sp) Body: … Do some stuff … jal something Epilogue: lw $s0, 0($sp) #restore registers … load the rest of the registers… lw $s1, 4($sp) lw $ra, (Framesize – 4)($sp) addiu $sp, $sp, FrameSize #release stack #spaces jr $ra #return to normal execution

24 MIPS Exercise Translate the following to MIPS: void insertionSort(int *arr, int size){ int i, j; for(i=1; i<size; i++){ j=i; while(j>0 && arr[j]<arr[j-1]){ swap(arr + j, arr + (j-1)); j--; }

25 Instruction Format opcode rs rt immediate rd funct shamt R I J
target address For I-instruction, immediate is sign extended to 32 bits for HW simplicity. Some I-instructions suffers from sign extension, so assembler must recompile with lui/ori to compensate. Branch stores the different (PC-relative addressing) between the current address and the target address (divided by 4) in the immediate field. J-instruction borrow the upper 4 bits of PC and append them to the target address multiplied by 4.

26 Need to convert to TAL when:
MAL v.s. TAL Since it is usually quite hard to convert directly from MAL to binary format, we convert MAL to TAL first, then convert from TAL to binary. TAL is a subset of MAL Need to convert to TAL when: Using psuedo-instructions. Doesn’t fit into Immediate field. When converting to TAL, make sure to not change ANY registers besides $at!!!!

27 Floating Point Representation
Normalized format: +1.xxx…xtwo*2yyy…ytwo Multiple of Word Size (32 bits) 31 S Exponent 30 23 22 Significand 1 bit 8 bits 23 bits S represents Sign Exponent represents y’s Significand represents x’s Exponent Bias = 2^(E - 1) – 1 Denorm Imp. Exp. = - (Exp. Bias – 1) Why this representation? Nice ordering.

28 Problem: There’s a gap among representable FP numbers around 0
Denorms (1/2) Problem: There’s a gap among representable FP numbers around 0 Smallest representable pos num: a = 1.000…0 2 * = 2-126 Second smallest representable pos num: b = 1.000……1 2 * = ( …12) * = ( ) * = a - 0 = 2-126 b - a = 2-149 Normalization and implicit 1 is to blame! Wouldn’t it be cool if we had some extra bits to represent this? Gaps! b + - a

29 (-1)S x (0 . Significand) x 2(-De. Imp. Exp.)
Denorms (2/2) Solution: We still haven’t used Exponent=0, Significand nonzero Denormalized number: no (implied) leading 1, implicit exponent = -126 Smallest representable pos num: A = 2-149 Second smallest representable pos num: b = 2-148 (-1)S x (0 . Significand) x 2(-De. Imp. Exp.) + -

30 Special Numbers Summary
Reserve exponents, significands: Exponent Significand Object +/-0 nonzero Denorm 1-254 Anything +/- fl. Pt # 255 +/- ∞ NaN


Download ppt "Instructor Eric Chang Greet class… SLOOOOOOOOOOWWW DOOOOOWNNNNN"

Similar presentations


Ads by Google