Simplify the first example, as the LLVM IR interfaces have evolved. Other
[oota-llvm.git] / docs / Stacker.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
2                       "http://www.w3.org/TR/html4/strict.dtd">
3 <html>
4 <head>
5   <title>Stacker: An Example Of Using LLVM</title>
6   <link rel="stylesheet" href="llvm.css" type="text/css">
7   <style>
8     table, tr, td { border: 2px solid gray }
9     table { border-collapse: collapse; margin-bottom: 2em }
10   </style>
11 </head>
12 <body>
13
14 <div class="doc_title">Stacker: An Example Of Using LLVM</div>
15
16 <ol>
17   <li><a href="#abstract">Abstract</a></li>
18   <li><a href="#introduction">Introduction</a></li>
19   <li><a href="#lessons">Lessons I Learned About LLVM</a>
20     <ol>
21       <li><a href="#value">Everything's a Value!</a></li>
22       <li><a href="#terminate">Terminate Those Blocks!</a></li>
23       <li><a href="#blocks">Concrete Blocks</a></li>
24       <li><a href="#push_back">push_back Is Your Friend</a></li>
25       <li><a href="#gep">The Wily GetElementPtrInst</a></li>
26       <li><a href="#linkage">Getting Linkage Types Right</a></li>
27       <li><a href="#constants">Constants Are Easier Than That!</a></li>
28     </ol></li>
29   <li><a href="#lexicon">The Stacker Lexicon</a>
30     <ol>
31       <li><a href="#stack">The Stack</a></li>
32       <li><a href="#punctuation">Punctuation</a></li>
33       <li><a href="#comments">Comments</a></li>
34       <li><a href="#literals">Literals</a></li>
35       <li><a href="#words">Words</a></li>
36       <li><a href="#style">Standard Style</a></li>
37       <li><a href="#builtins">Built-Ins</a></li>
38     </ol></li>
39   <li><a href="#example">Prime: A Complete Example</a></li>
40   <li><a href="#internal">Internal Code Details</a>
41     <ol>
42       <li><a href="#directory">The Directory Structure </a></li>
43       <li><a href="#lexer">The Lexer</a></li>
44       <li><a href="#parser">The Parser</a></li>
45       <li><a href="#compiler">The Compiler</a></li>
46       <li><a href="#runtime">The Runtime</a></li>
47       <li><a href="#driver">Compiler Driver</a></li>
48       <li><a href="#tests">Test Programs</a></li>
49       <li><a href="#exercise">Exercise</a></li>
50       <li><a href="#todo">Things Remaining To Be Done</a></li>
51     </ol></li>
52 </ol>
53
54 <div class="doc_author">
55   <p>Written by <a href="mailto:rspencer@x10sys.com">Reid Spencer</a></p>
56 </div>
57
58 <!-- ======================================================================= -->
59 <div class="doc_section"><a name="abstract">Abstract</a></div>
60 <div class="doc_text">
61 <p>This document is another way to learn about LLVM. Unlike the 
62 <a href="LangRef.html">LLVM Reference Manual</a> or 
63 <a href="ProgrammersManual.html">LLVM Programmer's Manual</a>, here we learn
64 about LLVM through the experience of creating a simple programming language
65 named Stacker.  Stacker was invented specifically as a demonstration of
66 LLVM. The emphasis in this document is not on describing the
67 intricacies of LLVM itself but on how to use it to build your own
68 compiler system.</p>
69 </div>
70 <!-- ======================================================================= -->
71 <div class="doc_section"> <a name="introduction">Introduction</a> </div>
72 <div class="doc_text">
73 <p>Amongst other things, LLVM is a platform for compiler writers.
74 Because of its exceptionally clean and small IR (intermediate
75 representation), compiler writing with LLVM is much easier than with
76 other system. As proof, I wrote the entire compiler (language definition, 
77 lexer, parser, code generator, etc.) in about <em>four days</em>! 
78 That's important to know because it shows how quickly you can get a new
79 language running when using LLVM. Furthermore, this was the <em >first</em> 
80 language the author ever created using LLVM. The learning curve is 
81 included in that four days.</p>
82 <p>The language described here, Stacker, is Forth-like. Programs
83 are simple collections of word definitions, and the only thing definitions
84 can do is manipulate a stack or generate I/O.  Stacker is not a "real" 
85 programming language; it's very simple.  Although it is computationally 
86 complete, you wouldn't use it for your next big project. However, 
87 the fact that it is complete, it's simple, and it <em>doesn't</em> have 
88 a C-like syntax make it useful for demonstration purposes. It shows
89 that LLVM could be applied to a wide variety of languages.</p>
90 <p>The basic notions behind stacker is very simple. There's a stack of 
91 integers (or character pointers) that the program manipulates. Pretty 
92 much the only thing the program can do is manipulate the stack and do 
93 some limited I/O operations. The language provides you with several 
94 built-in words that manipulate the stack in interesting ways. To get 
95 your feet wet, here's how you write the traditional "Hello, World" 
96 program in Stacker:</p>
97 <p><code>: hello_world "Hello, World!" &gt;s DROP CR ;<br>
98 : MAIN hello_world ;<br></code></p>
99 <p>This has two "definitions" (Stacker manipulates words, not
100 functions and words have definitions): <code>MAIN</code> and <code>
101 hello_world</code>. The <code>MAIN</code> definition is standard; it
102 tells Stacker where to start. Here, <code>MAIN</code> is defined to 
103 simply invoke the word <code>hello_world</code>. The
104 <code>hello_world</code> definition tells stacker to push the 
105 <code>"Hello, World!"</code> string on to the stack, print it out 
106 (<code>&gt;s</code>), pop it off the stack (<code>DROP</code>), and
107 finally print a carriage return (<code>CR</code>). Although 
108 <code>hello_world</code> uses the stack, its net effect is null. Well
109 written Stacker definitions have that characteristic. </p>
110 <p>Exercise for the reader: how could you make this a one line program?</p>
111 </div>
112 <!-- ======================================================================= -->
113 <div class="doc_section"><a name="lessons"></a>Lessons I Learned About LLVM</div>
114 <div class="doc_text">
115 <p>Stacker was written for two purposes: </p>
116 <ol>
117     <li>to get the author over the learning curve, and</li>
118     <li>to provide a simple example of how to write a compiler using LLVM.</li>
119 </ol>
120 <p>During the development of Stacker, many lessons about LLVM were
121 learned. Those lessons are described in the following subsections.<p>
122 </div>
123 <!-- ======================================================================= -->
124 <div class="doc_subsection"><a name="value"></a>Everything's a Value!</div>
125 <div class="doc_text">
126 <p>Although I knew that LLVM uses a Single Static Assignment (SSA) format, 
127 it wasn't obvious to me how prevalent this idea was in LLVM until I really
128 started using it.  Reading the <a href="ProgrammersManual.html">
129 Programmer's Manual</a> and <a href="LangRef.html">Language Reference</a>,
130 I noted that most of the important LLVM IR (Intermediate Representation) C++ 
131 classes were derived from the Value class. The full power of that simple
132 design only became fully understood once I started constructing executable
133 expressions for Stacker.</p>
134
135 <p>This really makes your programming go faster. Think about compiling code
136 for the following C/C++ expression: <code>(a|b)*((x+1)/(y+1))</code>. Assuming
137 the values are on the stack in the order a, b, x, y, this could be
138 expressed in stacker as: <code>1 + SWAP 1 + / ROT2 OR *</code>.
139 You could write a function using LLVM that computes this expression like 
140 this: </p>
141
142 <div class="doc_code"><pre>
143 Value* 
144 expression(BasicBlock* bb, Value* a, Value* b, Value* x, Value* y )
145 {
146     ConstantSInt* one = ConstantSInt::get(Type::IntTy, 1);
147     BinaryOperator* or1 = BinaryOperator::createOr(a, b, "", bb);
148     BinaryOperator* add1 = BinaryOperator::createAdd(x, one, "", bb);
149     BinaryOperator* add2 = BinaryOperator::createAdd(y, one, "", bb);
150     BinaryOperator* div1 = BinaryOperator::createDiv(add1, add2, "", bb);
151     BinaryOperator* mult1 = BinaryOperator::createMul(or1, div1, "", bb);
152     return mult1;
153 }
154 </pre></div>
155
156 <p>"Okay, big deal," you say?  It is a big deal. Here's why. Note that I didn't
157 have to tell this function which kinds of Values are being passed in. They could be
158 <code>Instruction</code>s, <code>Constant</code>s, <code>GlobalVariable</code>s, or
159 any of the other subclasses of <code>Value</code> that LLVM supports.
160 Furthermore, if you specify Values that are incorrect for this sequence of 
161 operations, LLVM will either notice right away (at compilation time) or the LLVM 
162 Verifier will pick up the inconsistency when the compiler runs. In either case 
163 LLVM prevents you from making a type error that gets passed through to the 
164 generated program.  This <em>really</em> helps you write a compiler that 
165 always generates correct code!<p>
166 <p>The second point is that we don't have to worry about branching, registers,
167 stack variables, saving partial results, etc. The instructions we create 
168 <em>are</em> the values we use. Note that all that was created in the above
169 code is a Constant value and five operators. Each of the instructions <em>is</em> 
170 the resulting value of that instruction. This saves a lot of time.</p>
171 <p>The lesson is this: <em>SSA form is very powerful: there is no difference
172 between a value and the instruction that created it.</em> This is fully
173 enforced by the LLVM IR. Use it to your best advantage.</p>
174 </div>
175 <!-- ======================================================================= -->
176 <div class="doc_subsection"><a name="terminate"></a>Terminate Those Blocks!</div>
177 <div class="doc_text">
178 <p>I had to learn about terminating blocks the hard way: using the debugger 
179 to figure out what the LLVM verifier was trying to tell me and begging for
180 help on the LLVMdev mailing list. I hope you avoid this experience.</p>
181 <p>Emblazon this rule in your mind:</p>
182 <ul>
183     <li><em>All</em> <code>BasicBlock</code>s in your compiler <b>must</b> be
184         terminated with a terminating instruction (branch, return, etc.).
185     </li>
186 </ul>
187 <p>Terminating instructions are a semantic requirement of the LLVM IR. There
188 is no facility for implicitly chaining together blocks placed into a function
189 in the order they occur. Indeed, in the general case, blocks will not be
190 added to the function in the order of execution because of the recursive
191 way compilers are written.</p>
192 <p>Furthermore, if you don't terminate your blocks, your compiler code will 
193 compile just fine. You won't find out about the problem until you're running 
194 the compiler and the module you just created fails on the LLVM Verifier.</p>
195 </div>
196 <!-- ======================================================================= -->
197 <div class="doc_subsection"><a name="blocks"></a>Concrete Blocks</div>
198 <div class="doc_text">
199 <p>After a little initial fumbling around, I quickly caught on to how blocks
200 should be constructed. In general, here's what I learned:
201 <ol>
202     <li><em>Create your blocks early.</em> While writing your compiler, you 
203     will encounter several situations where you know apriori that you will
204     need several blocks. For example, if-then-else, switch, while, and for
205     statements in C/C++ all need multiple blocks for expression in LVVM. 
206     The rule is, create them early.</li>
207     <li><em>Terminate your blocks early.</em> This just reduces the chances 
208     that you forget to terminate your blocks which is required (go 
209     <a href="#terminate">here</a> for more). 
210     <li><em>Use getTerminator() for instruction insertion.</em> I noticed early on
211     that many of the constructors for the Instruction classes take an optional
212     <code>insert_before</code> argument. At first, I thought this was a mistake
213     because clearly the normal mode of inserting instructions would be one at
214     a time <em>after</em> some other instruction, not <em>before</em>. However,
215     if you hold on to your terminating instruction (or use the handy dandy
216     <code>getTerminator()</code> method on a <code>BasicBlock</code>), it can
217     always be used as the <code>insert_before</code> argument to your instruction
218     constructors. This causes the instruction to automatically be inserted in 
219     the RightPlace&trade; place, just before the terminating instruction. The 
220     nice thing about this design is that you can pass blocks around and insert 
221     new instructions into them without ever knowing what instructions came 
222     before. This makes for some very clean compiler design.</li>
223 </ol>
224 <p>The foregoing is such an important principal, its worth making an idiom:</p>
225 <pre>
226 BasicBlock* bb = new BasicBlock();
227 bb->getInstList().push_back( new Branch( ... ) );
228 new Instruction(..., bb->getTerminator() );
229 </pre>
230 <p>To make this clear, consider the typical if-then-else statement
231 (see StackerCompiler::handle_if() method).  We can set this up
232 in a single function using LLVM in the following way: </p>
233 <pre>
234 using namespace llvm;
235 BasicBlock*
236 MyCompiler::handle_if( BasicBlock* bb, SetCondInst* condition )
237 {
238     // Create the blocks to contain code in the structure of if/then/else
239     BasicBlock* then_bb = new BasicBlock(); 
240     BasicBlock* else_bb = new BasicBlock();
241     BasicBlock* exit_bb = new BasicBlock();
242
243     // Insert the branch instruction for the "if"
244     bb->getInstList().push_back( new BranchInst( then_bb, else_bb, condition ) );
245
246     // Set up the terminating instructions
247     then->getInstList().push_back( new BranchInst( exit_bb ) );
248     else->getInstList().push_back( new BranchInst( exit_bb ) );
249
250     // Fill in the then part .. details excised for brevity
251     this->fill_in( then_bb );
252
253     // Fill in the else part .. details excised for brevity
254     this->fill_in( else_bb );
255
256     // Return a block to the caller that can be filled in with the code
257     // that follows the if/then/else construct.
258     return exit_bb;
259 }
260 </pre>
261 <p>Presumably in the foregoing, the calls to the "fill_in" method would add 
262 the instructions for the "then" and "else" parts. They would use the third part
263 of the idiom almost exclusively (inserting new instructions before the 
264 terminator). Furthermore, they could even recurse back to <code>handle_if</code> 
265 should they encounter another if/then/else statement, and it will just work.</p>
266 <p>Note how cleanly this all works out. In particular, the push_back methods on
267 the <code>BasicBlock</code>'s instruction list. These are lists of type 
268 <code>Instruction</code> (which is also of type <code>Value</code>). To create 
269 the "if" branch we merely instantiate a <code>BranchInst</code> that takes as 
270 arguments the blocks to branch to and the condition to branch on. The 
271 <code>BasicBlock</code> objects act like branch labels! This new 
272 <code>BranchInst</code> terminates the <code>BasicBlock</code> provided 
273 as an argument. To give the caller a way to keep inserting after calling 
274 <code>handle_if</code>, we create an <code>exit_bb</code> block which is
275 returned 
276 to the caller.  Note that the <code>exit_bb</code> block is used as the 
277 terminator for both the <code>then_bb</code> and the <code>else_bb</code>
278 blocks. This guarantees that no matter what else <code>handle_if</code>
279 or <code>fill_in</code> does, they end up at the <code>exit_bb</code> block.
280 </p>
281 </div>
282 <!-- ======================================================================= -->
283 <div class="doc_subsection"><a name="push_back"></a>push_back Is Your Friend</div>
284 <div class="doc_text">
285 <p>
286 One of the first things I noticed is the frequent use of the "push_back"
287 method on the various lists. This is so common that it is worth mentioning.
288 The "push_back" inserts a value into an STL list, vector, array, etc. at the
289 end. The method might have also been named "insert_tail" or "append".
290 Although I've used STL quite frequently, my use of push_back wasn't very
291 high in other programs. In LLVM, you'll use it all the time.
292 </p>
293 </div>
294 <!-- ======================================================================= -->
295 <div class="doc_subsection"><a name="gep"></a>The Wily GetElementPtrInst</div>
296 <div class="doc_text">
297 <p>
298 It took a little getting used to and several rounds of postings to the LLVM
299 mailing list to wrap my head around this instruction correctly. Even though I had
300 read the Language Reference and Programmer's Manual a couple times each, I still
301 missed a few <em>very</em> key points:
302 </p>
303 <ul>
304 <li>GetElementPtrInst gives you back a Value for the last thing indexed.</li>
305 <li>All global variables in LLVM  are <em>pointers</em>.</li>
306 <li>Pointers must also be dereferenced with the GetElementPtrInst
307 instruction.</li>
308 </ul>
309 <p>This means that when you look up an element in the global variable (assuming
310 it's a struct or array), you <em>must</em> deference the pointer first! For many
311 things, this leads to the idiom:
312 </p>
313 <pre>
314 std::vector&lt;Value*&gt; index_vector;
315 index_vector.push_back( ConstantSInt::get( Type::LongTy, 0 );
316 // ... push other indices ...
317 GetElementPtrInst* gep = new GetElementPtrInst( ptr, index_vector );
318 </pre>
319 <p>For example, suppose we have a global variable whose type is [24 x int]. The
320 variable itself represents a <em>pointer</em> to that array. To subscript the
321 array, we need two indices, not just one. The first index (0) dereferences the
322 pointer. The second index subscripts the array. If you're a "C" programmer, this
323 will run against your grain because you'll naturally think of the global array
324 variable and the address of its first element as the same. That tripped me up
325 for a while until I realized that they really do differ .. by <em>type</em>.
326 Remember that LLVM is strongly typed. Everything has a type.  
327 The "type" of the global variable is [24 x int]*. That is, it's
328 a pointer to an array of 24 ints.  When you dereference that global variable with
329 a single (0) index, you now have a "[24 x int]" type.  Although
330 the pointer value of the dereferenced global and the address of the zero'th element
331 in the array will be the same, they differ in their type. The zero'th element has
332 type "int" while the pointer value has type "[24 x int]".</p>
333 <p>Get this one aspect of LLVM right in your head, and you'll save yourself
334 a lot of compiler writing headaches down the road.</p>
335 </div>
336 <!-- ======================================================================= -->
337 <div class="doc_subsection"><a name="linkage"></a>Getting Linkage Types Right</div>
338 <div class="doc_text">
339 <p>Linkage types in LLVM can be a little confusing, especially if your compiler
340 writing mind has affixed firm concepts to particular words like "weak",
341 "external", "global", "linkonce", etc. LLVM does <em>not</em> use the precise
342 definitions of, say, ELF or GCC, even though they share common terms. To be fair,
343 the concepts are related and similar but not precisely the same. This can lead
344 you to think you know what a linkage type represents but in fact it is slightly
345 different. I recommend you read the 
346 <a href="LangRef.html#linkage"> Language Reference on this topic</a> very 
347 carefully. Then, read it again.<p>
348 <p>Here are some handy tips that I discovered along the way:</p>
349 <ul>
350     <li><em>Uninitialized means external.</em> That is, the symbol is declared in the current
351     module and can be used by that module, but it is not defined by that module.</li>
352     <li><em>Setting an initializer changes a global' linkage type.</em> Setting an 
353     initializer changes a global's linkage type from whatever it was to a normal, 
354     defined global (not external). You'll need to call the setLinkage() method to 
355     reset it if you specify the initializer after the GlobalValue has been constructed. 
356     This is important for LinkOnce and Weak linkage types.</li> 
357     <li><em>Appending linkage can keep track of things.</em> Appending linkage can 
358     be used to keep track of compilation information at runtime. It could be used, 
359     for example, to build a full table of all the C++ virtual tables or hold the 
360     C++ RTTI data, or whatever. Appending linkage can only be applied to arrays. 
361     All arrays with the same name in each module are concatenated together at link 
362     time.</li>
363 </ul>
364 </div>
365 <!-- ======================================================================= -->
366 <div class="doc_subsection"><a name="constants"></a>Constants Are Easier Than That!</div>
367 <div class="doc_text">
368 <p>
369 Constants in LLVM took a little getting used to until I discovered a few utility
370 functions in the LLVM IR that make things easier. Here's what I learned: </p>
371 <ul>
372  <li>Constants are Values like anything else and can be operands of instructions</li>
373  <li>Integer constants, frequently needed, can be created using the static "get"
374  methods of the ConstantInt, ConstantSInt, and ConstantUInt classes. The nice thing
375  about these is that you can "get" any kind of integer quickly.</li>
376  <li>There's a special method on Constant class which allows you to get the null 
377  constant for <em>any</em> type. This is really handy for initializing large 
378  arrays or structures, etc.</li>
379 </ul>
380 </div>
381 <!-- ======================================================================= -->
382 <div class="doc_section"> <a name="lexicon">The Stacker Lexicon</a></div>
383 <div class="doc_text"><p>This section describes the Stacker language</p></div>
384 <div class="doc_subsection"><a name="stack"></a>The Stack</div>
385 <div class="doc_text">
386 <p>Stacker definitions define what they do to the global stack. Before
387 proceeding, a few words about the stack are in order. The stack is simply
388 a global array of 32-bit integers or pointers. A global index keeps track
389 of the location of the top of the stack. All of this is hidden from the 
390 programmer, but it needs to be noted because it is the foundation of the 
391 conceptual programming model for Stacker. When you write a definition,
392 you are, essentially, saying how you want that definition to manipulate
393 the global stack.</p>
394 <p>Manipulating the stack can be quite hazardous. There is no distinction
395 given and no checking for the various types of values that can be placed
396 on the stack. Automatic coercion between types is performed. In many 
397 cases, this is useful. For example, a boolean value placed on the stack
398 can be interpreted as an integer with good results. However, using a
399 word that interprets that boolean value as a pointer to a string to
400 print out will almost always yield a crash. Stacker simply leaves it
401 to the programmer to get it right without any interference or hindering
402 on interpretation of the stack values. You've been warned. :) </p>
403 </div>
404 <!-- ======================================================================= -->
405 <div class="doc_subsection"> <a name="punctuation"></a>Punctuation</div>
406 <div class="doc_text">
407 <p>Punctuation in Stacker is very simple. The colon and semi-colon 
408 characters are used to introduce and terminate a definition
409 (respectively). Except for <em>FORWARD</em> declarations, definitions 
410 are all you can specify in Stacker.  Definitions are read left to right. 
411 Immediately after the colon comes the name of the word being defined. 
412 The remaining words in the definition specify what the word does. The definition
413 is terminated by a semi-colon.</p>
414 <p>So, your typical definition will have the form:</p>
415 <pre><code>: name ... ;</code></pre>
416 <p>The <code>name</code> is up to you but it must start with a letter and contain
417 only letters, numbers, and underscore. Names are case sensitive and must not be
418 the same as the name of a built-in word. The <code>...</code> is replaced by
419 the stack manipulating words that you wish to define <code>name</code> as. <p>
420 </div>
421 <!-- ======================================================================= -->
422 <div class="doc_subsection"><a name="comments"></a>Comments</div>
423 <div class="doc_text">
424     <p>Stacker supports two types of comments. A hash mark (#) starts a comment
425     that extends to the end of the line. It is identical to the kind of comments
426     commonly used in shell scripts. A pair of parentheses also surround a comment.
427     In both cases, the content of the comment is ignored by the Stacker compiler. The
428     following does nothing in Stacker.
429     </p>
430 <pre><code>
431 # This is a comment to end of line
432 ( This is an enclosed comment )
433 </code></pre>
434 <p>See the <a href="#example">example</a> program to see comments in use in 
435 a real program.</p>
436 </div>
437 <!-- ======================================================================= -->
438 <div class="doc_subsection"><a name="literals"></a>Literals</div>
439 <div class="doc_text">
440     <p>There are three kinds of literal values in Stacker: Integers, Strings,
441     and Booleans. In each case, the stack operation is to simply push the
442     value on to the stack. So, for example:<br/>
443     <code> 42 " is the answer." TRUE </code><br/>
444     will push three values on to the stack: the integer 42, the
445     string " is the answer.", and the boolean TRUE.</p>
446 </div>
447 <!-- ======================================================================= -->
448 <div class="doc_subsection"><a name="words"></a>Words</div>
449 <div class="doc_text">
450 <p>Each definition in Stacker is composed of a set of words. Words are
451 read and executed in order from left to right. There is very little
452 checking in Stacker to make sure you're doing the right thing with 
453 the stack. It is assumed that the programmer knows how the stack 
454 transformation he applies will affect the program.</p>
455 <p>Words in a definition come in two flavors: built-in and programmer
456 defined. Simply mentioning the name of a previously defined or declared
457 programmer-defined word causes that word's stack actions to be invoked. It
458 is somewhat like a function call in other languages. The built-in
459 words have various effects, described <a href="#builtins">below</a>.</p>
460 <p>Sometimes you need to call a word before it is defined. For this, you can
461 use the <code>FORWARD</code> declaration. It looks like this:</p>
462 <p><code>FORWARD name ;</code></p>
463 <p>This simply states to Stacker that "name" is the name of a definition
464 that is defined elsewhere. Generally it means the definition can be found
465 "forward" in the file. But, it doesn't have to be in the current compilation
466 unit. Anything declared with <code>FORWARD</code> is an external symbol for
467 linking.</p>
468 </div>
469 <!-- ======================================================================= -->
470 <div class="doc_subsection"><a name="style"></a>Standard Style</div>
471 <div class="doc_text">
472 <p>TODO</p>
473 </div>
474 <!-- ======================================================================= -->
475 <div class="doc_subsection"><a name="builtins"></a>Built In Words</div>
476 <div class="doc_text">
477 <p>The built-in words of the Stacker language are put in several groups 
478 depending on what they do. The groups are as follows:</p>
479 <ol> 
480     <li><em>Logical</em>: These words provide the logical operations for
481     comparing stack operands.<br/>The words are: &lt; &gt; &lt;= &gt;= 
482     = &lt;&gt; true false.</li>
483     <li><em>Bitwise</em>: These words perform bitwise computations on 
484     their operands. <br/> The words are: &lt;&lt; &gt;&gt; XOR AND NOT</li>
485     <li><em>Arithmetic</em>: These words perform arithmetic computations on
486     their operands. <br/> The words are: ABS NEG + - * / MOD */ ++ -- MIN MAX</li>
487     <li><em>Stack</em>These words manipulate the stack directly by moving
488     its elements around.<br/> The words are: DROP DROP2 NIP NIP2 DUP DUP2 
489     SWAP SWAP2 OVER OVER2 ROT ROT2 RROT RROT2 TUCK TUCK2 PICK SELECT ROLL</li>
490     <li><em>Memory</em>These words allocate, free, and manipulate memory
491     areas outside the stack.<br/>The words are: MALLOC FREE GET PUT</li>
492     <li><em>Control</em>: These words alter the normal left to right flow
493     of execution.<br/>The words are: IF ELSE ENDIF WHILE END RETURN EXIT RECURSE</li>
494     <li><em>I/O</em>: These words perform output on the standard output
495     and input on the standard input. No other I/O is possible in Stacker.
496     <br/>The words are: SPACE TAB CR &gt;s &gt;d &gt;c &lt;s &lt;d &lt;c.</li>
497 </ol>
498 <p>While you may be familiar with many of these operations from other
499 programming languages, a careful review of their semantics is important
500 for correct programming in Stacker. Of most importance is the effect 
501 that each of these built-in words has on the global stack. The effect is
502 not always intuitive. To better describe the effects, we'll borrow from Forth the idiom of
503 describing the effect on the stack with:</p>
504 <p><code> BEFORE -- AFTER </code></p> 
505 <p>That is, to the left of the -- is a representation of the stack before
506 the operation. To the right of the -- is a representation of the stack
507 after the operation. In the table below that describes the operation of
508 each of the built in words, we will denote the elements of the stack 
509 using the following construction:</p>
510 <ol>
511     <li><em>b</em> - a boolean truth value</li>
512     <li><em>w</em> - a normal integer valued word.</li>
513     <li><em>s</em> - a pointer to a string value</li>
514     <li><em>p</em> - a pointer to a malloc'd memory block</li>
515 </ol>
516 </div>
517 <div class="doc_text" >
518     <table class="doc_table">
519 <tr class="doc_table"><td colspan="4">Definition Of Operation Of Built In Words</td></tr>
520 <tr class="doc_table"><td colspan="4"><b>LOGICAL OPERATIONS</b></td></tr>
521 <tr class="doc_table">
522     <td>Word</td>
523     <td>Name</td>
524     <td>Operation</td>
525     <td>Description</td>
526 </tr>
527 <tr class="doc_table">
528     <td>&lt;</td>
529     <td>LT</td>
530     <td>w1 w2 -- b</td>
531     <td>Two values (w1 and w2) are popped off the stack and
532     compared. If w1 is less than w2, TRUE is pushed back on
533     the stack, otherwise FALSE is pushed back on the stack.</td>
534 </tr>
535 <tr><td>&gt;</td>
536     <td>GT</td>
537     <td>w1 w2 -- b</td>
538     <td>Two values (w1 and w2) are popped off the stack and
539     compared. If w1 is greater than w2, TRUE is pushed back on
540     the stack, otherwise FALSE is pushed back on the stack.</td>
541 </tr>
542 <tr><td>&gt;=</td>
543     <td>GE</td>
544     <td>w1 w2 -- b</td>
545     <td>Two values (w1 and w2) are popped off the stack and
546     compared. If w1 is greater than or equal to w2, TRUE is 
547     pushed back on the stack, otherwise FALSE is pushed back 
548     on the stack.</td>
549 </tr>
550 <tr><td>&lt;=</td>
551     <td>LE</td>
552     <td>w1 w2 -- b</td>
553     <td>Two values (w1 and w2) are popped off the stack and
554     compared. If w1 is less than or equal to w2, TRUE is 
555     pushed back on the stack, otherwise FALSE is pushed back 
556     on the stack.</td>
557 </tr>
558 <tr><td>=</td>
559     <td>EQ</td>
560     <td>w1 w2 -- b</td>
561     <td>Two values (w1 and w2) are popped off the stack and
562     compared. If w1 is equal to w2, TRUE is 
563     pushed back on the stack, otherwise FALSE is pushed back 
564     </td>
565 </tr>
566 <tr><td>&lt;&gt;</td>
567     <td>NE</td>
568     <td>w1 w2 -- b</td>
569     <td>Two values (w1 and w2) are popped off the stack and
570     compared. If w1 is equal to w2, TRUE is 
571     pushed back on the stack, otherwise FALSE is pushed back 
572     </td>
573 </tr>
574 <tr><td>FALSE</td>
575     <td>FALSE</td>
576     <td> -- b</td>
577     <td>The boolean value FALSE (0) is pushed on to the stack.</td>
578 </tr>
579 <tr><td>TRUE</td>
580     <td>TRUE</td>
581     <td> -- b</td>
582     <td>The boolean value TRUE (-1) is pushed on to the stack.</td>
583 </tr>
584 <tr><td colspan="4"><b>BITWISE OPERATORS</b></td></tr>
585 <tr>
586     <td>Word</td>
587     <td>Name</td>
588     <td>Operation</td>
589     <td>Description</td>
590 </tr>
591 <tr><td>&lt;&lt;</td>
592     <td>SHL</td>
593     <td>w1 w2 -- w1&lt;&lt;w2</td>
594     <td>Two values (w1 and w2) are popped off the stack. The w2
595     operand is shifted left by the number of bits given by the
596     w1 operand. The result is pushed back to the stack.</td>
597 </tr>
598 <tr><td>&gt;&gt;</td>
599     <td>SHR</td>
600     <td>w1 w2 -- w1&gt;&gt;w2</td>
601     <td>Two values (w1 and w2) are popped off the stack. The w2
602     operand is shifted right by the number of bits given by the
603     w1 operand. The result is pushed back to the stack.</td>
604 </tr>
605 <tr><td>OR</td>
606     <td>OR</td>
607     <td>w1 w2 -- w2|w1</td>
608     <td>Two values (w1 and w2) are popped off the stack. The values
609     are bitwise OR'd together and pushed back on the stack. This is 
610     not a logical OR. The sequence 1 2 OR yields 3 not 1.</td>
611 </tr>
612 <tr><td>AND</td>
613     <td>AND</td>
614     <td>w1 w2 -- w2&amp;w1</td>
615     <td>Two values (w1 and w2) are popped off the stack. The values
616     are bitwise AND'd together and pushed back on the stack. This is 
617     not a logical AND. The sequence 1 2 AND yields 0 not 1.</td>
618 </tr>
619 <tr><td>XOR</td>
620     <td>XOR</td>
621     <td>w1 w2 -- w2^w1</td>
622     <td>Two values (w1 and w2) are popped off the stack. The values
623     are bitwise exclusive OR'd together and pushed back on the stack. 
624     For example, The sequence 1 3 XOR yields 2.</td>
625 </tr>
626 <tr><td colspan="4"><b>ARITHMETIC OPERATORS</b></td></tr>
627 <tr>
628     <td>Word</td>
629     <td>Name</td>
630     <td>Operation</td>
631     <td>Description</td>
632 </tr>
633 <tr><td>ABS</td>
634     <td>ABS</td>
635     <td>w -- |w|</td>
636     <td>One value s popped off the stack; its absolute value is computed
637     and then pushed on to the stack. If w1 is -1 then w2 is 1. If w1 is
638     1 then w2 is also 1.</td>
639 </tr>
640 <tr><td>NEG</td>
641     <td>NEG</td>
642     <td>w -- -w</td>
643     <td>One value is popped off the stack which is negated and then
644     pushed back on to the stack. If w1 is -1 then w2 is 1. If w1 is
645     1 then w2 is -1.</td>
646 </tr>
647 <tr><td> + </td>
648     <td>ADD</td>
649     <td>w1 w2 -- w2+w1</td>
650     <td>Two values are popped off the stack. Their sum is pushed back
651     on to the stack</td>
652 </tr>
653 <tr><td> - </td>
654     <td>SUB</td>
655     <td>w1 w2 -- w2-w1</td>
656     <td>Two values are popped off the stack. Their difference is pushed back
657     on to the stack</td>
658 </tr>
659 <tr><td> * </td>
660     <td>MUL</td>
661     <td>w1 w2 -- w2*w1</td>
662     <td>Two values are popped off the stack. Their product is pushed back
663     on to the stack</td>
664 </tr>
665 <tr><td> / </td>
666     <td>DIV</td>
667     <td>w1 w2 -- w2/w1</td>
668     <td>Two values are popped off the stack. Their quotient is pushed back
669     on to the stack</td>
670 </tr>
671 <tr><td>MOD</td>
672     <td>MOD</td>
673     <td>w1 w2 -- w2%w1</td>
674     <td>Two values are popped off the stack. Their remainder after division
675     of w1 by w2 is pushed back on to the stack</td>
676 </tr>
677 <tr><td> */ </td>
678     <td>STAR_SLAH</td>
679     <td>w1 w2 w3 -- (w3*w2)/w1</td>
680     <td>Three values are popped off the stack. The product of w1 and w2 is
681     divided by w3. The result is pushed back on to the stack.</td>
682 </tr>
683 <tr><td> ++ </td>
684     <td>INCR</td>
685     <td>w -- w+1</td>
686     <td>One value is popped off the stack. It is incremented by one and then
687     pushed back on to the stack.</td>
688 </tr>
689 <tr><td> -- </td>
690     <td>DECR</td>
691     <td>w -- w-1</td>
692     <td>One value is popped off the stack. It is decremented by one and then
693     pushed back on to the stack.</td>
694 </tr>
695 <tr><td>MIN</td>
696     <td>MIN</td>
697     <td>w1 w2 -- (w2&lt;w1?w2:w1)</td>
698     <td>Two values are popped off the stack. The larger one is pushed back
699     on to the stack.</td>
700 </tr>
701 <tr><td>MAX</td>
702     <td>MAX</td>
703     <td>w1 w2 -- (w2&gt;w1?w2:w1)</td>
704     <td>Two values are popped off the stack. The larger value is pushed back
705         on to the stack.</td>
706 </tr>
707 <tr><td colspan="4"><b>STACK MANIPULATION OPERATORS</b></td></tr>
708 <tr>
709     <td>Word</td>
710     <td>Name</td>
711     <td>Operation</td>
712     <td>Description</td>
713 </tr>
714 <tr><td>DROP</td>
715     <td>DROP</td>
716     <td>w -- </td>
717     <td>One value is popped off the stack.</td>
718 </tr>
719 <tr><td>DROP2</td>
720     <td>DROP2</td>
721     <td>w1 w2 -- </td>
722     <td>Two values are popped off the stack.</td>
723 </tr>
724 <tr><td>NIP</td>
725     <td>NIP</td>
726     <td>w1 w2 -- w2</td>
727     <td>The second value on the stack is removed from the stack. That is,
728         a value is popped off the stack and retained. Then a second value is
729         popped and the retained value is pushed.</td>
730 </tr>
731 <tr><td>NIP2</td>
732     <td>NIP2</td>
733     <td>w1 w2 w3 w4 -- w3 w4</td>
734     <td>The third and fourth values on the stack are removed from it. That is,
735         two values are popped and retained. Then two more values are popped and
736         the two retained values are pushed back on.</td>
737 </tr>
738 <tr><td>DUP</td>
739     <td>DUP</td>
740     <td>w1 -- w1 w1</td>
741     <td>One value is popped off the stack. That value is then pushed on to
742         the stack twice to duplicate the top stack vaue.</td>
743 </tr>
744 <tr><td>DUP2</td>
745     <td>DUP2</td>
746     <td>w1 w2 -- w1 w2 w1 w2</td>
747     <td>The top two values on the stack are duplicated. That is, two vaues
748         are popped off the stack. They are alternately pushed back on the
749         stack twice each.</td>
750 </tr>
751 <tr><td>SWAP</td>
752     <td>SWAP</td>
753     <td>w1 w2 -- w2 w1</td>
754     <td>The top two stack items are reversed in their order. That is, two
755         values are popped off the stack and pushed back on to the stack in
756         the opposite order they were popped.</td>
757 </tr>
758 <tr><td>SWAP2</td>
759     <td>SWAP2</td>
760     <td>w1 w2 w3 w4 -- w3 w4 w2 w1</td>
761     <td>The top four stack items are swapped in pairs. That is, two values
762         are popped and retained. Then, two more values are popped and retained.
763         The values are pushed back on to the stack in the reverse order but
764         in pairs.</td>
765 </tr>
766 <tr><td>OVER</td>
767     <td>OVER</td>
768     <td>w1 w2-- w1 w2 w1</td>
769     <td>Two values are popped from the stack. They are pushed back
770         on to the stack in the order w1 w2 w1. This seems to cause the
771         top stack element to be duplicated "over" the next value.</td>
772 </tr>
773 <tr><td>OVER2</td>
774     <td>OVER2</td>
775     <td>w1 w2 w3 w4 -- w1 w2 w3 w4 w1 w2</td>
776     <td>The third and fourth values on the stack are replicated on to the
777         top of the stack</td>
778 </tr>
779 <tr><td>ROT</td>
780     <td>ROT</td>
781     <td>w1 w2 w3 -- w2 w3 w1</td>
782     <td>The top three values are rotated. That is, three value are popped
783         off the stack. They are pushed back on to the stack in the order
784         w1 w3 w2.</td>
785 </tr>
786 <tr><td>ROT2</td>
787     <td>ROT2</td>
788     <td>w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2</td>
789     <td>Like ROT but the rotation is done using three pairs instead of
790         three singles.</td>
791 </tr>
792 <tr><td>RROT</td>
793     <td>RROT</td>
794     <td>w1 w2 w3 -- w2 w3 w1</td>
795     <td>Reverse rotation. Like ROT, but it rotates the other way around.
796         Essentially, the third element on the stack is moved to the top
797         of the stack.</td>
798 </tr>
799 <tr><td>RROT2</td>
800     <td>RROT2</td>
801     <td>w1 w2 w3 w4 w5 w6 -- w3 w4 w5 w6 w1 w2</td>
802     <td>Double reverse rotation. Like RROT but the rotation is done using 
803         three pairs instead of three singles. The fifth and sixth stack 
804         elements are moved to the first and second positions</td>
805 </tr>
806 <tr><td>TUCK</td>
807     <td>TUCK</td>
808     <td>w1 w2 -- w2 w1 w2</td>
809     <td>Similar to OVER except that the second operand is being 
810         replicated. Essentially, the first operand is being "tucked"
811         in between two instances of the second operand. Logically, two
812         values are popped off the stack. They are placed back on the
813         stack in the order w2 w1 w2.</td>
814 </tr>
815 <tr><td>TUCK2</td>
816     <td>TUCK2</td>
817     <td>w1 w2 w3 w4 -- w3 w4 w1 w2 w3 w4</td>
818     <td>Like TUCK but a pair of elements is tucked over two pairs.
819         That is, the top two elements of the stack are duplicated and
820         inserted into the stack at the fifth and positions.</td>
821 </tr>
822 <tr><td>PICK</td>
823     <td>PICK</td>
824     <td>x0 ... Xn n -- x0 ... Xn x0</td>
825     <td>The top of the stack is used as an index into the remainder of
826         the stack. The element at the nth position replaces the index 
827         (top of stack). This is useful for cycling through a set of 
828         values. Note that indexing is zero based. So, if n=0 then you
829         get the second item on the stack. If n=1 you get the third, etc.
830         Note also that the index is replaced by the n'th value. </td>
831 </tr>
832 <tr><td>SELECT</td>
833     <td>SELECT</td>
834     <td>m n X0..Xm Xm+1 .. Xn -- Xm</td>
835     <td>This is like PICK but the list is removed and you need to specify
836         both the index and the size of the list. Careful with this one,
837         the wrong value for n can blow away a huge amount of the stack.</td>
838 </tr>
839 <tr><td>ROLL</td>
840     <td>ROLL</td>
841     <td>x0 x1 .. xn n -- x1 .. xn x0</td>
842     <td><b>Not Implemented</b>. This one has been left as an exercise to
843         the student. See <a href="#exercise">Exercise</a>. ROLL requires 
844     a value, "n", to be on the top of the stack. This value specifies how 
845     far into the stack to "roll". The n'th value is <em>moved</em> (not
846     copied) from its location and replaces the "n" value on the top of the
847     stack. In this way, all the values between "n" and x0 roll up the stack.
848     The operation of ROLL is a generalized ROT.  The "n" value specifies 
849     how much to rotate. That is, ROLL with n=1 is the same as ROT and 
850     ROLL with n=2 is the same as ROT2.</td>
851 </tr>
852 <tr><td colspan="4"><b>MEMORY OPERATORS</b></td></tr>
853 <tr>
854     <td>Word</td>
855     <td>Name</td>
856     <td>Operation</td>
857     <td>Description</td>
858 </tr>
859 <tr><td>MALLOC</td>
860     <td>MALLOC</td>
861     <td>w1 -- p</td>
862     <td>One value is popped off the stack. The value is used as the size
863         of a memory block to allocate. The size is in bytes, not words.
864         The memory allocation is completed and the address of the memory
865         block is pushed on to the stack.</td>
866 </tr>
867 <tr><td>FREE</td>
868     <td>FREE</td>
869     <td>p -- </td>
870     <td>One pointer value is popped off the stack. The value should be
871         the address of a memory block created by the MALLOC operation. The
872         associated memory block is freed. Nothing is pushed back on the
873         stack. Many bugs can be created by attempting to FREE something
874         that isn't a pointer to a MALLOC allocated memory block. Make
875         sure you know what's on the stack.  One way to do this is with
876         the following idiom:<br/>
877         <code>64 MALLOC DUP DUP (use ptr) DUP (use ptr) ...  FREE</code>
878         <br/>This ensures that an extra copy of the pointer is placed on
879         the stack (for the FREE at the end) and that every use of the
880         pointer is preceded by a DUP to retain the copy for FREE.</td>
881 </tr>
882 <tr><td>GET</td>
883     <td>GET</td>
884     <td>w1 p -- w2 p</td>
885     <td>An integer index and a pointer to a memory block are popped of
886         the block. The index is used to index one byte from the memory
887         block. That byte value is retained, the pointer is pushed again
888         and the retained value is pushed. Note that the pointer value
889         s essentially retained in its position so this doesn't count
890         as a "use ptr" in the FREE idiom.</td>
891 </tr>
892 <tr><td>PUT</td>
893     <td>PUT</td>
894     <td>w1 w2 p -- p </td>
895     <td>An integer value is popped of the stack. This is the value to
896         be put into a memory block. Another integer value is popped of
897         the stack. This is the indexed byte in the memory block. A
898         pointer to the memory block is popped off the stack. The
899         first value (w1) is then converted to a byte and written
900         to the element of the memory block(p) at the index given
901         by the second value (w2). The pointer to the memory block is
902         pushed back on the stack so this doesn't count as a "use ptr"
903         in the FREE idiom.</td>
904 </tr>
905 <tr><td colspan="4"><b>CONTROL FLOW OPERATORS</b></td></tr>
906 <tr>
907     <td>Word</td>
908     <td>Name</td>
909     <td>Operation</td>
910     <td>Description</td>
911 </tr>
912 <tr><td>RETURN</td>
913     <td>RETURN</td>
914     <td> --  </td>
915     <td>The currently executing definition returns immediately to its caller.
916         Note that there is an implicit <code>RETURN</code> at the end of each
917         definition, logically located at the semi-colon. The sequence 
918         <code>RETURN ;</code>  is valid but redundant.</td>
919 </tr>
920 <tr><td>EXIT</td>
921     <td>EXIT</td>
922     <td>w1 -- </td>
923     <td>A return value for the program is popped off the stack. The program is
924         then immediately terminated. This is normally an abnormal exit from the
925         program. For a normal exit (when <code>MAIN</code> finishes), the exit
926         code will always be zero in accordance with UNIX conventions.</td>
927 </tr>
928 <tr><td>RECURSE</td>
929     <td>RECURSE</td>
930     <td> -- </td>
931     <td>The currently executed definition is called again. This operation is 
932         needed since the definition of a word doesn't exist until the semi colon
933         is reacher. Attempting something like:<br/>
934         <code> : recurser recurser ; </code><br/> will yield and error saying that 
935         "recurser" is not defined yet. To accomplish the same thing, change this
936         to:<br/>
937         <code> : recurser RECURSE ; </code></td>
938 </tr>
939 <tr><td>IF (words...) ENDIF</td>
940     <td>IF (words...) ENDIF</td>
941     <td>b -- </td>
942     <td>A boolean value is popped of the stack. If it is non-zero then the "words..." 
943         are executed. Otherwise, execution continues immediately following the ENDIF.</td>
944 </tr>
945 <tr><td>IF (words...) ELSE (words...) ENDIF</td>
946     <td>IF (words...) ELSE (words...) ENDIF</td>
947     <td>b -- </td>
948     <td>A boolean value is popped of the stack. If it is non-zero then the "words..."
949         between IF and ELSE are executed. Otherwise the words between ELSE and ENDIF are
950         executed. In either case, after the (words....) have executed, execution continues
951         immediately following the ENDIF. </td>
952 </tr>
953 <tr><td>WHILE (words...) END</td>
954     <td>WHILE (words...) END</td>
955     <td>b -- b </td>
956     <td>The boolean value on the top of the stack is examined. If it is non-zero then the 
957         "words..." between WHILE and END are executed. Execution then begins again at the WHILE where another
958         boolean is popped off the stack. To prevent this operation from eating up the entire
959         stack, you should push on to the stack (just before the END) a boolean value that indicates
960         whether to terminate. Note that since booleans and integers can be coerced you can
961         use the following "for loop" idiom:<br/>
962         <code>(push count) WHILE (words...) -- END</code><br/>
963         For example:<br/>
964         <code>10 WHILE DUP &gt;d -- END</code><br/>
965         This will print the numbers from 10 down to 1. 10 is pushed on the stack. Since that is
966         non-zero, the while loop is entered. The top of the stack (10) is duplicated and then
967         printed out with &gt;d. The top of the stack is decremented, yielding 9 and control is
968         transfered back to the WHILE keyword. The process starts all over again and repeats until
969         the top of stack is decremented to 0 at which the WHILE test fails and control is
970         transfered to the word after the END.</td>
971 </tr>
972 <tr><td colspan="4"><b>INPUT &amp; OUTPUT OPERATORS</b></td></tr>
973 <tr>
974     <td>Word</td>
975     <td>Name</td>
976     <td>Operation</td>
977     <td>Description</td>
978 </tr>
979 <tr><td>SPACE</td>
980     <td>SPACE</td>
981     <td> --  </td>
982     <td>A space character is put out. There is no stack effect.</td>
983 </tr>
984 <tr><td>TAB</td>
985     <td>TAB</td>
986     <td> --  </td>
987     <td>A tab character is put out. There is no stack effect.</td>
988 </tr>
989 <tr><td>CR</td>
990     <td>CR</td>
991     <td> --  </td>
992     <td>A carriage return character is put out. There is no stack effect.</td>
993 </tr>
994 <tr><td>&gt;s</td>
995     <td>OUT_STR</td>
996     <td> -- </td>
997     <td>A string pointer is popped from the stack. It is put out.</td>
998 </tr>
999 <tr><td>&gt;d</td>
1000     <td>OUT_STR</td>
1001     <td> -- </td>
1002     <td>A value is popped from the stack. It is put out as a decimal
1003     integer.</td>
1004 </tr>
1005 <tr><td>&gt;c</td>
1006     <td>OUT_CHR</td>
1007     <td> -- </td>
1008     <td>A value is popped from the stack. It is put out as an ASCII
1009     character.</td>
1010 </tr>
1011 <tr><td>&lt;s</td>
1012     <td>IN_STR</td>
1013     <td> -- s </td>
1014     <td>A string is read from the input via the scanf(3) format string " %as".
1015     The resulting string is pushed on to the stack.</td>
1016 </tr>
1017 <tr><td>&lt;d</td>
1018     <td>IN_STR</td>
1019     <td> -- w </td>
1020     <td>An integer is read from the input via the scanf(3) format string " %d".
1021     The resulting value is pushed on to the stack</td>
1022 </tr>
1023 <tr><td>&lt;c</td>
1024     <td>IN_CHR</td>
1025     <td> -- w </td>
1026     <td>A single character is read from the input via the scanf(3) format string
1027     " %c". The value is converted to an integer and pushed on to the stack.</td>
1028 </tr>
1029 <tr><td>DUMP</td>
1030     <td>DUMP</td>
1031     <td> -- </td>
1032     <td>The stack contents are dumped to standard output. This is useful for
1033         debugging your definitions. Put DUMP at the beginning and end of a definition
1034         to see instantly the net effect of the definition.</td>
1035 </tr>
1036 </table>
1037
1038 </div>
1039 <!-- ======================================================================= -->
1040 <div class="doc_section"> <a name="example">Prime: A Complete Example</a></div>
1041 <div class="doc_text">
1042 <p>The following fully documented program highlights many features of both
1043 the Stacker language and what is possible with LLVM. The program has two modes
1044 of operation. If you provide numeric arguments to the program, it checks to see
1045 if those arguments are prime numbers and prints out the results. Without any 
1046 arguments, the program prints out any prime numbers it finds between 1 and one 
1047 million (there's a lot of them!). The source code comments below tell the 
1048 remainder of the story.
1049 </p>
1050 </div>
1051 <div class="doc_text">
1052 <pre><code>
1053 ################################################################################
1054 #
1055 # Brute force prime number generator
1056 #
1057 # This program is written in classic Stacker style, that being the style of a 
1058 # stack. Start at the bottom and read your way up !
1059 #
1060 # Reid Spencer - Nov 2003 
1061 ################################################################################
1062 # Utility definitions
1063 ################################################################################
1064 : print &gt;d CR ;
1065 : it_is_a_prime TRUE ;
1066 : it_is_not_a_prime FALSE ;
1067 : continue_loop TRUE ;
1068 : exit_loop FALSE;
1069     
1070 ################################################################################
1071 # This definition tries an actual division of a candidate prime number. It
1072 # determines whether the division loop on this candidate should continue or
1073 # not.
1074 # STACK&lt;:
1075 #    div - the divisor to try
1076 #    p   - the prime number we are working on
1077 # STACK&gt;:
1078 #    cont - should we continue the loop ?
1079 #    div - the next divisor to try
1080 #    p   - the prime number we are working on
1081 ################################################################################
1082 : try_dividing
1083     DUP2                        ( save div and p )
1084     SWAP                        ( swap to put divisor second on stack)
1085     MOD 0 =                     ( get remainder after division and test for 0 )
1086     IF 
1087         exit_loop               ( remainder = 0, time to exit )
1088     ELSE
1089         continue_loop           ( remainder != 0, keep going )
1090     ENDIF
1091 ;
1092
1093 ################################################################################
1094 # This function tries one divisor by calling try_dividing. But, before doing
1095 # that it checks to see if the value is 1. If it is, it does not bother with
1096 # the division because prime numbers are allowed to be divided by one. The
1097 # top stack value (cont) is set to determine if the loop should continue on
1098 # this prime number or not.
1099 # STACK<:
1100 #    cont - should we continue the loop (ignored)?
1101 #    div - the divisor to try
1102 #    p   - the prime number we are working on
1103 # STACK&gt;:
1104 #    cont - should we continue the loop ?
1105 #    div - the next divisor to try
1106 #    p   - the prime number we are working on
1107 ################################################################################
1108 : try_one_divisor
1109     DROP                        ( drop the loop continuation )
1110     DUP                         ( save the divisor )
1111     1 = IF                      ( see if divisor is == 1 )
1112         exit_loop               ( no point dividing by 1 )
1113     ELSE
1114         try_dividing            ( have to keep going )
1115     ENDIF
1116     SWAP                        ( get divisor on top )
1117     --                          ( decrement it )
1118     SWAP                        ( put loop continuation back on top )
1119 ;
1120
1121 ################################################################################
1122 # The number on the stack (p) is a candidate prime number that we must test to 
1123 # determine if it really is a prime number. To do this, we divide it by every 
1124 # number from one p-1 to 1. The division is handled in the try_one_divisor 
1125 # definition which returns a loop continuation value (which we also seed with
1126 # the value 1).  After the loop, we check the divisor. If it decremented all
1127 # the way to zero then we found a prime, otherwise we did not find one.
1128 # STACK&lt;:
1129 #   p - the prime number to check
1130 # STACK&gt;:
1131 #   yn - boolean indicating if its a prime or not
1132 #   p - the prime number checked
1133 ################################################################################
1134 : try_harder
1135     DUP                         ( duplicate to get divisor value ) )
1136     --                          ( first divisor is one less than p )
1137     1                           ( continue the loop )
1138     WHILE
1139        try_one_divisor          ( see if its prime )
1140     END
1141     DROP                        ( drop the continuation value )
1142     0 = IF                      ( test for divisor == 1 )
1143        it_is_a_prime            ( we found one )
1144     ELSE
1145        it_is_not_a_prime        ( nope, this one is not a prime )
1146     ENDIF
1147 ;
1148
1149 ################################################################################
1150 # This definition determines if the number on the top of the stack is a prime 
1151 # or not. It does this by testing if the value is degenerate (&lt;= 3) and 
1152 # responding with yes, its a prime. Otherwise, it calls try_harder to actually 
1153 # make some calculations to determine its primeness.
1154 # STACK&lt;:
1155 #    p - the prime number to check
1156 # STACK&gt;:
1157 #    yn - boolean indicating if its a prime or not
1158 #    p  - the prime number checked
1159 ################################################################################
1160 : is_prime 
1161     DUP                         ( save the prime number )
1162     3 &gt;= IF                  ( see if its &lt;= 3 )
1163         it_is_a_prime           ( its <= 3 just indicate its prime )
1164     ELSE 
1165         try_harder              ( have to do a little more work )
1166     ENDIF 
1167 ;
1168
1169 ################################################################################
1170 # This definition is called when it is time to exit the program, after we have 
1171 # found a sufficiently large number of primes.
1172 # STACK&lt;: ignored
1173 # STACK&gt;: exits
1174 ################################################################################
1175 : done 
1176     "Finished" &gt;s CR                 ( say we are finished )
1177     0 EXIT                      ( exit nicely )
1178 ;
1179
1180 ################################################################################
1181 # This definition checks to see if the candidate is greater than the limit. If 
1182 # it is, it terminates the program by calling done. Otherwise, it increments 
1183 # the value and calls is_prime to determine if the candidate is a prime or not. 
1184 # If it is a prime, it prints it. Note that the boolean result from is_prime is
1185 # gobbled by the following IF which returns the stack to just contining the
1186 # prime number just considered.
1187 # STACK&lt;: 
1188 #    p - one less than the prime number to consider
1189 # STAC&gt;K
1190 #    p+1 - the prime number considered
1191 ################################################################################
1192 : consider_prime 
1193     DUP                         ( save the prime number to consider )
1194     1000000 &lt; IF             ( check to see if we are done yet )
1195         done                    ( we are done, call "done" )
1196     ENDIF 
1197     ++                          ( increment to next prime number )
1198     is_prime                    ( see if it is a prime )
1199     IF 
1200        print                    ( it is, print it )
1201     ENDIF 
1202 ;
1203
1204 ################################################################################
1205 # This definition starts at one, prints it out and continues into a loop calling
1206 # consider_prime on each iteration. The prime number candidate we are looking at
1207 # is incremented by consider_prime.
1208 # STACK&lt;: empty
1209 # STACK&gt;: empty
1210 ################################################################################
1211 : find_primes 
1212     "Prime Numbers: " &gt;s CR  ( say hello )
1213     DROP                        ( get rid of that pesky string )
1214     1                           ( stoke the fires )
1215     print                       ( print the first one, we know its prime )
1216     WHILE                       ( loop while the prime to consider is non zero )
1217         consider_prime          ( consider one prime number )
1218     END 
1219
1220
1221 ################################################################################
1222 #
1223 ################################################################################
1224 : say_yes
1225     &gt;d                               ( Print the prime number )
1226     " is prime."                ( push string to output )
1227     &gt;s                               ( output it )
1228     CR                          ( print carriage return )
1229     DROP                        ( pop string )
1230 ;
1231
1232 : say_no
1233     &gt;d                               ( Print the prime number )
1234     " is NOT prime."            ( push string to put out )
1235     &gt;s                               ( put out the string )
1236     CR                          ( print carriage return )
1237     DROP                        ( pop string )
1238 ;
1239
1240 ################################################################################
1241 # This definition processes a single command line argument and determines if it
1242 # is a prime number or not.
1243 # STACK&lt;:
1244 #    n - number of arguments
1245 #    arg1 - the prime numbers to examine
1246 # STACK&gt;:
1247 #    n-1 - one less than number of arguments
1248 #    arg2 - we processed one argument
1249 ################################################################################
1250 : do_one_argument
1251     --                          ( decrement loop counter )
1252     SWAP                        ( get the argument value  )
1253     is_prime IF                 ( determine if its prime )
1254         say_yes                 ( uhuh )
1255     ELSE
1256         say_no                  ( nope )
1257     ENDIF
1258     DROP                        ( done with that argument )
1259 ;
1260
1261 ################################################################################
1262 # The MAIN program just prints a banner and processes its arguments.
1263 # STACK&lt;:
1264 #    n - number of arguments
1265 #    ... - the arguments
1266 ################################################################################
1267 : process_arguments
1268     WHILE                       ( while there are more arguments )
1269        do_one_argument          ( process one argument )
1270     END
1271 ;
1272     
1273 ################################################################################
1274 # The MAIN program just prints a banner and processes its arguments.
1275 # STACK&lt;: arguments
1276 ################################################################################
1277 : MAIN 
1278     NIP                         ( get rid of the program name )
1279     --                          ( reduce number of arguments )
1280     DUP                         ( save the arg counter )
1281     1 &lt;= IF                  ( See if we got an argument )
1282         process_arguments       ( tell user if they are prime )
1283     ELSE
1284         find_primes             ( see how many we can find )
1285     ENDIF
1286     0                           ( push return code )
1287 ;
1288 </code>
1289 </pre>
1290 </div>
1291 <!-- ======================================================================= -->
1292 <div class="doc_section"> <a name="internal">Internals</a></div>
1293 <div class="doc_text">
1294  <p><b>This section is under construction.</b>
1295  <p>In the mean time, you can always read the code! It has comments!</p>
1296 </div>
1297 <!-- ======================================================================= -->
1298 <div class="doc_subsection"> <a name="directory">Directory Structure</a></div>
1299 <div class="doc_text">
1300 <p>The source code, test programs, and sample programs can all be found
1301 under the LLVM "projects" directory. You will need to obtain the LLVM sources
1302 to find it (either via anonymous CVS or a tarball. See the 
1303 <a href="GettingStarted.html">Getting Started</a> document).</p>
1304 <p>Under the "projects" directory there is a directory named "Stacker". That
1305 directory contains everything, as follows:</p>
1306 <ul>
1307     <li><em>lib</em> - contains most of the source code
1308     <ul>
1309         <li><em>lib/compiler</em> - contains the compiler library
1310         <li><em>lib/runtime</em> - contains the runtime library
1311     </ul></li>
1312     <li><em>test</em> - contains the test programs</li>
1313     <li><em>tools</em> - contains the Stacker compiler main program, stkrc
1314     <ul>
1315         <li><em>lib/stkrc</em> - contains the Stacker compiler main program
1316     </ul</li>
1317     <li><em>sample</em> - contains the sample programs</li>
1318 </ul>
1319 </div>
1320 <!-- ======================================================================= -->
1321 <div class="doc_subsection"><a name="lexer"></a>The Lexer</div>
1322 <div class="doc_text">
1323 <p>See projects/Stacker/lib/compiler/Lexer.l</p>
1324 </div>
1325 <!-- ======================================================================= -->
1326 <div class="doc_subsection"><a name="parser"></a>The Parser</div>
1327 <div class="doc_text">
1328 <p>See projects/Stacker/lib/compiler/StackerParser.y</p>
1329 </div>
1330 <!-- ======================================================================= -->
1331 <div class="doc_subsection"><a name="compiler"></a>The Compiler</div>
1332 <div class="doc_text">
1333 <p>See projects/Stacker/lib/compiler/StackerCompiler.cpp</p>
1334 </div>
1335 <!-- ======================================================================= -->
1336 <div class="doc_subsection"><a name="runtime"></a>The Runtime</div>
1337 <div class="doc_text">
1338 <p>See projects/Stacker/lib/runtime/stacker_rt.c</p>
1339 </div>
1340 <!-- ======================================================================= -->
1341 <div class="doc_subsection"><a name="driver"></a>Compiler Driver</div>
1342 <div class="doc_text">
1343 <p>See projects/Stacker/tools/stkrc/stkrc.cpp</p>
1344 </div>
1345 <!-- ======================================================================= -->
1346 <div class="doc_subsection"><a name="tests"></a>Test Programs</div>
1347 <div class="doc_text">
1348 <p>See projects/Stacker/test/*.st</p>
1349 </div>
1350 <!-- ======================================================================= -->
1351 <div class="doc_subsection"> <a name="exercise">Exercise</a></div>
1352 <div class="doc_text">
1353 <p>As you may have noted from a careful inspection of the Built-In word
1354 definitions, the ROLL word is not implemented. This word was left out of 
1355 Stacker on purpose so that it can be an exercise for the student.  The exercise 
1356 is to implement the ROLL functionality (in your own workspace) and build a test 
1357 program for it.  If you can implement ROLL, you understand Stacker and probably 
1358 a fair amount about LLVM since this is one of the more complicated Stacker 
1359 operations. The work will almost be completely limited to the 
1360 <a href="#compiler">compiler</a>.  
1361 <p>The ROLL word is already recognized by both the lexer and parser but ignored 
1362 by the compiler. That means you don't have to futz around with figuring out how
1363 to get the keyword recognized. It already is.  The part of the compiler that
1364 you need to implement is the <code>ROLL</code> case in the 
1365 <code>StackerCompiler::handle_word(int)</code> method.</p> See the
1366 implementations of PICK and SELECT in the same method to get some hints about
1367 how to complete this exercise.<p>
1368 <p>Good luck!</p>
1369 </div>
1370 <!-- ======================================================================= -->
1371 <div class="doc_subsection"><a name="todo">Things Remaining To Be Done</a></div>
1372 <div class="doc_text">
1373 <p>The initial implementation of Stacker has several deficiencies. If you're
1374 interested, here are some things that could be implemented better:</p>
1375 <ol>
1376     <li>Write an LLVM pass to compute the correct stack depth needed by the
1377     program. Currently the stack is set to a fixed number which means programs
1378     with large numbers of definitions might fail.</li>
1379     <li>Write an LLVM pass to optimize the use of the global stack. The code
1380     emitted currently is somewhat wasteful. It gets cleaned up a lot by existing
1381     passes but more could be done.</li>
1382     <li>Add -O -O1 -O2 and -O3 optimization switches to the compiler driver to
1383     allow LLVM optimization without using "opt."</li>
1384     <li>Make the compiler driver use the LLVM linking facilities (with IPO)
1385     before depending on GCC to do the final link.</li>
1386     <li>Clean up parsing. It doesn't handle errors very well.</li>
1387     <li>Rearrange the StackerCompiler.cpp code to make better use of inserting
1388     instructions before a block's terminating instruction. I didn't figure this
1389     technique out until I was nearly done with LLVM. As it is, its a bad example
1390     of how to insert instructions!</li>
1391     <li>Provide for I/O to arbitrary files instead of just stdin/stdout.</li>
1392     <li>Write additional built-in words; with inspiration from FORTH</li>
1393     <li>Write additional sample Stacker programs.</li>
1394     <li>Add your own compiler writing experiences and tips in the 
1395     <a href="#lessons">Lessons I Learned About LLVM</a> section.</li>
1396 </ol>
1397 </div>
1398
1399 <!-- *********************************************************************** -->
1400
1401 <hr>
1402 <address>
1403   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
1404   src="http://jigsaw.w3.org/css-validator/images/vcss" alt="Valid CSS!"></a>
1405   <a href="http://validator.w3.org/check/referer"><img
1406   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01!"></a>
1407
1408   <a href="mailto:rspencer@x10sys.com">Reid Spencer</a><br>
1409   <a href="http://llvm.cs.uiuc.edu">LLVM Compiler Infrastructure</a><br>
1410   Last modified: $Date$
1411 </address>
1412
1413 </body>
1414 </html>