Embedded System Design

The Washington Institute for Near East Policy

Politico.com: Politics '08

Tuesday, August 14, 2007

Monday, August 13, 2007

The basics of programming embedded processors: Part 3

By Wayne Wolf , Embedded.com
Aug 7 2007 (0:15 AM)
URL: http://www.embedded.com/showArticle.jhtml?articleID=201203685


It is useful to understand how a high-level language program is translated into instructions. First, since implementing an embedded computing system often requires controlling the instruction sequences used to handle interrupts, placement of data and instructions in memory, and so forth, understanding how the compiler works can help you know when you cannot rely on the compiler.


Next, because many applications are also performance sensitive, understanding how code is generated can help you meet your performance goals, either by writing high-level code that gets compiled into the instructions you want or by recognizing when you must write your own assembly code.

Compilation = translation + optimization. Compilation combines translation and optimization. The high-level language program is translated into the lower-level form of instructions; optimizations try to generate better instruction sequences than would be possible if the brute force technique of independently translating source code statements were used.


Optimization techniques focus on more of the program to ensure that compilation decisions that appear to be good for one statement are not unnecessarily problematic for other parts of the program.

The compilation process is summarized in Figure 5-12 below. Compilation begins with high-level language code such as C and generally produces assembly code. (Directly producing object code simply duplicates the functions of an assembler, which is a very desirable stand-alone program to have.)


The highlevel language program is parsed to break it into statements and expressions. In addition, a symbol table is generated, which includes all the named objects in the program. Some compilers may then perform higher-level optimizations that can be viewed as modifying the high-level language program input without reference to instructions.



Figure 5-12. The compilation process.

Simplifying arithmetic expressions is one example of a machineindependent optimization. Not all compilers do such optimizations, and compilers can vary widely regarding which combinations of machine-independent optimizations they do perform. Instruction-level optimizations are aimed at generating code.


They may work directly on real instructions or on a pseudoinstruction format that is later mapped onto the instructions of the target CPU. This level of optimization also helps modularize the compiler by allowing code generation to create simpler code that is later optimized. For example, consider the following array access code:

x[i] = c*x[i];

A simple code generator would generate the address for x[i] twice, once for each appearance in the statement. The later optimization phases can recognize this as an example of common expressions that need not be duplicated.


While in this simple case it would be possible to create a code generator that never generated the redundant expression, taking into account every such optimization at code generation time is very difficult. We get better code and more reliable compilers by generating simple code first and then optimizing it.

Statement Translation
In this section, we consider the basic job of translating the high-level language program with little or no optimization. Let's first consider how to translate an expression.


A large amount of the code in a typical application consists of arithmetic and logical expressions. Understanding how to compile a single expression, as described in Example 5-2 below, is a good first step in understanding the entire compilation process.

Example 5-2 Compiling an Arithmetic Expression
In the following arithmetic expression,

