1 / 60

ELE271 April 9, 2014 Motivation for HLL, C Variables Data Types Functions TI Functions

ELE271 April 9, 2014 Motivation for HLL, C Variables Data Types Functions TI Functions. Moving Up Levels of Abstraction. Problems. Algorithms. High Level Language (Java). High/Low Level Language (C). Machine (ISA) Architecture. Microarchitecture. Circuits. Devices.

esben
Download Presentation

ELE271 April 9, 2014 Motivation for HLL, C Variables Data Types Functions TI Functions

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. ELE271 • April 9, 2014 • Motivation for HLL, C • Variables • Data Types • Functions • TI Functions

  2. Moving Up Levels of Abstraction Problems Algorithms High Level Language (Java) High/Low Level Language (C) Machine (ISA) Architecture Microarchitecture Circuits Devices

  3. What Programmming Languages have you used?

  4. Other Languages: • Java – OOP, internet • C/C++ - general purpose, embedded. • Mathmatica – image processing • VHDL, Verilog, ABEL – Hardware Description Languages (HDL) • LISP, TCL - LISt Processing • Perl, Python, Ruby – text processing, report generation. • PROLOG - logic programming • MATLAB - matrix and vector manipulations • BASIC – interpreter for small computers • APL – matrix and vectors • FORTRAN – formula translation • COBOL – business and accounting • PASCAL – procedural • Ada – DOD large systems • ….

  5. High Level vs. Assembly

  6. High Level vs. Assembly More efficient code • High Level Languages • More programmer friendly. • More ISA independent • Each high-level statement translates to several instructions in the ISA of the computer (one-to-many) • Assembly Languages • Lower level, closer to ISA • Very ISA-dependent • Each instruction specifies a single ISA instruction (1-to-1) • Makes low level programming more user friendly

  7. The C Language The C Programming Language • A high-level programming language developed between 1969 and 1973 at Bell Labs by Dennis Ritchie. • C first developed for use in writing compilers and operating systems (UNIX). • A low-level high-level language . • Many variants of C • 1989, the American National Standards Institute standardized C (ANSI C, most commonly used C) • “The C Programming Language” by Kernighan and Ritchie is the C “Bible” (Also called the “White Book”.) • C is powerful and flexible and proven to be one of the most popular programming languages of all time – very few computer architectures exist (if any) for which there is no C. • C is predecessor to most of today’s procedural languages such as C++ and Java.

  8. Approaches to C • 1. Top Down – Computer Science • How can I use a programming language to solve real world problems? • 2. Bottom Up – Electrical Engineering • How can I use hardware to support abstract data types?

  9. Starting point: If I were to create a new programming language, where would I start? We will start with algebra. • “Algebra starts as the art of manipulating sums, products, and powers of numbers. • The rules for these manipulations hold for all numbers, so the manipulations may be carried out with letters standing for numbers. • It then appears that the same rules hold for various different sorts of numbers….and that the rules apply to things…which are not numbers at all.” We call these variables. Saunders Mac Lane and Garret Birkhoff (1967) Are there other approaches?

  10. What do mean by “Variable” in Computer Science? • Data placeholder • Pointer • Location • Memory location

  11. A variable is a named memory cell. Jimenez p.225, https://sites.google.com/site/usfcomputerscience/variables-are-memory-cells In computer programming, a variable or scalar is a storage location and an associated symbolic name (an identifier) which contains some known or unknown quantity or information, a value. The variable name is the usual way to reference the stored value; this separation of name and content allows the name to be used independently of the exact information it represents. The identifier in computer source code can be bound to a value during run time, and the value of the variable may thus change during the course of program execution. Variables in programming may not directly correspond to the concept of variables in mathematics. The value of a computing variable is not necessarily part of an equation or formula as in mathematics. In computing, a variable may be employed in a repetitive process — assigned a value in one place, then used elsewhere, then reassigned a new value and used again in the same way (see iteration). Variables in computer programming are frequently given long names to make them relatively descriptive of their use, whereas variables in mathematics often have terse, one- or two-character names for brevity in transcription and manipulation. http://en.wikipedia.org/wiki/Variable_(computer_science)

  12. Variables: named memory location in a Von Neumann machine. Review: What is a Von Neumann Architecture? One Memory for data And program. Chapter 3 - ISA

  13. Review: Assembler Sections A section is a block of code or data that occupies contiguous space in the memory map. Each section has its own Location Counter. The assembler assembles into the current section. C global vars initialized to zero. Assembler Sections • There are two types of sections: • Initialized sections containing data or code (modal) • .sect • .text • .cstring • Uninitialized sections reserving space in the memory map for uninitialized data (temporary) • .bss • .usect

  14. Example: match to correct memory segment A: .byte 41h myStr: .cstring"HELLO WORLD, I AM THE MSP430!". .bssramVar,MAXBYTES mov.b ramVar,0(myStr)

  15. Given: z = K + y. (assume integer values) Where do I store these variables? Assembly C constintK=2; K: .byte 02h ; write to flash int x=2; .bss x,2 mov.w #2,&x ; write to flash and copy to RAM int x=2; mov.w #2,0(SP) ;write to flash and copy to stack

  16. High Level Languages Other benefits of HLL’s • numberOfDays = 30; • myCurrentPayPerHour = 10.75; • switch_A = ON; • Symbolic names for values – extension of algebra • Abstraction of underlying hardware • printf("Hello World!"); • Provide expressiveness • if(isCloudy) • get(umbrella); • else • get(sunglasses); • Enhances code readability • Provide safeguards against bugs • main() • { • readInput(); • checkForErrors(); • doCalculation(); • writeOutput(); • } High-level languages make complex programming simpler, while low-level languages tend to produce more efficient code

  17. Example: now that I know where to store vars, let’s list (compile) the necessary assembly instructions for a typical algebraic expression: HLL (Algebra): z = K+ y Assembly: ?? The implementation of a HLL involves the interaction between computational structures (CPU) and memory (RAMand Stack). See DataTypeInt.c

  18. HLL (Algebra): z = x + y 0x0FFFF ? mov.w#5,&x mov.w#3,&y mov.w#x,r14 mov.w&y,r15 add.w@r14,r15 mov.w#z,r14 mov.wr15,0(r14) { 0x05c00 16KB 0x01c00 0x00000

  19. How to write this in C: z = x + y volatile int x; volatile int y; volatile int z; void main(void) { //main function x=5; y=3; z=x+y; // just like algebra, not avail in assembly, Jimenez p. 226 } CDateTypeInt.c

  20. The C Language C Program • What is found in a C program? • Functions (see Jimenez p.226) • Global variables. • What is a variable? • A symbolic name for a memory location containing a value. • 2 types of variables • Local (automatic – accessible only within function’s frame) • Global (static – accessible anywhere in program after declaration). • Variable declarations include • A symbolic name • Data type (int, char, double) • Scope (who has access, code region where the variable is defined) • Extent (lifetime of variable value at run-time). • What is a constant? • A symbolic name for a value that cannot be altered by a program during execution.

  21. Assembler Code C Code Object Code Machine Code The C Language C Program Development

  22. C Preprocessor Preprocessed source code 1st Pass 2nd Pass Code Generation Source Code Analysis Symbol Table Object module Library & Object Files Linker ExecutableImage The C Language Compile: produce (something, esp. a list, report, or book) by assembling information collected from other sources C Compiler C Source Code

  23. Another Program Tells compiler to use all the definitions found in the msp430.h library. A .h file is called a header file and contains definitions and declarations. //************************************ // blinky.c: Software Toggle P1.0 //************************************ #include "msp430.h" volatile unsigned int i; // no optimization void main(void) { WDTCTL = WDTPW | WDTHOLD; // stop watchdog P1DIR |= BIT0; // P1.0 output while(1) // loop { if(i == 0) { P1OUT ^= BIT0; // toggle P4.6 } i = i + 1; // delay } } All C programs must have a main() routine. Stop WD w/Password Allocate a global RAM variable (.bss i,2) Set P1.0 as output Loop forever Toggle P1.0 Delay 65,536

  24. inti,j,k; // declaring more than one variable int i1, i2, i3, c3po; // numbers OK, except for first letter int bananas = 10; // using an initializer intmonkey_count = 0; // two ways of doing ... intmonkeyCount = 0; // ... multi-word names int ab, Ab, aB, AB; // case sensitive names int _compilerVar; // compiler uses _ as first char char newline = ‘\n’; // a character with an initializer char lineBuffer[32]; // an array of 32 chars (a string) double bananasPerMonkey; // floating point declarations double hugeNumber = 1.0E33; // positive exponent double tinyNumber = 1.0E-33; // negative exponent double fractionThing = 3.33333; // no exponent

  25. What is found in a C program? • Functions • Global variables. • What is a variable? • A symbolic name for a memory location containing a value. • 2 types of variables • Local (automatic – accessible only within function’s frame) • Global (static – accessible anywhere in program after declaration). • Variable declarations include • A symbolic name • Data type (int, char, double) • Scope (code region where the variable is defined) • Extent (lifetime of variable value at run-time). • What is a constant? • A symbolic name for a value that cannot be altered by a program during execution.

  26. intx=‘A’, char y=3, float, long

  27. MSP430 Data Type support for ANSI-C http://www.ti.com/lit/ug/slau132i/slau132i.pdf

  28. Storage Classes • Storage class specifiers • Storage duration – how long an object exists in memory • Scope – where object can be referenced in program • Automatic storage • Object created and destroyed within its block • auto: default for local variables auto int x, y; • register: tries to put variable into high-speed registers • Can only be used for automatic variables register int counter = 1;

  29. Variables Scope: Local versus Global • Extent of a variable is its lifetime in a program • Local Variables (automatic) • Declared at the beginning of a block • Stored in activation record on the stack • Scope is from point of declaration to the end of the block • Un-initialized • Global Variables (static) • Declared outside of a function • Stored in Global Data Section of memory • Scope is from point of declaration to the end of the program • May be initialized to zero { // begin blockintice_cream; ...} intice_cream; { // begin block ...}

  30. Extent of a variable is its lifetime in a program • Local Variables (automatic) • Declared at the beginning of a block • Stored in activation record on the stack • Scope is from point of declaration to the end of the block • Un-initialized • Global Variables (static) • Declared outside of a function • Stored in Global Data Section of memory • Scope is from point of declaration to the end of the program • May be initialized to zero

  31. Variable Storage von Neumann Memory Layout 0000 I/O Space Static storage class Global Variables Static Variables Global Data Section(Global and Static vars) Heap(Dynamically allocated vars) Run-Time Stack(Local and Auto vars) SP Automatic storage class Local Variables Program Code PC An activation record is a block of memory on the stack that is created with scoping operators. The record contains all the local variables for a given invocation of a block or function. FFFF Interrupt Vector Table

  32. C Preprocessor The C Preprocessor • The C preprocessor or cpp is the macro preprocessor for the C and C++ computer programming languages. • In many C implementations, it is a separate program invoked by the compiler as the first part of translation. • The language of preprocessor directives is only weakly related to the grammar of C and so is sometimes used to process other kinds of text files. • The preprocessor provides the ability for #include <stdio.h> // system header #include "myheader.h" // user header • the inclusion of header files (#include), #define PI 3.14159 #define add(x,y) x+y #define concatenate(x,y) x##y • macro expansions (#define), #if 0 somecode… #else somecode… #endif __FILE__ __LINE__ __DATE__ __TIME__ • conditional compilation (#if, #else, #endif), • and line control (#line).

  33. The C Symbol Table • The C compiler keeps track of variables, constants, functions, and other symbolic identifier in a symbol table. • A new symbol table entry is created when a program identifier is declared. • Specifically, each symbol table entry contains: • Name • Type (data type, function, address, etc.) • Storage class (auto, static) • Location or offset • Scope. • Variables must be declared and in scope before they can be used (referenced) by a program.

  34. Operators Operators and Expressions Expressions are formed by combining variables with operators and ALWAYS return a single value in C. i = 5; i < j; a = (a < b); Operators Assignment – changes the values of variables Arithmetic – add, subtract, multiply, divide Bitwise – AND, OR, XOR, NOT, and shifts on Integers Relational – equality, inequality, less-than, etc. Logical – AND, OR, NOT on Booleans Increment/Decrement C supports a rich set of operators that allow the programmer to manipulate variables

  35. The switch statement switch (expression) { case1: code block 1; case2: code block 2; case3: code block 3; . . . default: code block N } Jimenez p.229

  36. Variable Scope C to Assembly x05f8 { int x = 10; int y = 20; int z = 30; x = x + 4; y = x + y - z; } x05fa x Scope Frame x05fc y x05fe z x0600 SP SP Scope activation Stack 0x8696: 8031 0006 SUB.W #0x0006,SP 0x869a: 40B1 000A 0000 MOV.W #0x000a,0x0000(SP) 0x86a0: 40B1 0014 0002 MOV.W #0x0014,0x0002(SP) 0x86a6: 40B1 001E 0004 MOV.W #0x001e,0x0004(SP) 0x86ac: 52A1 0000 ADD.W #4,0x0000(SP) 0x86b0: 411F 0002 MOV.W 0x0002(SP),R15 0x86b4: 512F ADD.W @SP,R15 0x86b6: 811F 0004 SUB.W 0x0004(SP),R15 0x86ba: 4F81 0002 MOV.W R15,0x0002(SP) 0x86be: 5031 0006 ADD.W #0x0006,SP Scope deactivation

  37. Functions Functions • Functions have been included in all programming languages since the very early days of computing. • Support for functions is provided directly in all instruction set architectures. • In other languages, called procedures, methods, subroutines, ... • C is heavily oriented around functions. • A C program is organized as a collection of functions. • Every C statement belongs to a function • All C programs start and finish execution in the function main • Functions may call other functions which, in turn, call more functions. • Functions • Provides abstraction • hide low-level details • give high-level structure to program, easier to understand overall program flow • enables separable, independent development • Used for Systematic Decomposition • Functions break large computing tasks into smaller ones. • Functions enlarge the set of elementary building blocks.

  38. High Level Languages C Functions • Divide and conquer • Construct a program from smaller pieces or components • These smaller pieces are called modules • Each piece more manageable than the original program • main() • { • readInput(); • checkForErrors(); • doCalculation(); • writeOutput(); • }

  39. Functions • Modules in C • Programs combine user-defined functions with library functions • C standard library has a wide variety of functions • Function calls • Invoking functions • Provide function name and arguments (data) • Function performs operations or manipulations • Function returns results • Function call analogy: • Boss asks worker to complete task • Worker gets information, does task, returns result • Information hiding: boss does not know details

  40. Function Definitions • Function definition format return-value-type function-name( parameter-list ){ declarations and statements} • Function-name: any valid identifier • Return-value-type: data type of the result (default int) • void– indicates that the function returns nothing • Parameter-list: comma separated list, declares parameters • A type must be listed explicitly for each parameter unless, the parameter is of type int

  41. Function Prototypes • Function prototype • Function name • Parameters – what the function takes in • Return type – data type function returns (default int) • Used to validate functions • Prototype only needed if function definition comes after use in program • The function with the prototype int maximum( int, int, int ); • Takes in 3 ints • Returns an int • Promotion rules and conversions • Converting to lower types can lead to errors

  42. Header Files • Header files • Contain function prototypes for library functions • <stdlib.h> , <math.h> , etc • Load with #include <filename> #include <math.h> • Custom header files • Create file with functions • Save as filename.h • Load in other files with #include "filename.h" • Reuse functions

  43. function prototype (declaration) arguments formal parameters Return value function call Functions C Functions (Jimenez p. 232) intaddNumbers(int, int); int main() { int result; result = addNumbers(4, 5); ... } intaddNumbers(int x, int y) { return (x+y); } scope of addNumberswith prototype scope of addNumberswithout prototype Function definition

  44. C Compiler User Guide – Runtime Environment http://www.ti.com/lit/ug/slau132i/slau132i.pdf

  45. Automatic variables z = x + y volatile int x; volatile int y; volatile int z; void main(void) { //main function volatile int x; volatile int y; volatile int z; x=5; y=3; z=x+y; // just like algebra, not avail in assembly, Jimenez p. 226 } CDateTypeInt.c

  46. High Address Frame or Activation Record Stack Stack Pointer (SP) Parameter Passing Stack Frames / Parameter Passing • Each function call creates a new stack frame (activation record). • Function arguments are evaluated right to left • R12 = 1st argument, R13 = 2nd argument • The result of the function is returned in R12. Parameters (When more than 4) Return Address Saved Registers (if any) Local Variables Low Address

  47. Program starts main calls A A calls B B returns to A A returns to main Memory Memory Memory Memory Memory main main main main main A A A B SP SP SP SP SP Activation Records Run-time Stack Operation

  48. Example Draw a line for all connections between the C and assembly programs below. ; myAssemblyProgram.asm .defasm_mult .ref C_multiply .text ; asm_mult ******************** ; IN: r12 = arg1 ; r13 = arg2 ; OUT: r12 = arg1 * arg2 ; asm_mult: call #C_multiply ret .end // myCProgram.c extern intasm_mult(int, int); void main(void) { int result; result = asm_mult(10, 20); return; } intC_multiply(int x, int y) { return x * y; }

  49. Frames Compiler Register Usage Register allocations The scratch registers R12 to R15 are used for parameter passing and hence are not normally preserved across the call. The other general-purpose registers, R4 to R11, are mainly used for register variables and temporary results and must be preserved across a call. This is handled automatically within C. Function parameters The parameters of a called function are passed to an assembler routine in a right to left order. Up to four left most parameters are passed in registers unless they are defined as a struct or union type, in which case they are also passed on the stack. The remaining parameters are always passed on the stack.

More Related