a*b + 5*(c ' d)

the variable is written in terms of program variables. In some machines we may be able to perform memory-to-memory arithmetic directly on the locations corresponding to those variables. However, in many machines, such as the ARM, we must first load the variables into registers. This requires choosing which registers receive not only the named variables but also intermediate results such as (c ' d).

The code for the expression can be built by walking the data flow graph. The data flow graph for the expression appears below.



The temporary variables for the intermediate values and final result have been named w, x, y, and z. To generate code, we walk from the tree's root (where z, the final result, is generated) by traversing the nodes in post order. During the walk, we generate instructions to cover the operation at every node. The path is presented below.



The nodes are numbered in the order in which code is generated. Since every node in the data flow graph corresponds to an operation that is directly supported by the instruction set, we simply generate an instruction at every node. Since we are making an arbitrary register assignment, we can use up the registers in order starting with r1. The resulting ARM code follows:

; operator 1 (+) ADR r4,a ; get address for a MOV r1,[r4] ; load a ADR r4,b ; get address for b MOV r2,[r4] ; load b ADD r3,r1,r2 ; put w into r3 ; operator 2 (') ADR r4,c ; get address for c MOV r4,[r4] ; load c ADR r4,d ; get address for d MOV r5,[r4] ; load d SUB r6,r4,r5 ; put x into r6 ; operator 3 (*) MUL r7,r6,#5 ; operator 3, puts y into r7 ; operator 4 (+) ADD r8,r7,r3 ; operator 4, puts z into r8
The equivalent SHARC code appears below.

! operator 1 (+) R1 = DM(a); ! load a R2 = DM(b); ! load b R3 = R1 + R2; ! compute a + b ! operator 2 (') R4 = DM(c); ! load c R5 = DM(d); ! load d R6 = R4 ' R5; ! compute c ' d ! operator 3 (*) R7 = 5; R8 = R6 * R7; ! compute y ! operator 4 (+) R9 = R3 + R8; ! compute z
One obvious optimization is to reuse a register whose value is no longer needed. In the case of the intermediate values w, x, and y, we know that they cannot be used after the end of the expression (e.g., in another expression) since they have no name in the C program. However, the final result z may in fact be used in a C assignment and the value reused later in the program. In this case we would need to know when the register is no longer needed to determine its best use.



Figure 5-13. Flow of control in C and control flow diagrams

In the previous example, we made an arbitrary allocation of variables to registers for simplicity. When we have large programs with multiple expressions, we must allocate registers more carefully since CPUs have a limited number of registers. We will consider register allocation later.

We also need to be able to translate control structures. Since conditionals are controlled by expressions, the code generation techniques of the last example can be used for those expressions, leaving us with the task of generating code for the flow of control itself.


Figure 5-13 above shows a simple example of changing flow of control in C - an if statement, in which the condition controls whether the true or false branch of the if is taken. Figure 5-13 also shows the control flow diagram for the if statement. Example 5-3 illustrates how to implement conditionals in assembly language.

Example 5-3 Generating Code for a Conditional
Consider the following C statement:

if (a + b > 0) x = 5;else x = 7;
The CDFG for the statement appears below.



We know how to generate the code for the expressions. We can generate the control flow code by walking the CDFG. One ordered walk through the CDFG follows:



To generate code, we must assign a label to the first instruction at the end of a directed edge and create a branch for each edge that does not go to the immediately following instruction. The exact steps to be taken at the branch points depend on the target architecture.


On some machines, evaluating expressions generates condition codes that we can test in subsequent branches, and on other machines we must use test-and-branch instructions. ARM allows us to test condition codes, so we get the following ARM code for the 1-2-3 walk:

ADR r5,a ; get address for a LDR r1,[r5] ; load a ADR r5,b ; get address for b LDR r2,b ; load b ADD r3,r1,r2 BLE label3 ; true condition falls through branch ; true case LDR r3,#5 ; load constant ADR r5,x STR r3, [r5] ; store value into x B stmtend ; done with the true case ; false case label3 LDR r3,#7 ; load constant ADR r5,x ; get address of x STR r3,[r5] ; store value into x stmtend ...
The 1-2 and 3-4 edges do not require a branch and label because they are straight-line code. In contrast, the 1-3 and 2-4 edges do require a branch and a label for the target.

Since expressions are generally created as straight-line code, they typically require careful consideration of the order in which the operations are executed. We have much more freedom when generating conditional code because the branches ensure that the flow of control goes to the right block of code. If we walk the CDFG in a different order and lay out the code blocks in a different order in memory, we still get valid code as long as we properly place branches.

Drawing a control flow graph based on the while form of the loop helps us understand how to translate it into instructions.



C compilers can generate (using the -s flag) assembler source, which some compilers intersperse with the C code. Such code is a very good way to learn about both assembly language programming and compilation. Web Aid 5-Assembly has examples of assembly output from C compilers for the ARM and SHARC.

Procedures
Another major code generation problem is the creation of procedures. Generating code for procedures is relatively straightforward once we know the procedure linkage appropriate for the CPU. At the procedure definition, we generate the code to handle the procedure call and return. At each call of the procedure, we set up the procedure parameters and make the call.

The CPU's subroutine call mechanism is usually not sufficient to directly support procedures in modern programming languages. The procedure linkage mechanism provides a way for the program to pass parameters into the program and for the procedure to return a value.


It also provides help in restoring the values of registers that the procedure has modified. All procedures in a given programming language use the same linkage mechanism (although different languages may use different linkages). The mechanism can also be used to call handwritten assembly language routines from compiled code.

Procedure stacks are typically built to grow down from high addresses. A stack pointer (sp) defines the end of the current frame, while a frame pointer (fp) defines the end of the last frame. (The fp is technically necessary only if the stack frame can be grown by the procedure during execution.)


The procedure can refer to an element in the frame by addressing relative to sp. When a new procedure is called, the sp and fp are modified to push another frame onto the stack.

The ARM Procedure Call Standard (APCS) is a good illustration of a typical procedure linkage mechanism. Although the stack frames are in main memory, understanding how registers are used is key to understanding the mechanism, as explained below.

r0"r3 are used to pass parameters into the procedure. r0 is also used to hold the return value. If more than four parameters are required, they are put on the stack frame.
r4"r7 hold register variables.
r11 is the frame pointer and r13 is the stack pointer.
r10 holds the limiting address on stack size, which is used to check for stack overflows.
Other registers have additional uses in the protocol.



Figure 5-14. Layout of a one-dimensional array in memory

Data Structures
The compiler must also translate references to data structures into references to raw memories. In general, this requires address computations. Some of these computations can be done at compile time while others must be done at run time. arrays Arrays are interesting because the address of an array element must in general be computed at run time, since the array index may change. Let us first consider one-dimensional arrays:

a[i]

The layout of the array in memory is shown in Figure 5-14 above. The zeroth element is stored as the first element of the array, the first element directly below, and so on. We can create a pointer for the array that points to the array's head, namely, a[0]. If we call that pointer aptr for convenience, then we can rewrite the reading of a [i] as

*(aptr + i)

Two-dimensional arrays are more challenging. There are multiple possible ways to lay out a two-dimensional array in memory, as shown in Figure 5-15 below. In this form, which is known as row major, the inner variable of the array (j in a[i,j]) varies most quickly. (Fortran uses a different organization known as column major.)


Two-dimensional arrays also require more sophisticated addressing - in particular, we must know the size of the array. Let us consider the row-major form. If the a[] array is of size N × M, then we can turn the two-dimensional array access into a one-dimensional array access. Thus,

a[i,j]

becomes

a[i*M + j]

where the maximum value for j is M ' 1.



Figure 5-15. Memory layout for two-dimensional arrays

A C struct is easier to address. As shown in Figure 5-16 below, a structure is implemented as a contiguous block of memory. Fields in the structure can be accessed using constant offsets to the base address of the structure. In this example, if field1 is four bytes long, then field2 can be accessed as

*(aptr + 4)

This addition can usually be done at compile time, requiring only the indirection itself to fetch the memory location during execution.

Expression Simplification
Expression simplification is a useful area for machine-independent transformations. We can use the laws of algebra to simplify expressions. Consider the following expression:

a*b + a*c

We can use the distributive law to rewrite the expression as

a*(b + c)


Figure 5-16. C structure layout and access.

Since the new expression has only two operations rather than three for the original form, it is almost certainly cheaper, because it is both faster and smaller. Such transformations make some broad assumptions about the relative cost of operations.


In some cases, simple generalizations about the cost of operations may be misleading. For example, a CPU with a multiply-andaccumulate instruction may be able to do a multiply and addition as cheaply as it can do an addition. However, such situations can often be taken care of in code generation.

We can also use the laws of arithmetic to further simplify expressions on constants. Consider the following C statement:

for (i = 0; i < 8 + 1; i++)

We can simplify 8 + 1 to 9 at compile time - there is no need to perform that arithmetic while the program is executing. Why would a program ever contain expressions that evaluate to constants? Using named constants rather than numbers is good programming practice and often leads to constant expression. The original form of the for statement could have been

for (i = 0; i < NOPS + 1; i++)

where, for example, the added 1 takes care of a trailing null character.

Dead Code Elimination
Code that will never be executed can be safely removed from the program. The general problem of identifying code that will never be executed is difficult, but there are some important special cases where it can be done. Programmers will intentionally introduce dead code in certain situations.


Consider this C code fragment:


#define DEBUG 0 ... if (DEBUG) print_debug_stuff();


In the above case, the print_debug_stuff() function is never executed, but the code allows the programmer to override the preprocessor variable definition (perhaps with a compile-time flag) to enable the debugging code.


This case is easy to analyze because the condition is the constant 0, which C uses for the false condition. Since there is no else clause in the if statement, the compiler can totally eliminate the if statement, rewriting the CDFG to provide a direct edge between the statements before and after the if.

Some dead code may be introduced by the compiler. For example, certain optimizations introduce copy statements that copy one variable to another. If uses of the first variable can be replaced by references to the second one, then the copy statement becomes dead code that can be eliminated.

Procedure Inlining
Another machine-independent transformation that requires a little more evaluation is procedure inlining. An inlined procedure does not have a separate procedure body and procedure linkage; rather, the body of the procedure is substituted in place for the procedure call. Figure 5-17 below shows an example of function inlining in C.


The C++ programming language provides an inline construct that tells the compiler to generate inline code for a function. In this case, an inlined procedure is generated in expanded form whenever possible. However, inlining is not always the best thing to do. It does eliminate the procedure linkage instructions. However, in a cached system, having multiple copies of the function body may actually slow down the fetches of these instructions. Inlining also increases code size, and memory may be precious.

Function definition:
int foo(a,b,c) { return a + b " c; }

Function call:
z = foo(w,x,y,);

Inlining result:
z = w + x " y;

Figure 5-17. Function inlining in C.

Loop Transformations
Loops are important program structures—although they are compactly described in the source code, they often use a large fraction of the computation time. Many techniques have been designed to optimize loops.

A simple but useful transformation is known as loop unrolling, which is illustrated in Example 5-4. Loop unrolling is important because it helps expose parallelism that can be used by later stages of the compiler.

Example 5-4 Loop Unrolling
A simple loop in C follows:

for (i = 0; i < N; i++) { a[i]=b[i]*c[i]; }
This loop is executed a fixed number of times, namely, N. A straightforward implementation of the loop would create and initialize the loop variable i, update its value on every iteration, and test it to see whether to exit the loop. However, since the loop is executed a fixed number of times, we can generate more direct code.

If we let N = 4, then we can substitute the above C code for the following loop:

a[0] = b[0]*c[0]; a[1] = b[1]*c[1]; a[2] = b[2]*c[2]; a[3] = b[3]*c[3];
This unrolled code has no loop overhead code at all, that is, no iteration variable and no tests. But the unrolled loop has the same problems as the inlined procedure—it may interfere with the cache and expands the amount of code required.

We do not, of course, have to fully unroll loops. Rather than unroll the above loop four times, we could unroll it twice. The following code results:

for (i = 0; i < 2; i++) { a[i*2] = b[i*2]*c[i*2]; a[i*2 + 1] = b[i*2 + 1]*c[i*2 + 1]; }
In this case, since all operations in the two lines of the loop body are independent, later stages of the compiler may be able to generate code that allows them to be executed efficiently on the CPU's pipeline.

Loop fusion combines two or more loops into a single loop. For this transformation to be legal, two conditions must be satisfied. First, the loops must iterate over the same values. Second, the loop bodies must not have dependencies that would be violated if they are executed together—for example, if the second loop's ith iteration depends on the results of the i + 1th iteration of the first loop, the two loops cannot be combined. Loop distribution is the opposite of loop fusion, that is, decomposing a single loop into multiple loops.

Loop tiling breaks up a loop into a set of nested loops, with each inner loop performing the operations on a subset of the data. An example is shown in Figure 5-18. Here, each loop is broken up into tiles of size two. Each loop is split into two loops—for example, the inner ii loop iterates within the tile and the outer i loop iterates across the tiles.


The result is that the pattern of accesses across the a array is drastically different - rather than walking across one row in its entirety, the code walks through rows and columns following the tile structure. Loop tiling changes the order in which array elements are accessed, thereby allowing us to better control the behavior of the cache during loop execution.


Figure 5-18. Loop tiling.

We can also modify the arrays being indexed in loops. Array padding adds dummy data elements to a loop in order to change the layout of the array in the cache. Although these array locations will not be used, they do change how the useful array elements fall into cache lines. Judicious padding can in some cases significantly reduce the number of cache conflicts during loop execution.


Next in Part 4: The creation of procedures
To read Part 1, go to "Program design and analysis."
To read Part 2 , go to " Models of program, assemblers and linkers."


Used with the permission of the publisher, Newnes/Elsevier, this series of six articles is based on copyrighted material from "Computers as Components: Principles of Embedded Computer System Design" by Wayne Wolf. The book can be purchased on line.

Wayne Wolf is currently the Georgia Research Alliance Eminent Scholar holding the Rhesa "Ray" S. Farmer, Jr., Distinguished Chair in Embedded Computer Systems at Georgia Tech's School of Electrical and Computer Engineering (ECE). Previously a professor of electrical engineering at Princeton University, he worked at AT&T Bell Laboratories. He has served as editor in chief of the ACM Transactions on Embedded Computing and of Design Automation for Embedded Systems.

The basics of programming embedded processors: Part 4

By Wayne Wolf , Embedded.com
Aug 13 2007 (3:00 AM)
URL: http://www.embedded.com/showArticle.jhtml?articleID=201500002

Another major code generation problem is the creation of procedures. Generating code for procedures is relatively straightforward once we know the procedure linkage appropriate for the CPU. At the procedure definition, we generate the code to handle the procedure call and return. At each call of the procedure, we set up the procedure parameters and make the call.

The CPU's subroutine call mechanism is usually not sufficient to directly support procedures in modern programming languages. The procedure linkage mechanism provides a way for the program to pass parameters into the program and for the procedure to return a value.


It also provides help in restoring the values of registers that the procedure has modified. All procedures in a given programming language use the same linkage mechanism (although different languages may use different linkages). The mechanism can also be used to call handwritten assembly language routines from compiled code.

Procedure stacks are typically built to grow down from high addresses. A stack pointer (sp) defines the end of the current frame, while a frame pointer (fp) defines the end of the last frame. (The fp is technically necessary only if the stack frame can be grown by the procedure during execution.)


The procedure can refer to an element in the frame by addressing relative to sp. When a new procedure is called, the sp and fp are modified to push another frame onto the stack.

The ARM Procedure Call Standard (APCS) is a good illustration of a typical procedure linkage mechanism. Although the stack frames are in main memory, understanding how registers are used is key to understanding the mechanism, as explained below.

r0"r3 are used to pass parameters into the procedure. r0 is also used to hold the return value. If more than four parameters are required, they are put on the stack frame.
r4"r7 hold register variables.
r11 is the frame pointer and r13 is the stack pointer.
r10 holds the limiting address on stack size, which is used to check for stack overflows.
Other registers have additional uses in the protocol.



Figure 5-14. Layout of a one-dimensional array in memory

Data Structures
The compiler must also translate references to data structures into references to raw memories. In general, this requires address computations. Some of these computations can be done at compile time while others must be done at run time. arrays Arrays are interesting because the address of an array element must in general be computed at run time, since the array index may change. Let us first consider one-dimensional arrays:

a[i]

The layout of the array in memory is shown in Figure 5-14 above. The zeroth element is stored as the first element of the array, the first element directly below, and so on. We can create a pointer for the array that points to the array's head, namely, a[0]. If we call that pointer aptr for convenience, then we can rewrite the reading of a [i] as

*(aptr + i)

Two-dimensional arrays are more challenging. There are multiple possible ways to lay out a two-dimensional array in memory, as shown in Figure 5-15 below. In this form, which is known as row major, the inner variable of the array (j in a[i,j]) varies most quickly. (Fortran uses a different organization known as column major.)


Two-dimensional arrays also require more sophisticated addressing - in particular, we must know the size of the array. Let us consider the row-major form. If the a[] array is of size N × M, then we can turn the two-dimensional array access into a one-dimensional array access. Thus,

a[i,j]

becomes

a[i*M + j]

where the maximum value for j is M ' 1.



Figure 5-15. Memory layout for two-dimensional arrays

A C struct is easier to address. As shown in Figure 5-16 below, a structure is implemented as a contiguous block of memory. Fields in the structure can be accessed using constant offsets to the base address of the structure. In this example, if field1 is four bytes long, then field2 can be accessed as

*(aptr + 4)

This addition can usually be done at compile time, requiring only the indirection itself to fetch the memory location during execution.

Expression Simplification
Expression simplification is a useful area for machine-independent transformations. We can use the laws of algebra to simplify expressions. Consider the following expression:

a*b + a*c

We can use the distributive law to rewrite the expression as

a*(b + c)


Figure 5-16. C structure layout and access.

Since the new expression has only two operations rather than three for the original form, it is almost certainly cheaper, because it is both faster and smaller. Such transformations make some broad assumptions about the relative cost of operations.


In some cases, simple generalizations about the cost of operations may be misleading. For example, a CPU with a multiply-andaccumulate instruction may be able to do a multiply and addition as cheaply as it can do an addition. However, such situations can often be taken care of in code generation.

We can also use the laws of arithmetic to further simplify expressions on constants. Consider the following C statement:

for (i = 0; i < 8 + 1; i++)

We can simplify 8 + 1 to 9 at compile time - there is no need to perform that arithmetic while the program is executing. Why would a program ever contain expressions that evaluate to constants? Using named constants rather than numbers is good programming practice and often leads to constant expression. The original form of the for statement could have been

for (i = 0; i < NOPS + 1; i++)

where, for example, the added 1 takes care of a trailing null character.


Dead Code Elimination
Code that will never be executed can be safely removed from the program. The general problem of identifying code that will never be executed is difficult, but there are some important special cases where it can be done. Programmers will intentionally introduce dead code in certain situations.


Consider this C code fragment:


#define DEBUG 0 ... if (DEBUG) print_debug_stuff();


In the above case, the print_debug_stuff() function is never executed, but the code allows the programmer to override the preprocessor variable definition (perhaps with a compile-time flag) to enable the debugging code.


This case is easy to analyze because the condition is the constant 0, which C uses for the false condition. Since there is no else clause in the if statement, the compiler can totally eliminate the if statement, rewriting the CDFG to provide a direct edge between the statements before and after the if.

Some dead code may be introduced by the compiler. For example, certain optimizations introduce copy statements that copy one variable to another. If uses of the first variable can be replaced by references to the second one, then the copy statement becomes dead code that can be eliminated.

Procedure Inlining
Another machine-independent transformation that requires a little more evaluation is procedure inlining. An inlined procedure does not have a separate procedure body and procedure linkage; rather, the body of the procedure is substituted in place for the procedure call. Figure 5-17 below shows an example of function inlining in C.


The C++ programming language provides an inline construct that tells the compiler to generate inline code for a function. In this case, an inlined procedure is generated in expanded form whenever possible. However, inlining is not always the best thing to do. It does eliminate the procedure linkage instructions. However, in a cached system, having multiple copies of the function body may actually slow down the fetches of these instructions. Inlining also increases code size, and memory may be precious.

Function definition:
int foo(a,b,c) { return a + b " c; }

Function call:
z = foo(w,x,y,);

Inlining result:
z = w + x " y;

Figure 5-17. Function inlining in C.

Loop Transformations
Loops are important program structures - although they are compactly described in the source code, they often use a large fraction of the computation time. Many techniques have been designed to optimize loops.

A simple but useful transformation is known as loop unrolling, which is illustrated in Example 5-4 below. Loop unrolling is important because it helps expose parallelism that can be used by later stages of the compiler.

Example 5-4 Loop Unrolling
A simple loop in C follows:

for (i = 0; i < N; i++) { a[i]=b[i]*c[i]; }
This loop is executed a fixed number of times, namely, N. A straightforward implementation of the loop would create and initialize the loop variable i, update its value on every iteration, and test it to see whether to exit the loop. However, since the loop is executed a fixed number of times, we can generate more direct code.

If we let N = 4, then we can substitute the above C code for the following loop:

a[0] = b[0]*c[0]; a[1] = b[1]*c[1]; a[2] = b[2]*c[2]; a[3] = b[3]*c[3];
This unrolled code has no loop overhead code at all, that is, no iteration variable and no tests. But the unrolled loop has the same problems as the inlined procedure—it may interfere with the cache and expands the amount of code required.

We do not, of course, have to fully unroll loops. Rather than unroll the above loop four times, we could unroll it twice. The following code results:

for (i = 0; i < 2; i++) { a[i*2] = b[i*2]*c[i*2]; a[i*2 + 1] = b[i*2 + 1]*c[i*2 + 1]; }
In this case, since all operations in the two lines of the loop body are independent, later stages of the compiler may be able to generate code that allows them to be executed efficiently on the CPU's pipeline.

Loop fusion combines two or more loops into a single loop. For this transformation to be legal, two conditions must be satisfied. First, the loops must iterate over the same values. Second, the loop bodies must not have dependencies that would be violated if they are executed together - for example, if the second loop's ith iteration depends on the results of the i + 1th iteration of the first loop, the two loops cannot be combined. Loop distribution is the opposite of loop fusion, that is, decomposing a single loop into multiple loops.

Loop tiling breaks up a loop into a set of nested loops, with each inner loop performing the operations on a subset of the data. An example is shown in Figure 5-18 below. Here, each loop is broken up into tiles of size two. Each loop is split into two loops - for example, the inner ii loop iterates within the tile and the outer i loop iterates across the tiles.


The result is that the pattern of accesses across the a array is drastically different - rather than walking across one row in its entirety, the code walks through rows and columns following the tile structure. Loop tiling changes the order in which array elements are accessed, thereby allowing us to better control the behavior of the cache during loop execution.


Figure 5-18. Loop tiling.

We can also modify the arrays being indexed in loops. Array padding adds dummy data elements to a loop in order to change the layout of the array in the cache. Although these array locations will not be used, they do change how the useful array elements fall into cache lines. Judicious padding can in some cases significantly reduce the number of cache conflicts during loop execution.

Next in Part 5: Register allocation and scheduling
To read Part 1, go to "Program design and analysis."
To read Part 2 , go to " Models of program, assemblers and linkers."
To read Part 3, go to "Basic compilation techniques"

Used with the permission of the publisher, Newnes/Elsevier, this series of six articles is based on copyrighted material from "Computers as Components: Principles of Embedded Computer System Design" by Wayne Wolf. The book can be purchased on line.

Wayne Wolf is currently the Georgia Research Alliance Eminent Scholar holding the Rhesa "Ray" S. Farmer, Jr., Distinguished Chair in Embedded Computer Systems at Georgia Tech's School of Electrical and Computer Engineering (ECE). Previously a professor of electrical engineering at Princeton University, he worked at AT&T Bell Laboratories. He has served as editor in chief of the ACM Transactions on Embedded Computing and of Design Automation for Embedded Systems.

Tuesday, July 31, 2007

The basics of programming embedded processors: Part 2

The basics of programming embedded processors: Part 2
By Wayne Wolf, Embedded.com
Jul 31 2007 (0:15 AM)
URL: http://www.embedded.com/showArticle.jhtml?articleID=201201938


Where previously in Part 1 we covered the basics of program design and analysis and the usefulness of design patterns, in this part in this series of articles we develop models for programs that are more general than source code.


Why not use the source code directly? First, there are many different types of source code - assembly languages, C code, and so on - but we can use a single model to describe all of them. Second, once we have such a model, we can perform many useful analyses on the model more easily than we could on the source code.

Our fundamental model for programs is the control/data flow graph (CDFG). (We can also model hardware behavior with the CDFG.) As the name implies, the CDFG has constructs that model both data operations (arithmetic and other computations) and control operations (conditionals). Part of the power of the CDFG comes from its combination of control and data constructs. To understand the CDFG, we start with pure data descriptions and then extend the model to control.

Data Flow Graphs
A data flow graph is a model of a program with no conditionals. In a high-level programming language, a code segment with no conditionals—more precisely, with only one entry and exit point—is known as a basic block. Figure 5-3 below shows a simple basic block. As the C code is executed, we would enter this basic block at the beginning and execute all the statements.

w = a + b;
x = a - c;
y = x+ d;
x = a + c;
z= y + e;

Figure 5-3. A basic block in C


Before we are able to draw the data flow graph for this code we need to modify it slightly. There are two assignments to the variable x - it appears twice on the left side of an assignment. We need to rewrite the code in single-assignment form, in which a variable appears only once on the left side.


Since our specification is C code, we assume that the statements are executed sequentially, so that any use of a variable refers to its latest assigned value. In this case, x is not reused in this block (presumably it is used elsewhere), so we just have to eliminate the multiple assignment to x . The result is shown in Figure 5-4 below, where we have used the names x1 and x2 to distinguish the separate uses of x.

w = a + b;
x1 = a - c;
y = x1 + d;
x2 = a + c;
z = y + e;

Figure 5-4. The basic block in single-assignment form.

The single-assignment form is important because it allows us to identify a unique location in the code where each named location is computed. As an introduction to the data flow graph, we use two types of nodes in the graph— round nodes denote operators and square nodes represent values. The value nodes may be either inputs to the basic block, such as a and b , or variables assigned to within the block, such as w and x1 . The data flow graph for our single-assignment code is shown in Figure 5-5 below.


The single-assignment form means that the data flow graph is acyclic—if we assigned to x multiple times, then the second assignment would form a cycle in the graph including x and the operators used to compute x .


Keeping the data flow graph acyclic is important in many types of analyses we want to do on the graph. (Of course, it is important to know whether the source code actually assigns to a variable multiple times, because some of those assignments may be mistakes. We consider the analysis of source code for proper use of assignments later in this series.)


Figure 5-5. An extended data flow graph for our sample block

The data flow graph is generally drawn in the form shown in Figure 5-6 below. Here, the variables are not explicitly represented by nodes. Instead, the edges are labeled with the variables they represent. As a result, a variable can be represented by more than one edge. However, the edges are directed and all the edges for a variable must come from a single source. We use this form for its simplicity and compactness.



Figure 5-6. Standard data flow graph for sample basic block

The data flow graph for the code makes the order in which the operations are performed in the C code much less obvious. This is one of the advantages of the data flow graph. We can use it to determine feasible reorderings of the operations, which may help us to reduce pipeline or cache conflicts.


We can also use it when the exact order of operations simply doesn't matter. The data flow graph defines a partial ordering of the operations in the basic block. We must ensure that a value is computed before it is used, but generally there are several possible orderings of evaluating expressions that satisfy this requirement.

Control/Data Flow Graphs
A CDFG uses a data flow graph as an element, adding constructs to describe control. In a basic CDFG, we have two types of nodes: decision nodes and data flow nodes.

A data flow node encapsulates a complete data flow graph to represent a basic block. We can use one type of decision node to describe all the types of control in a sequential program. (The jump/branch is, after all, the way we implement all those high-level control constructs.)

Figure 5-7 below shows a bit of C code with control constructs and the CDFG constructed from it. The rectangular nodes in the graph represent the basic blocks. The basic blocks in the C code have been represented by function calls for simplicity. The diamond-shaped nodes represent the conditionals. The node's condition is given by the label, and the edges are labeled with the possible outcomes of evaluating the condition.


Building a CDFG for a while loop is straightforward, as shown in Figure 5-8 below. The while loop consists of both a test and a loop body, each of which we know how to represent in a CDFG. We can represent for loops by remembering that, in C, a for loop is defined in terms of a while loop. The following for loop

for (i = 0; i < N; i++) {
loop_body();
}

is equivalent to

if (cond1) basic_block_1();else basic_block_2();basic_block_3();switch (test1) { case c1: basic_block_4(); break; case c2: basic_block_5(); break; case c3: basic_block_6(): break;}
C Code
Figure 5-7. C code (above) and its CDFG (below)







--------------------------------------------------------------------------------

i=0;while (iC Code

Figure 5-8. C code (above) and its CDFG (below) for a while loop.



Hierarchical representation. For a complete CDFG model, we can use a data flow graph to model each data flow node. Thus, the CDFG is a hierarchical representation—a data flow CDFG can be expanded to reveal a complete data flow graph. An execution model for a CDFG is very much like the execution of the program it represents. The CDFG does not require explicit declaration of variables, but we assume that the implementation has sufficient memory for all the variables.

We can define a state variable that represents a program counter in a CPU. (When studying a drawing of a CDFG, a finger works well for keeping track of the program counter state.) As we execute the program, we either execute the data flow node or compute the decision in the decision node and follow the appropriate edge, depending on the type of node the program counter points on.


Even though the data flow nodes may specify only a partial ordering on the data flow computations, the CDFG is a sequential representation of the program. There is only one program counter in our execution model of the CDFG, and operations are not executed in parallel.

The CDFG is not necessarily tied to high-level language control structures. We can also build a CDFG for an assembly language program. A jump instruction corresponds to a nonlocal edge in the CDFG. Some architectures, such as ARM and many VLIW processors, support predicated execution of instructions, which may be represented by special constructs in the CDFG.

Assembly and linking
Assembly and linking are the last steps in the compilation process—they turn a list of instructions into an image of the program's bits in memory. In this section, we survey the basic techniques required for assembly linking to help us understand the complete compilation process.

Figure 5-9 below highlights the role of assemblers and linkers in the compilation process. This process is often hidden from us by compilation commands that do everything required to generate an executable program. As the figure shows, most compilers do not directly generate machine code, but instead create the instruction-level program in the form of humanreadable assembly language.


Generating assembly language rather than binary instructions frees the compiler writer from details extraneous to the compilation process, which include the instruction format as well as the exact addresses of instructions and data. The assembler's job is to translate symbolic assembly language statements into bit-level representations of instructions known as object code.

The assembler takes care of instruction formats and does part of the job of translating labels into addresses. However, since the program may be built from many files, the final steps in determining the addresses of instructions and data are performed by the linker, which produces an executable binary file. That file may not necessarily be located in the CPU's memory, however, unless the linker happens to create the executable directly in RAM. The program that brings the program into memory for execution is called a loader.


Figure 5-9. Program generation from compilation through loading.

The simplest form of the assembler assumes that the starting address of the assembly language program has been specified by the programmer. The addresses in such a program are known as absolute addresses.


However, in many cases, particularly when we are creating an executable out of several component files, we do not want to specify the starting addresses for all the modules before assembly.


If we did, we would have to determine before assembly not only the length of each program in memory but also the order in which they would be linked into the program.


Most assemblers therefore allow us to use relative addresses by specifying at the start of the file that the origin of the assembly language module is to be computed later. Addresses within the module are then computed relative to the start of the module. The linker is then responsible for translating relative addresses into absolute addresses.

Assemblers. When translating assembly code into object code, the assembler must translate opcodes and format the bits in each instruction, and translate labels into addresses. In this section, we review the translation of assembly language into binary.

Labels make the assembly process more complex, but they are the most important abstraction provided by the assembler. Labels let the programmer (a human programmer or a compiler generating assembly code) avoid worrying about the absolute locations of instructions and data. Label processing requires making two passes through the assembly source code as follows:

1. The first pass scans the code to determine the address of each label.
2. The second pass assembles the instructions using the label values computed in the first pass.

As shown in Figure 5-10 below, the name of each symbol and its address is stored in a symbol table that is built during the first pass. The symbol table is built by scanning from the first instruction to the last. (For the moment, we assume that we know the absolute address of the first instruction in the program; we consider the general case later in this series).


During scanning, the current location in memory is kept in a program location counter (PLC). Despite the similarity in name to a program counter, the PLC is not used to execute the program, only to assign memory locations to labels. For example, the PLC always makes exactly one pass through the program, whereas the program counter makes many passes over code in a loop.


Thus, at the start of the first pass, the PLC is set to the program's starting address and the assembler looks at the first line. After examining the line, the assembler updates the PLC to the next location (since ARM instructions are four bytes long, the PLC would be incremented by four) and looks at the next instruction.


If the instruction begins with a label, a new entry is made in the symbol table, which includes the label name and its value. The value of the label is equal to the current value of the PLC. At the end of the first pass, the assembler rewinds to the beginning of the assembly language file to make the second pass. During the second pass, when a label name is found, the label is looked up in the symbol table and its value substituted into the appropriate place in the instruction.


Figure 5-10. Symbol table processing during assembly.

But how do we know the starting value of the PLC? The simplest case is absolute addressing. In this case, one of the first statements in the assembly language program is a pseudo-op that specifies the origin of the program, that is, the location of the first address in the program. A common name for this pseudo-op (e.g., the one used for the ARM) is the ORG statement

ORG 2000

which puts the start of the program at location 2000. This pseudo-op accomplishes this by setting the PLC's value to its argument's value, 2000 in this case. Assemblers generally allow a program to have many ORG statements in case instructions or data must be spread around various spots in memory. Example 5-1 below illustrates the use of the PLC in generating the symbol table.

Example 5-1: Generating a Symbol Table
Let's use the following simple example of ARM assembly code:
ORG 100 label1 ADR r4,c LDR r0,[r4] label2 ADR r4,d LDR r1,[r4] label3 SUB r0,r0,r1
The initial ORG statement tells us the starting address of the program. To begin, let's initialize the symbol table to an empty state and put the PLC at the initial ORG statement.



The PLC value shown is at the beginning of this step, before we have processed the ORG statement. The ORG tells us to set the PLC value to 100.



To process the next statement, we move the PLC to point to the next statement. But because the last statement was a pseudo-op that generates no memory values, the PLC value remains at 100.



Because there is a label in this statement, we add it to the symbol table, taking its value from the current PLC value.



To process the next statement, we advance the PLC to point to the next line of the program and increment its value by the length in memory of the last line, namely, 4.



We continue this process as we scan the program until we reach the end, at which the state of the PLC and symbol table are as shown below.



Assemblers allow labels to be added to the symbol table without occupying space in the program memory. A typical name of this pseudo-op is EQU for equate. For example, in the code

ADD r0,r1,r2FOO EQU 5BAZ SUB r3,r4,#FOO
the EQU pseudo-op adds a label named FOO with the value 5 to the symbol table. The value of the BAZ label is the same as if the EQU pseudo-op were not present, since EQU does not advance the PLC. The new label is used in the subsequent SUB instruction as the name for a constant. EQUs can be used to define symbolic values to help make the assembly code more structured.

The ARM assembler supports one pseudo-op that is particular to the ARM instruction set. In other architectures, an address would be loaded into a register (e.g., for an indirect access) by reading it from a memory location. ARM does not have an instruction that can load an effective address, so the assembler supplies the ADR pseudo-op to create the address in the register.


It does so by using ADD or SUB instructions to generate the address. The address to be loaded can be register relative, program relative, or numeric, but it must assemble to a single instruction. More complicated address calculations must be explicitly programmed.

The assembler produces an object file that describes the instructions and data in binary format. A commonly used object file format, originally developed for Unix but now used in other environments as well, is known as COFF (common object file format). The object file must describe the instructions, data, and any addressing information and also usually carries along the symbol table for later use in debugging.

Generating relative code rather than absolute code introduces some new challenges to the assembly language process. Rather than using an ORG statement to provide the starting address, the assembly code uses a pseudo-op to indicate that the code is in fact relocatable. (Relative code is the default for both the ARM and SHARC assemblers.)


Similarly, we must mark the output object file as being relative code. We can initialize the PLC to 0 to denote that addresses are relative to the start of the file. However, when we generate code that makes use of those labels, we must be careful, since we do not yet know the actual value that must be put into the bits.


We must instead generate relocatable code. We use extra bits in the object file format to mark the relevant fields as relocatable and then insert the label's relative value into the field.


The linker must therefore modify the generated code - when it finds a field marked as relative, it uses the absolute addresses that it has generated to replace the relative value with a correct, absolute value for the address. To understand the details of turning relocatable code into absolute executable code, we must understand the linking process described in the next section.

Linking. Many assembly language programs are written as several smaller pieces rather than as a single large file. Breaking a large program into smaller files helps delineate program modularity. If the program uses library routines, those will already be preassembled, and assembly language source code for the libraries may not be available for purchase.


A linker allows a program to be stitched together out of several smaller pieces. The linker operates on the object files created by the assembler and modifies the assembled code to make the necessary links between files.

Some labels will be both defined and used in the same file. Other labels will be defined in a single file but used elsewhere as illustrated in Figure 5-11 below. The place in the file where a label is defined is known as an entry point. The place in the file where the label is used is called an external reference.


The main job of the loader is to resolve external references based on available entry points. As a result of the need to know how definitions and references connect, the assembler passes to the linker not only the object file but also the symbol table. Even if the entire symbol table is not kept for later debugging purposes, it must at least pass the entry points. External references are identified in the object code by their relative symbol identifiers.


Figure 5-11. External references and entry points.


The linker proceeds in two phases. First, it determines the absolute address of the start of each object file. The order in which object files are to be loaded is given by the user, either by specifying parameters when the loader is run or by creating a load map file that gives the order in which files are to be placed in memory.


Given the order in which files are to be placed in memory and the length of each object file, it is easy to compute the absolute starting address of each file. At the start of the second phase, the loader merges all symbol tables from the object files into a single, large table. It then edits the object files to change relative addresses into absolute addresses.


This is typically performed by having the assembler write extra bits into the object file to identify the instructions and fields that refer to labels. If a label cannot be found in the merged symbol table, it is undefined and an error message is sent to the user.

Controlling where code modules are loaded into memory is important in embedded systems. Some data structures and instructions, such as those used to manage interrupts, must be put at precise memory locations for them to work. In other cases, different types of memory may be installed at different address ranges. For example, if we have EPROM in some locations and DRAM in others, we want to make sure that locations to be written are put in the DRAM locations.

Workstations and PCs provide dynamically linked libraries, and certain sophisticated embedded computing environments may provide them as well. Rather than link a separate copy of commonly used routines such as I/O to every executable program on the system, dynamically linked libraries allow them to be linked in at the start of program execution.


A brief linking process is run just before execution of the program begins; the dynamic linker uses code libraries to link in the required routines. This not only saves storage space but also allows programs that use those libraries to be easily updated. However, it does introduce a delay before the program starts executing.


Next, in Part 3: Basic compilation techniques.
To read Part 1, go to "Program design and analysis."


Used with the permission of the publisher, Newnes/Elsevier, this series of six articles is based on copyrighted material from "Computers as Components: Principles of Embedded Computer System Design" by Wayne Wolf. The book can be purchased on line.

Wayne Wolf is currently the Georgia Research Alliance Eminent Scholar holding the Rhesa "Ray" S. Farmer, Jr., Distinguished Chair in Embedded Computer Systems at Georgia Tech's School of Electrical and Computer Engineering (ECE). Previously a professor of electrical engineering at Princeton University, he worked at AT&T Bell Laboratories. He has served as editor in chief of the ACM Transactions on Embedded Computing and of Design Automation for Embedded Systems.


References:
[Dou99] Bruce Powell Douglas, Doing Hard Time: Developing Real Time Systems with UML. Addison Wesley, 1999.
[Chi94] M.Chiodo, et. al., "Hardware/software codesign of Embedded Systems," IEEE Micro, 1994


Copyright 2005 © CMP Media LLC

The basics of programming embedded processors: Part 1

http://www.embedded.com/showArticle.jhtml?articleID=201200638


Wayne Wolf, Embedded.com Jul 24 2007 (1:00 AM

Designing and implementing embedded programs is different and more challenging than writing typical workstation or PC programs. Embedded code must not only provide rich functionality, it must also often run at a required rate to meet system deadlines, fit into the allowed amount of memory, and meet power consumption requirements.
Designing code that simultaneously meets multiple design constraints is a considerable challenge, but luckily there are techniques and tools that we can use to help us through the design process. Making sure that the program works is also a challenge, but once again methods and tools come to our aid.
Presented in this series of six articles we will contentrate on high-level programming languages, specifically the C language. High-level languages were once shunned as too inefficient for embedded microcontrollers, but better compilers, more compilerfriendly architectures, and faster processors and memory have made highlevel language programs common.
Some sections of a program may still need to be written in assembly language if the compiler doesn't give sufficiently good results, but even when coding in assembly language it is often helpful to think about the program's functionality in high-level form. Many of the analysis and optimization techniques that we study in this chapter are equally applicable to programs written in assembly language.
Future parts in this series will discuss (1) the control/data flow graph as a model for high-level language programs (which can also be applied to programs written originally in assembly language) with a particular focus on design patterns; (2) the assembly and linking process; (3) the basic steps in compilation; (4) optimization techniques specific to embedded computing for energy consumption, performance and size.Design PatternsA design pattern is a generalized description of a way to solve a certain class of problems. As a simple example, we could write C code for one implementation of a linked list, but that code would set in concrete the data items available in the list, actions on errors, and so on. A design pattern describing the list mechanism would capture the essential components and behaviors of the list without adding unnecessary detail. A design pattern can be described in the Unified Modeling Language (UML); it usually takes the form of a collaboration diagram, which shows how classes work together to perform a given function.
Figure 5-1 below shows a simple description of a design pattern as a UML class diagram. The diagram defines two classes: List to describe the entire list and List-element for one of the items in the list. The List class defines the basic operations that you want to do on a list.
The details of what goes in the list and so forth can be easily added into this design pattern. A design pattern can be parameterized so that it can be customized to the needs of a particular application. A more complete description of the pattern might include
state diagrams to describe behavior and
sequence diagrams to show how classes interact.
Figure 5-1. A simple description of a design pattern
Design patterns are primarily intended to help solve midlevel design challenges. A design pattern may include only a single class, but it usually describes a handful of classes.
Design patterns rarely include more than a few dozen classes. A design pattern probably will not provide you with the complete architecture of your system, but it can provide you with the architectures for many subsystems in your design:
By stitching together and specializing existing design patterns, you may be able to quickly create a large part of your system architecture.
Design patterns are meant to be used in ways similar to how engineers in other disciplines work. A designer can consult catalogs of design patterns to find patterns that seem to fit a particular design problem.
The designer can then choose parameters suited to the application and see what that implies for the implementation of the design pattern. The designer can then choose the design pattern that seems to be the best match for the design, parameterize it, and instantiate it.
Design patterns can be of many different types. A few are listed below.
The digital filter is easily described as a design pattern.
Data structures and their associated actions can be described as design patterns.
A reactive system that reacts to external stimuli can be described as a design pattern, leaving the exact state transition diagram as a parameter.
Douglass [Dou99] describes a policy class that describes a protocol that can be used to implement a variety of policies.
Design Patterns for Embedded SystemsIn this section, we consider design patterns for two very different styles of programs: the state machine and the circular buffer. State machines are well suited to reactive systems such as user interfaces, and circular buffers are useful in digital signal processing.
State machine style. When inputs appear intermittently rather than as periodic samples, it is often convenient to think of the system as reacting to those inputs. The reaction of most systems can be characterized in terms of the input received and the current state of the system. This leads naturally to a finite-state machine style of describing the reactive system's behavior.
Moreover, if the behavior is specified in that way, it is natural to write the program implementing that behavior in a state machine style. The state machine style of programming is also an efficient implementation of such computations.
Finite-state machines are usually first encountered in the context of hardware design.The programming example describe below shows how to write a finite-state machine in a high-level programming language.
Programming Example: A state machine in CThe behavior we want to implement is a simple seat belt controller [Chi94]. The controller's job is to turn on a buzzer if a person sits in a seat and does not fasten the seat belt within a fixed amount of time. This system has three inputs and one output.
The inputs are a sensor for the seat to know when a person has sat down, a seat belt sensor that tells when the belt is fastened, and a timer that goes off when the required time interval has elapsed. The output is the buzzer. Shown below is a state diagram that describes the seat belt controller's behavior.
The idle state is in force when there is no person in the seat. When the person sits down, the machine goes into the seated state and turns on the timer. If the timer goes off before the seat belt is fastened, the machine goes into the buzzer state. If the seat belt goes on first, it enters the belted state. When the person leaves the seat, the machine goes back to idle.
To write this behavior in C, we will assume that we have loaded the current values of all three inputs ( seat , belt , timer ) into variables and will similarly hold the outputs in variables temporarily ( timer_on , buzzer_on ). We will use a variable named state to hold the current state of the machine and a switch statement to determine what action to take in each state. The code follows: #define IDLE 0 #define SEATED 1 #define BELTED 2 #define BUZZER 3
This code takes advantage of the fact that the state will remain the same unless explicitly changed; this makes self-loops back to the same state easy to implement.
This state machine may be executed forever in a while(TRUE) loop or periodically called by some other code. In either case, the code must be executed regularly so that it can check on the current value of the inputs and, if necessary, go into a new state.
Data stream style. The data stream style makes sense for data that comes in regularly and must be processed on the fly. The FIR filter of the example shown above is a classic example of stream-oriented processing. For each sample, the filter must emit one output that depends on the values of the last n inputs.
In a typical workstation application, we would process the samples over a given interval by reading them all in from a file and then computing the results all at once in a batch process. In an embedded system we must not only emit outputs in real time, but we must also do so using a minimum amount of memory.
The circular buffer is a data structure that lets us handle streaming data in an efficient way. Figure 5-2 below illustrates how a circular buffer stores a subset of the data stream. At each point in time, the algorithm needs a subset of the data stream that forms a window into the stream.
The window slides with time as we throw out old values no longer needed and add new values. Since the size of the window does not change, we can use a fixed-size buffer to hold the current data.
Figure 5-2. A circular buffer for streaming data
To avoid constantly copying data within the buffer, we will move the head of the buffer in time. The buffer points to the location at which the next sample will be placed; every time we add a sample, we automatically overwrite the oldest sample, which is the one that needs to be thrown out.
When the pointer gets to the end of the buffer, it wraps around to the top. Described below is an example of an efficient implementation of a circular buffer.
Programming Example: A circular buffer for an FIR filterAppearing below are the declarations for the circular buffer and filter coefficients, assuming that N , the number of taps in the filter, has been previously defined. int circ_buffer[N]; /* circular buffer for data */ int circ_buffer_head = 0; /* current head of the buffer */ int c[N]; /* filter coefficients (constants) */
To write C code for a circular buffer-based FIR filter, we need to modify the original loop slightly. Because the 0th element of data may not be in the 0th element of the circular buffer, we have to change the way in which we access the data. One of the implications of this is that we need separate loop indices for the circular buffer and coefficients.
The above code assumes that some other code, such as an interrupt handler, is replacing the last element of the circular buffer at the appropriate times. The statement 1buff = (ibuff == (N " 1) ? 0 : ibuff++) is a shorthand C way of incrementing ibuff such that it returns to 0 after reaching the end of the circular buffer array.
Next in Part 2: Models of programs.
Used with the permission of the publisher, Newnes/Elsevier, this series of six articles is based on copyrighted material from "Computers as Components: Principles of Embedded Computer System Design" by Wayne Wolf. The book can be purchased on line.
Wayne Wolf is currently the Georgia Research Alliance Eminent Scholar holding the Rhesa "Ray" S. Farmer, Jr., Distinguished Chair in Embedded Computer Systems at Georgia Tech's School of Electrical and Computer Engineering (ECE). Previously a professor of electrical engineering at Princeton University, he worked at AT&T Bell Laboratories. He has served as editor in chief of the ACM Transactions on Embedded Computing and of Design Automation for Embedded Systems.
References:[Dou99] Bruce Powell Douglas, Doing Hard Time: Developing Real Time Systems with UML. Addison Wesley, 1999.[Chi94] M.Chiodo, et. al., "Hardware/software codesign of Embedded Systems," IEEE Micro, 1994
Copyright 2005 © CMP Media LLC

Thursday, July 19, 2007

The Smurfit-Stone Building in Chicago from Millennium Park




Smurfit-Stone Building
Designed by: A. Epstein and Sons
Construction Completed: 1984
Area: The Loop
Post Code: 60601
City: Chicago, Illinois
One of Chicago's signature skyscrapers, what the Smurfit-Stone building lacks in height, it more than makes up for in style.

How to become an Embedded Geek

http://www.ganssle.com/startinges.pdf

Basics of ADCs and DACs, part 1

By Walt Kester and James Bryant, Analog Devices, Courtesy of DSP DesignLine
Jul 19 2007 (3:00 AM)

Introduction
Prior to the actual analog-to-digital conversion, the analog signal usually passes through some sort of signal conditioning circuitry, which performs such functions as amplification, attenuation, and filtering. The low-pass/band-pass filter is required to remove unwanted signals outside the bandwidth of interest and prevent aliasing
http://www.embedded.com/showArticle.jhtml?articleID=201002320

[Part 2 explains how ADCs and DACs introduce noise through quantization errors, offsets errors, and other "DC" errors. It will be published Thursday, July 26.]

802.11 -1999 IEEE Standard

http://standards.ieee.org/getieee802/download/802.11-1999.pdf

The Resonant Chamber

Tuesday, June 12, 2007

The Fine Art of Statecraft

By Dennis Ross
U.S. News & World Report, June 10, 2007

When one looks at U.S. foreign policy and our standing in the world today, it is hard to escape the conclusion that the Bush administration has not exactly excelled in the exercise of statecraft. Good statecraft matches objectives and means. Poor statecraft does not.
Look at the administration's signature issues -- Iraq and democratic transformation in the Middle East -- and one sees poster children for ambitious objectives married to minimalist means. Part of the problem has been the instinct to try to get by on the cheap. More basically, however, the problem has been the administration's tendency to rely on faith-based, not reality-based, assessments. Too often objectives have been shaped by a world that the administration wants to believe exists or can be easily created.

If the administration had more of a negotiating mind-set, it would have understood the importance of seeing the world as it truly is. That does not require settling for the status quo. Those with a negotiating mind-set believe they can solve problems even if they don't believe every problem can be solved. They realize they have to understand each and every reality, no matter how unacceptable, before they can try to change it.

That is why those with negotiating mind-sets know it is essential to set clear objectives and identify the means to achieve them. They also understand the importance of leverage: One always wants the other side to think it needs a deal more than your side. Had Secretary of State Condoleezza Rice been governed by a negotiating mind-set, would she have issued several public calls for the Iranians to send their foreign minister to the recent Sharm al-Sheikh conference on Iraq? Consider that the Iranians weren't equivocating on attending, just on the level of representation. To Iranian (and other Middle Eastern) ears, Rice seemed to be pleading for the Iranian foreign minister to come -- in effect saying we need you more than you need us.

Statecraft, like negotiations, is about understanding both our leverage and our adversaries' vulnerabilities. Often our allies may have far more leverage, and we have to find ways to shape objectives that they share. We need to frame them publicly in a way that makes it easier for them to embrace, to orchestrate with them how best to exercise pressure as well as inducements, and to recognize that a readiness to engage with adversaries often makes it easier for our allies to take tougher steps that add to our leverage.

Iran is a good case in point. The Iranians have high unemployment, high inflation, and declining oil and natural gas output, their chief sources of revenue. To preserve social peace, they use the revenues they generate from oil and natural gas exports to subsidize consumer goods in Iran. The Iranian vulnerabilities are very clear, and the Bush administration, to its credit, has focused on generating United Nations Security Council sanctions to persuade the Iranian regime of the high price it is going to pay for continuing with its nuclear program.

Slow motion. That's the good news; now the bad. Iran is not changing its behavior. We have the right objective in trying to stop the Iranian nuclear program. But we have a mismatch between that goal and the means we are using: We are employing slow-motion diplomacy at the Security Council while the Iranians have a fast-paced nuclear development program. It's time to go outside the Security Council and persuade our European allies to move beyond incremental pressures and actually cut their economic lifeline to Iran such as the billions of dollars in credit guarantees to companies doing business with Tehran.

How to convince the European Union? Statecraft. Convey to the Europeans that unless economic pressure is dramatically increased now, the use of force to stop the Iranian nuclear program will become more, not less, likely. To make economic pressure more palatable to the Europeans, let them know that once the new penalties are in place, we will join them in direct negotiations with Iran -- something they believe is the key to overcoming the crisis with Iran.

Ultimately, statecraft is about clarity, communication, intensive engagement, and knowing how to apply leverage. It is time to restore it to U.S. foreign policy.

A former Mideast negotiator, Ambassador Ross is author of Statecraft and How to Restore America's Standing in the World, published this month by Farrar, Straus, and Giroux.

This story appears in the June 18, 2007 print edition of U.S. News & World Report.

Read this op-ed at U.S. News & World Report

Saturday, February 10, 2007

Full Text of Senator Barack Obama's Announcement for President

Springfield, IL | February 10, 2007

Let me begin by saying thanks to all you who've traveled, from far and wide, to brave the cold today.

We all made this journey for a reason. It's humbling, but in my heart I know you didn't come here just for me, you came here because you believe in what this country can be. In the face of war, you believe there can be peace. In the face of despair, you believe there can be hope. In the face of a politics that's shut you out, that's told you to settle, that's divided us for too long, you believe we can be one people, reaching for what's possible, building that more perfect union.

That's the journey we're on today. But let me tell you how I came to be here. As most of you know, I am not a native of this great state. I moved to Illinois over two decades ago. I was a young man then, just a year out of college; I knew no one in Chicago, was without money or family connections. But a group of churches had offered me a job as a community organizer for $13,000 a year. And I accepted the job, sight unseen, motivated then by a single, simple, powerful idea - that I might play a small part in building a better America.

My work took me to some of Chicago's poorest neighborhoods. I joined with pastors and lay-people to deal with communities that had been ravaged by plant closings. I saw that the problems people faced weren't simply local in nature - that the decision to close a steel mill was made by distant executives; that the lack of textbooks and computers in schools could be traced to the skewed priorities of politicians a thousand miles away; and that when a child turns to violence, there's a hole in his heart no government could ever fill.

It was in these neighborhoods that I received the best education I ever had, and where I learned the true meaning of my Christian faith.

After three years of this work, I went to law school, because I wanted to understand how the law should work for those in need. I became a civil rights lawyer, and taught constitutional law, and after a time, I came to understand that our cherished rights of liberty and equality depend on the active participation of an awakened electorate. It was with these ideas in mind that I arrived in this capital city as a state Senator.

It was here, in Springfield, where I saw all that is America converge - farmers and teachers, businessmen and laborers, all of them with a story to tell, all of them seeking a seat at the table, all of them clamoring to be heard. I made lasting friendships here - friends that I see in the audience today.

It was here we learned to disagree without being disagreeable - that it's possible to compromise so long as you know those principles that can never be compromised; and that so long as we're willing to listen to each other, we can assume the best in people instead of the worst.

That's why we were able to reform a death penalty system that was broken. That's why we were able to give health insurance to children in need. That's why we made the tax system more fair and just for working families, and that's why we passed ethics reforms that the cynics said could never, ever be passed.

It was here, in Springfield, where North, South, East and West come together that I was reminded of the essential decency of the American people - where I came to believe that through this decency, we can build a more hopeful America.

And that is why, in the shadow of the Old State Capitol, where Lincoln once called on a divided house to stand together, where common hopes and common dreams still, I stand before you today to announce my candidacy for President of the United States.

I recognize there is a certain presumptuousness - a certain audacity - to this announcement. I know I haven't spent a lot of time learning the ways of Washington. But I've been there long enough to know that the ways of Washington must change.

The genius of our founders is that they designed a system of government that can be changed. And we should take heart, because we've changed this country before. In the face of tyranny, a band of patriots brought an Empire to its knees. In the face of secession, we unified a nation and set the captives free. In the face of Depression, we put people back to work and lifted millions out of poverty. We welcomed immigrants to our shores, we opened railroads to the west, we landed a man on the moon, and we heard a King's call to let justice roll down like water, and righteousness like a mighty stream.

Each and every time, a new generation has risen up and done what's needed to be done. Today we are called once more - and it is time for our generation to answer that call.

For that is our unyielding faith - that in the face of impossible odds, people who love their country can change it.

That's what Abraham Lincoln understood. He had his doubts. He had his defeats. He had his setbacks. But through his will and his words, he moved a nation and helped free a people. It is because of the millions who rallied to his cause that we are no longer divided, North and South, slave and free. It is because men and women of every race, from every walk of life, continued to march for freedom long after Lincoln was laid to rest, that today we have the chance to face the challenges of this millennium together, as one people - as Americans.

All of us know what those challenges are today - a war with no end, a dependence on oil that threatens our future, schools where too many children aren't learning, and families struggling paycheck to paycheck despite working as hard as they can. We know the challenges. We've heard them. We've talked about them for years.

What's stopped us from meeting these challenges is not the absence of sound policies and sensible plans. What's stopped us is the failure of leadership, the smallness of our politics - the ease with which we're distracted by the petty and trivial, our chronic avoidance of tough decisions, our preference for scoring cheap political points instead of rolling up our sleeves and building a working consensus to tackle big problems.

For the last six years we've been told that our mounting debts don't matter, we've been told that the anxiety Americans feel about rising health care costs and stagnant wages are an illusion, we've been told that climate change is a hoax, and that tough talk and an ill-conceived war can replace diplomacy, and strategy, and foresight. And when all else fails, when Katrina happens, or the death toll in Iraq mounts, we've been told that our crises are somebody else's fault. We're distracted from our real failures, and told to blame the other party, or gay people, or immigrants.

And as people have looked away in disillusionment and frustration, we know what's filled the void. The cynics, and the lobbyists, and the special interests who've turned our government into a game only they can afford to play. They write the checks and you get stuck with the bills, they get the access while you get to write a letter, they think they own this government, but we're here today to take it back. The time for that politics is over. It's time to turn the page.

We've made some progress already. I was proud to help lead the fight in Congress that led to the most sweeping ethics reform since Watergate.

But Washington has a long way to go. And it won't be easy. That's why we'll have to set priorities. We'll have to make hard choices. And although government will play a crucial role in bringing about the changes we need, more money and programs alone will not get us where we need to go. Each of us, in our own lives, will have to accept responsibility - for instilling an ethic of achievement in our children, for adapting to a more competitive economy, for strengthening our communities, and sharing some measure of sacrifice. So let us begin. Let us begin this hard work together. Let us transform this nation.

Let us be the generation that reshapes our economy to compete in the digital age. Let's set high standards for our schools and give them the resources they need to succeed. Let's recruit a new army of teachers, and give them better pay and more support in exchange for more accountability. Let's make college more affordable, and let's invest in scientific research, and let's lay down broadband lines through the heart of inner cities and rural towns all across America.

And as our economy changes, let's be the generation that ensures our nation's workers are sharing in our prosperity. Let's protect the hard-earned benefits their companies have promised. Let's make it possible for hardworking Americans to save for retirement. And let's allow our unions and their organizers to lift up this country's middle-class again.

Let's be the generation that ends poverty in America. Every single person willing to work should be able to get job training that leads to a job, and earn a living wage that can pay the bills, and afford child care so their kids have a safe place to go when they work. Let's do this.

Let's be the generation that finally tackles our health care crisis. We can control costs by focusing on prevention, by providing better treatment to the chronically ill, and using technology to cut the bureaucracy. Let's be the generation that says right here, right now, that we will have universal health care in America by the end of the next president's first term.

Let's be the generation that finally frees America from the tyranny of oil. We can harness homegrown, alternative fuels like ethanol and spur the production of more fuel-efficient cars. We can set up a system for capping greenhouse gases. We can turn this crisis of global warming into a moment of opportunity for innovation, and job creation, and an incentive for businesses that will serve as a model for the world. Let's be the generation that makes future generations proud of what we did here.

Most of all, let's be the generation that never forgets what happened on that September day and confront the terrorists with everything we've got. Politics doesn't have to divide us on this anymore - we can work together to keep our country safe. I've worked with Republican Senator Dick Lugar to pass a law that will secure and destroy some of the world's deadliest, unguarded weapons. We can work together to track terrorists down with a stronger military, we can tighten the net around their finances, and we can improve our intelligence capabilities. But let us also understand that ultimate victory against our enemies will come only by rebuilding our alliances and exporting those ideals that bring hope and opportunity to millions around the globe.

But all of this cannot come to pass until we bring an end to this war in Iraq. Most of you know I opposed this war from the start. I thought it was a tragic mistake. Today we grieve for the families who have lost loved ones, the hearts that have been broken, and the young lives that could have been. America, it's time to start bringing our troops home. It's time to admit that no amount of American lives can resolve the political disagreement that lies at the heart of someone else's civil war. That's why I have a plan that will bring our combat troops home by March of 2008. Letting the Iraqis know that we will not be there forever is our last, best hope to pressure the Sunni and Shia to come to the table and find peace.

Finally, there is one other thing that is not too late to get right about this war - and that is the homecoming of the men and women - our veterans - who have sacrificed the most. Let us honor their valor by providing the care they need and rebuilding the military they love. Let us be the generation that begins this work.

I know there are those who don't believe we can do all these things. I understand the skepticism. After all, every four years, candidates from both parties make similar promises, and I expect this year will be no different. All of us running for president will travel around the country offering ten-point plans and making grand speeches; all of us will trumpet those qualities we believe make us uniquely qualified to lead the country. But too many times, after the election is over, and the confetti is swept away, all those promises fade from memory, and the lobbyists and the special interests move in, and people turn away, disappointed as before, left to struggle on their own.

That is why this campaign can't only be about me. It must be about us - it must be about what we can do together. This campaign must be the occasion, the vehicle, of your hopes, and your dreams. It will take your time, your energy, and your advice - to push us forward when we're doing right, and to let us know when we're not. This campaign has to be about reclaiming the meaning of citizenship, restoring our sense of common purpose, and realizing that few obstacles can withstand the power of millions of voices calling for change.

By ourselves, this change will not happen. Divided, we are bound to fail.

But the life of a tall, gangly, self-made Springfield lawyer tells us that a different future is possible.

He tells us that there is power in words.

He tells us that there is power in conviction.

That beneath all the differences of race and region, faith and station, we are one people.

He tells us that there is power in hope.

As Lincoln organized the forces arrayed against slavery, he was heard to say: "Of strange, discordant, and even hostile elements, we gathered from the four winds, and formed and fought to battle through."

That is our purpose here today.

That's why I'm in this race.

Not just to hold an office, but to gather with you to transform a nation.

I want to win that next battle - for justice and opportunity.

I want to win that next battle - for better schools, and better jobs, and health care for all.

I want us to take up the unfinished business of perfecting our union, and building a better America.

And if you will join me in this improbable quest, if you feel destiny calling, and see as I see, a future of endless possibility stretching before us; if you sense, as I sense, that the time is now to shake off our slumber, and slough off our fear, and make good on the debt we owe past and future generations, then I'm ready to take up the cause, and march with you, and work with you. Together, starting today, let us finish the work that needs to be done, and usher in a new birth of freedom on this Earth.

Sunday, January 21, 2007

2008 Democratic Presedential Primary in the Web Information Age

Senators Hillary Rodam Clinton and Barack Obama have announced their intent to run for their party's 2008 presenential nomination.

Both are strong canidates within the Democratic Party.
Hillary's deep grasp of domestic and foreign policy issues vs. Barack's academicly tempered optimisim and general vision for change.

The talking heads seem to doubt the depth of Barrack's knowledge on the major issues facing this nation. I suspect this because those ideas are not enumerated on his presential exploratory committee website relative to Hilary's site. However his Illinois senate website is much more mature. Obama Senate Site: On The Issues:

Barack Obama Predential Exploratory Committee

Hillary Clinton Presedential Exploratory Committee