Update CMake.
[oota-llvm.git] / docs / ProgrammersManual.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   <meta http-equiv="Content-type" content="text/html;charset=UTF-8">
6   <title>LLVM Programmer's Manual</title>
7   <link rel="stylesheet" href="llvm.css" type="text/css">
8 </head>
9 <body>
10
11 <div class="doc_title">
12   LLVM Programmer's Manual
13 </div>
14
15 <ol>
16   <li><a href="#introduction">Introduction</a></li>
17   <li><a href="#general">General Information</a>
18     <ul>
19       <li><a href="#stl">The C++ Standard Template Library</a></li>
20 <!--
21       <li>The <tt>-time-passes</tt> option</li>
22       <li>How to use the LLVM Makefile system</li>
23       <li>How to write a regression test</li>
24
25 --> 
26     </ul>
27   </li>
28   <li><a href="#apis">Important and useful LLVM APIs</a>
29     <ul>
30       <li><a href="#isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt>
31 and <tt>dyn_cast&lt;&gt;</tt> templates</a> </li>
32       <li><a href="#string_apis">Passing strings (the <tt>StringRef</tt>
33 and <tt>Twine</tt> classes)</a>
34         <ul>
35           <li><a href="#StringRef">The <tt>StringRef</tt> class</a> </li>
36           <li><a href="#Twine">The <tt>Twine</tt> class</a> </li>
37         </ul>
38       </li>
39       <li><a href="#DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt>
40 option</a>
41         <ul>
42           <li><a href="#DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt>
43 and the <tt>-debug-only</tt> option</a> </li>
44         </ul>
45       </li>
46       <li><a href="#Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
47 option</a></li>
48 <!--
49       <li>The <tt>InstVisitor</tt> template
50       <li>The general graph API
51 --> 
52       <li><a href="#ViewGraph">Viewing graphs while debugging code</a></li>
53     </ul>
54   </li>
55   <li><a href="#datastructure">Picking the Right Data Structure for a Task</a>
56     <ul>
57     <li><a href="#ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
58     <ul>
59       <li><a href="#dss_fixedarrays">Fixed Size Arrays</a></li>
60       <li><a href="#dss_heaparrays">Heap Allocated Arrays</a></li>
61       <li><a href="#dss_smallvector">"llvm/ADT/SmallVector.h"</a></li>
62       <li><a href="#dss_vector">&lt;vector&gt;</a></li>
63       <li><a href="#dss_deque">&lt;deque&gt;</a></li>
64       <li><a href="#dss_list">&lt;list&gt;</a></li>
65       <li><a href="#dss_ilist">llvm/ADT/ilist.h</a></li>
66       <li><a href="#dss_other">Other Sequential Container Options</a></li>
67     </ul></li>
68     <li><a href="#ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
69     <ul>
70       <li><a href="#dss_sortedvectorset">A sorted 'vector'</a></li>
71       <li><a href="#dss_smallset">"llvm/ADT/SmallSet.h"</a></li>
72       <li><a href="#dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a></li>
73       <li><a href="#dss_denseset">"llvm/ADT/DenseSet.h"</a></li>
74       <li><a href="#dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a></li>
75       <li><a href="#dss_set">&lt;set&gt;</a></li>
76       <li><a href="#dss_setvector">"llvm/ADT/SetVector.h"</a></li>
77       <li><a href="#dss_uniquevector">"llvm/ADT/UniqueVector.h"</a></li>
78       <li><a href="#dss_otherset">Other Set-Like ContainerOptions</a></li>
79     </ul></li>
80     <li><a href="#ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
81     <ul>
82       <li><a href="#dss_sortedvectormap">A sorted 'vector'</a></li>
83       <li><a href="#dss_stringmap">"llvm/ADT/StringMap.h"</a></li>
84       <li><a href="#dss_indexedmap">"llvm/ADT/IndexedMap.h"</a></li>
85       <li><a href="#dss_densemap">"llvm/ADT/DenseMap.h"</a></li>
86       <li><a href="#dss_map">&lt;map&gt;</a></li>
87       <li><a href="#dss_othermap">Other Map-Like Container Options</a></li>
88     </ul></li>
89     <li><a href="#ds_string">String-like containers</a>
90     <!--<ul>
91        todo
92     </ul>--></li>
93     <li><a href="#ds_bit">BitVector-like containers</a>
94     <ul>
95       <li><a href="#dss_bitvector">A dense bitvector</a></li>
96       <li><a href="#dss_sparsebitvector">A sparse bitvector</a></li>
97     </ul></li>
98   </ul>
99   </li>
100   <li><a href="#common">Helpful Hints for Common Operations</a>
101     <ul>
102       <li><a href="#inspection">Basic Inspection and Traversal Routines</a>
103         <ul>
104           <li><a href="#iterate_function">Iterating over the <tt>BasicBlock</tt>s
105 in a <tt>Function</tt></a> </li>
106           <li><a href="#iterate_basicblock">Iterating over the <tt>Instruction</tt>s
107 in a <tt>BasicBlock</tt></a> </li>
108           <li><a href="#iterate_institer">Iterating over the <tt>Instruction</tt>s
109 in a <tt>Function</tt></a> </li>
110           <li><a href="#iterate_convert">Turning an iterator into a
111 class pointer</a> </li>
112           <li><a href="#iterate_complex">Finding call sites: a more
113 complex example</a> </li>
114           <li><a href="#calls_and_invokes">Treating calls and invokes
115 the same way</a> </li>
116           <li><a href="#iterate_chains">Iterating over def-use &amp;
117 use-def chains</a> </li>
118           <li><a href="#iterate_preds">Iterating over predecessors &amp;
119 successors of blocks</a></li>
120         </ul>
121       </li>
122       <li><a href="#simplechanges">Making simple changes</a>
123         <ul>
124           <li><a href="#schanges_creating">Creating and inserting new
125                  <tt>Instruction</tt>s</a> </li>
126           <li><a href="#schanges_deleting">Deleting              <tt>Instruction</tt>s</a> </li>
127           <li><a href="#schanges_replacing">Replacing an                 <tt>Instruction</tt>
128 with another <tt>Value</tt></a> </li>
129           <li><a href="#schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a> </li>  
130         </ul>
131       </li>
132       <li><a href="#create_types">How to Create Types</a></li>
133 <!--
134     <li>Working with the Control Flow Graph
135     <ul>
136       <li>Accessing predecessors and successors of a <tt>BasicBlock</tt>
137       <li>
138       <li>
139     </ul>
140 --> 
141     </ul>
142   </li>
143
144   <li><a href="#threading">Threads and LLVM</a>
145   <ul>
146     <li><a href="#startmultithreaded">Entering and Exiting Multithreaded Mode
147         </a></li>
148     <li><a href="#shutdown">Ending execution with <tt>llvm_shutdown()</tt></a></li>
149     <li><a href="#managedstatic">Lazy initialization with <tt>ManagedStatic</tt></a></li>
150   </ul>
151   </li>
152
153   <li><a href="#advanced">Advanced Topics</a>
154   <ul>
155   <li><a href="#TypeResolve">LLVM Type Resolution</a>
156   <ul>
157     <li><a href="#BuildRecType">Basic Recursive Type Construction</a></li>
158     <li><a href="#refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a></li>
159     <li><a href="#PATypeHolder">The PATypeHolder Class</a></li>
160     <li><a href="#AbstractTypeUser">The AbstractTypeUser Class</a></li>
161   </ul></li>
162
163   <li><a href="#SymbolTable">The <tt>ValueSymbolTable</tt> and <tt>TypeSymbolTable</tt> classes</a></li>
164   <li><a href="#UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a></li>
165   </ul></li>
166
167   <li><a href="#coreclasses">The Core LLVM Class Hierarchy Reference</a>
168     <ul>
169       <li><a href="#Type">The <tt>Type</tt> class</a> </li>
170       <li><a href="#Module">The <tt>Module</tt> class</a></li>
171       <li><a href="#Value">The <tt>Value</tt> class</a>
172       <ul>
173         <li><a href="#User">The <tt>User</tt> class</a>
174         <ul>
175           <li><a href="#Instruction">The <tt>Instruction</tt> class</a></li>
176           <li><a href="#Constant">The <tt>Constant</tt> class</a>
177           <ul>
178             <li><a href="#GlobalValue">The <tt>GlobalValue</tt> class</a>
179             <ul>
180               <li><a href="#Function">The <tt>Function</tt> class</a></li>
181               <li><a href="#GlobalVariable">The <tt>GlobalVariable</tt> class</a></li>
182             </ul>
183             </li>
184           </ul>
185           </li>
186         </ul>
187         </li>
188         <li><a href="#BasicBlock">The <tt>BasicBlock</tt> class</a></li>
189         <li><a href="#Argument">The <tt>Argument</tt> class</a></li>
190       </ul>
191       </li>
192     </ul>
193   </li>
194 </ol>
195
196 <div class="doc_author">    
197   <p>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a>, 
198                 <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a>, 
199                 <a href="mailto:ggreif@gmail.com">Gabor Greif</a>, 
200                 <a href="mailto:jstanley@cs.uiuc.edu">Joel Stanley</a>,
201                 <a href="mailto:rspencer@x10sys.com">Reid Spencer</a> and
202                 <a href="mailto:owen@apple.com">Owen Anderson</a></p>
203 </div>
204
205 <!-- *********************************************************************** -->
206 <div class="doc_section">
207   <a name="introduction">Introduction </a>
208 </div>
209 <!-- *********************************************************************** -->
210
211 <div class="doc_text">
212
213 <p>This document is meant to highlight some of the important classes and
214 interfaces available in the LLVM source-base.  This manual is not
215 intended to explain what LLVM is, how it works, and what LLVM code looks
216 like.  It assumes that you know the basics of LLVM and are interested
217 in writing transformations or otherwise analyzing or manipulating the
218 code.</p>
219
220 <p>This document should get you oriented so that you can find your
221 way in the continuously growing source code that makes up the LLVM
222 infrastructure. Note that this manual is not intended to serve as a
223 replacement for reading the source code, so if you think there should be
224 a method in one of these classes to do something, but it's not listed,
225 check the source.  Links to the <a href="/doxygen/">doxygen</a> sources
226 are provided to make this as easy as possible.</p>
227
228 <p>The first section of this document describes general information that is
229 useful to know when working in the LLVM infrastructure, and the second describes
230 the Core LLVM classes.  In the future this manual will be extended with
231 information describing how to use extension libraries, such as dominator
232 information, CFG traversal routines, and useful utilities like the <tt><a
233 href="/doxygen/InstVisitor_8h-source.html">InstVisitor</a></tt> template.</p>
234
235 </div>
236
237 <!-- *********************************************************************** -->
238 <div class="doc_section">
239   <a name="general">General Information</a>
240 </div>
241 <!-- *********************************************************************** -->
242
243 <div class="doc_text">
244
245 <p>This section contains general information that is useful if you are working
246 in the LLVM source-base, but that isn't specific to any particular API.</p>
247
248 </div>
249
250 <!-- ======================================================================= -->
251 <div class="doc_subsection">
252   <a name="stl">The C++ Standard Template Library</a>
253 </div>
254
255 <div class="doc_text">
256
257 <p>LLVM makes heavy use of the C++ Standard Template Library (STL),
258 perhaps much more than you are used to, or have seen before.  Because of
259 this, you might want to do a little background reading in the
260 techniques used and capabilities of the library.  There are many good
261 pages that discuss the STL, and several books on the subject that you
262 can get, so it will not be discussed in this document.</p>
263
264 <p>Here are some useful links:</p>
265
266 <ol>
267
268 <li><a href="http://www.dinkumware.com/refxcpp.html">Dinkumware C++ Library
269 reference</a> - an excellent reference for the STL and other parts of the
270 standard C++ library.</li>
271
272 <li><a href="http://www.tempest-sw.com/cpp/">C++ In a Nutshell</a> - This is an
273 O'Reilly book in the making.  It has a decent Standard Library
274 Reference that rivals Dinkumware's, and is unfortunately no longer free since the
275 book has been published.</li>
276
277 <li><a href="http://www.parashift.com/c++-faq-lite/">C++ Frequently Asked
278 Questions</a></li>
279
280 <li><a href="http://www.sgi.com/tech/stl/">SGI's STL Programmer's Guide</a> -
281 Contains a useful <a
282 href="http://www.sgi.com/tech/stl/stl_introduction.html">Introduction to the
283 STL</a>.</li>
284
285 <li><a href="http://www.research.att.com/%7Ebs/C++.html">Bjarne Stroustrup's C++
286 Page</a></li>
287
288 <li><a href="http://64.78.49.204/">
289 Bruce Eckel's Thinking in C++, 2nd ed. Volume 2 Revision 4.0 (even better, get
290 the book).</a></li>
291
292 </ol>
293   
294 <p>You are also encouraged to take a look at the <a
295 href="CodingStandards.html">LLVM Coding Standards</a> guide which focuses on how
296 to write maintainable code more than where to put your curly braces.</p>
297
298 </div>
299
300 <!-- ======================================================================= -->
301 <div class="doc_subsection">
302   <a name="stl">Other useful references</a>
303 </div>
304
305 <div class="doc_text">
306
307 <ol>
308 <li><a href="http://www.psc.edu/%7Esemke/cvs_branches.html">CVS
309 Branch and Tag Primer</a></li>
310 <li><a href="http://www.fortran-2000.com/ArnaudRecipes/sharedlib.html">Using
311 static and shared libraries across platforms</a></li>
312 </ol>
313
314 </div>
315
316 <!-- *********************************************************************** -->
317 <div class="doc_section">
318   <a name="apis">Important and useful LLVM APIs</a>
319 </div>
320 <!-- *********************************************************************** -->
321
322 <div class="doc_text">
323
324 <p>Here we highlight some LLVM APIs that are generally useful and good to
325 know about when writing transformations.</p>
326
327 </div>
328
329 <!-- ======================================================================= -->
330 <div class="doc_subsection">
331   <a name="isa">The <tt>isa&lt;&gt;</tt>, <tt>cast&lt;&gt;</tt> and
332   <tt>dyn_cast&lt;&gt;</tt> templates</a>
333 </div>
334
335 <div class="doc_text">
336
337 <p>The LLVM source-base makes extensive use of a custom form of RTTI.
338 These templates have many similarities to the C++ <tt>dynamic_cast&lt;&gt;</tt>
339 operator, but they don't have some drawbacks (primarily stemming from
340 the fact that <tt>dynamic_cast&lt;&gt;</tt> only works on classes that
341 have a v-table). Because they are used so often, you must know what they
342 do and how they work. All of these templates are defined in the <a
343  href="/doxygen/Casting_8h-source.html"><tt>llvm/Support/Casting.h</tt></a>
344 file (note that you very rarely have to include this file directly).</p>
345
346 <dl>
347   <dt><tt>isa&lt;&gt;</tt>: </dt>
348
349   <dd><p>The <tt>isa&lt;&gt;</tt> operator works exactly like the Java
350   "<tt>instanceof</tt>" operator.  It returns true or false depending on whether
351   a reference or pointer points to an instance of the specified class.  This can
352   be very useful for constraint checking of various sorts (example below).</p>
353   </dd>
354
355   <dt><tt>cast&lt;&gt;</tt>: </dt>
356
357   <dd><p>The <tt>cast&lt;&gt;</tt> operator is a "checked cast" operation. It
358   converts a pointer or reference from a base class to a derived class, causing
359   an assertion failure if it is not really an instance of the right type.  This
360   should be used in cases where you have some information that makes you believe
361   that something is of the right type.  An example of the <tt>isa&lt;&gt;</tt>
362   and <tt>cast&lt;&gt;</tt> template is:</p>
363
364 <div class="doc_code">
365 <pre>
366 static bool isLoopInvariant(const <a href="#Value">Value</a> *V, const Loop *L) {
367   if (isa&lt;<a href="#Constant">Constant</a>&gt;(V) || isa&lt;<a href="#Argument">Argument</a>&gt;(V) || isa&lt;<a href="#GlobalValue">GlobalValue</a>&gt;(V))
368     return true;
369
370   // <i>Otherwise, it must be an instruction...</i>
371   return !L-&gt;contains(cast&lt;<a href="#Instruction">Instruction</a>&gt;(V)-&gt;getParent());
372 }
373 </pre>
374 </div>
375
376   <p>Note that you should <b>not</b> use an <tt>isa&lt;&gt;</tt> test followed
377   by a <tt>cast&lt;&gt;</tt>, for that use the <tt>dyn_cast&lt;&gt;</tt>
378   operator.</p>
379
380   </dd>
381
382   <dt><tt>dyn_cast&lt;&gt;</tt>:</dt>
383
384   <dd><p>The <tt>dyn_cast&lt;&gt;</tt> operator is a "checking cast" operation.
385   It checks to see if the operand is of the specified type, and if so, returns a
386   pointer to it (this operator does not work with references). If the operand is
387   not of the correct type, a null pointer is returned.  Thus, this works very
388   much like the <tt>dynamic_cast&lt;&gt;</tt> operator in C++, and should be
389   used in the same circumstances.  Typically, the <tt>dyn_cast&lt;&gt;</tt>
390   operator is used in an <tt>if</tt> statement or some other flow control
391   statement like this:</p>
392
393 <div class="doc_code">
394 <pre>
395 if (<a href="#AllocationInst">AllocationInst</a> *AI = dyn_cast&lt;<a href="#AllocationInst">AllocationInst</a>&gt;(Val)) {
396   // <i>...</i>
397 }
398 </pre>
399 </div>
400    
401   <p>This form of the <tt>if</tt> statement effectively combines together a call
402   to <tt>isa&lt;&gt;</tt> and a call to <tt>cast&lt;&gt;</tt> into one
403   statement, which is very convenient.</p>
404
405   <p>Note that the <tt>dyn_cast&lt;&gt;</tt> operator, like C++'s
406   <tt>dynamic_cast&lt;&gt;</tt> or Java's <tt>instanceof</tt> operator, can be
407   abused.  In particular, you should not use big chained <tt>if/then/else</tt>
408   blocks to check for lots of different variants of classes.  If you find
409   yourself wanting to do this, it is much cleaner and more efficient to use the
410   <tt>InstVisitor</tt> class to dispatch over the instruction type directly.</p>
411
412   </dd>
413
414   <dt><tt>cast_or_null&lt;&gt;</tt>: </dt>
415   
416   <dd><p>The <tt>cast_or_null&lt;&gt;</tt> operator works just like the
417   <tt>cast&lt;&gt;</tt> operator, except that it allows for a null pointer as an
418   argument (which it then propagates).  This can sometimes be useful, allowing
419   you to combine several null checks into one.</p></dd>
420
421   <dt><tt>dyn_cast_or_null&lt;&gt;</tt>: </dt>
422
423   <dd><p>The <tt>dyn_cast_or_null&lt;&gt;</tt> operator works just like the
424   <tt>dyn_cast&lt;&gt;</tt> operator, except that it allows for a null pointer
425   as an argument (which it then propagates).  This can sometimes be useful,
426   allowing you to combine several null checks into one.</p></dd>
427
428 </dl>
429
430 <p>These five templates can be used with any classes, whether they have a
431 v-table or not.  To add support for these templates, you simply need to add
432 <tt>classof</tt> static methods to the class you are interested casting
433 to. Describing this is currently outside the scope of this document, but there
434 are lots of examples in the LLVM source base.</p>
435
436 </div>
437
438
439 <!-- ======================================================================= -->
440 <div class="doc_subsection">
441   <a name="string_apis">Passing strings (the <tt>StringRef</tt>
442 and <tt>Twine</tt> classes)</a>
443 </div>
444
445 <div class="doc_text">
446
447 <p>Although LLVM generally does not do much string manipulation, we do have
448 several important APIs which take strings.  Two important examples are the
449 Value class -- which has names for instructions, functions, etc. -- and the
450 StringMap class which is used extensively in LLVM and Clang.</p>
451
452 <p>These are generic classes, and they need to be able to accept strings which
453 may have embedded null characters.  Therefore, they cannot simply take
454 a <tt>const char *</tt>, and taking a <tt>const std::string&amp;</tt> requires
455 clients to perform a heap allocation which is usually unnecessary.  Instead,
456 many LLVM APIs use a <tt>const StringRef&amp;</tt> or a <tt>const 
457 Twine&amp;</tt> for passing strings efficiently.</p>
458
459 </div>
460
461 <!-- _______________________________________________________________________ -->
462 <div class="doc_subsubsection">
463   <a name="StringRef">The <tt>StringRef</tt> class</a>
464 </div>
465
466 <div class="doc_text">
467
468 <p>The <tt>StringRef</tt> data type represents a reference to a constant string
469 (a character array and a length) and supports the common operations available
470 on <tt>std:string</tt>, but does not require heap allocation.</p>
471
472 <p>It can be implicitly constructed using a C style null-terminated string,
473 an <tt>std::string</tt>, or explicitly with a character pointer and length.
474 For example, the <tt>StringRef</tt> find function is declared as:</p>
475
476 <div class="doc_code">
477   iterator find(const StringRef &amp;Key);
478 </div>
479
480 <p>and clients can call it using any one of:</p>
481
482 <div class="doc_code">
483 <pre>
484   Map.find("foo");                 <i>// Lookup "foo"</i>
485   Map.find(std::string("bar"));    <i>// Lookup "bar"</i>
486   Map.find(StringRef("\0baz", 4)); <i>// Lookup "\0baz"</i>
487 </pre>
488 </div>
489
490 <p>Similarly, APIs which need to return a string may return a <tt>StringRef</tt>
491 instance, which can be used directly or converted to an <tt>std::string</tt>
492 using the <tt>str</tt> member function.  See 
493 "<tt><a href="/doxygen/classllvm_1_1StringRef_8h-source.html">llvm/ADT/StringRef.h</a></tt>"
494 for more information.</p>
495
496 <p>You should rarely use the <tt>StringRef</tt> class directly, because it contains
497 pointers to external memory it is not generally safe to store an instance of the
498 class (unless you know that the external storage will not be freed).</p>
499
500 </div>
501
502 <!-- _______________________________________________________________________ -->
503 <div class="doc_subsubsection">
504   <a name="Twine">The <tt>Twine</tt> class</a>
505 </div>
506
507 <div class="doc_text">
508
509 <p>The <tt>Twine</tt> class is an efficient way for APIs to accept concatenated
510 strings.  For example, a common LLVM paradigm is to name one instruction based on
511 the name of another instruction with a suffix, for example:</p>
512
513 <div class="doc_code">
514 <pre>
515     New = CmpInst::Create(<i>...</i>, SO->getName() + ".cmp");
516 </pre>
517 </div>
518
519 <p>The <tt>Twine</tt> class is effectively a
520 lightweight <a href="http://en.wikipedia.org/wiki/Rope_(computer_science)">rope</a>
521 which points to temporary (stack allocated) objects.  Twines can be implicitly
522 constructed as the result of the plus operator applied to strings (i.e., a C
523 strings, an <tt>std::string</tt>, or a <tt>StringRef</tt>).  The twine delays the
524 actual concatentation of strings until it is actually required, at which point
525 it can be efficiently rendered directly into a character array.  This avoids
526 unnecessary heap allocation involved in constructing the temporary results of
527 string concatenation. See
528 "<tt><a href="/doxygen/classllvm_1_1Twine_8h-source.html">llvm/ADT/Twine.h</a></tt>"
529 for more information.</p>
530
531 <p>As with a <tt>StringRef</tt>, <tt>Twine</tt> objects point to external memory
532 and should almost never be stored or mentioned directly.  They are intended
533 solely for use when defining a function which should be able to efficiently
534 accept concatenated strings.</p>
535
536 </div>
537
538
539 <!-- ======================================================================= -->
540 <div class="doc_subsection">
541   <a name="DEBUG">The <tt>DEBUG()</tt> macro and <tt>-debug</tt> option</a>
542 </div>
543
544 <div class="doc_text">
545
546 <p>Often when working on your pass you will put a bunch of debugging printouts
547 and other code into your pass.  After you get it working, you want to remove
548 it, but you may need it again in the future (to work out new bugs that you run
549 across).</p>
550
551 <p> Naturally, because of this, you don't want to delete the debug printouts,
552 but you don't want them to always be noisy.  A standard compromise is to comment
553 them out, allowing you to enable them if you need them in the future.</p>
554
555 <p>The "<tt><a href="/doxygen/Debug_8h-source.html">llvm/Support/Debug.h</a></tt>"
556 file provides a macro named <tt>DEBUG()</tt> that is a much nicer solution to
557 this problem.  Basically, you can put arbitrary code into the argument of the
558 <tt>DEBUG</tt> macro, and it is only executed if '<tt>opt</tt>' (or any other
559 tool) is run with the '<tt>-debug</tt>' command line argument:</p>
560
561 <div class="doc_code">
562 <pre>
563 DEBUG(errs() &lt;&lt; "I am here!\n");
564 </pre>
565 </div>
566
567 <p>Then you can run your pass like this:</p>
568
569 <div class="doc_code">
570 <pre>
571 $ opt &lt; a.bc &gt; /dev/null -mypass
572 <i>&lt;no output&gt;</i>
573 $ opt &lt; a.bc &gt; /dev/null -mypass -debug
574 I am here!
575 </pre>
576 </div>
577
578 <p>Using the <tt>DEBUG()</tt> macro instead of a home-brewed solution allows you
579 to not have to create "yet another" command line option for the debug output for
580 your pass.  Note that <tt>DEBUG()</tt> macros are disabled for optimized builds,
581 so they do not cause a performance impact at all (for the same reason, they
582 should also not contain side-effects!).</p>
583
584 <p>One additional nice thing about the <tt>DEBUG()</tt> macro is that you can
585 enable or disable it directly in gdb.  Just use "<tt>set DebugFlag=0</tt>" or
586 "<tt>set DebugFlag=1</tt>" from the gdb if the program is running.  If the
587 program hasn't been started yet, you can always just run it with
588 <tt>-debug</tt>.</p>
589
590 </div>
591
592 <!-- _______________________________________________________________________ -->
593 <div class="doc_subsubsection">
594   <a name="DEBUG_TYPE">Fine grained debug info with <tt>DEBUG_TYPE</tt> and
595   the <tt>-debug-only</tt> option</a>
596 </div>
597
598 <div class="doc_text">
599
600 <p>Sometimes you may find yourself in a situation where enabling <tt>-debug</tt>
601 just turns on <b>too much</b> information (such as when working on the code
602 generator).  If you want to enable debug information with more fine-grained
603 control, you define the <tt>DEBUG_TYPE</tt> macro and the <tt>-debug</tt> only
604 option as follows:</p>
605
606 <div class="doc_code">
607 <pre>
608 #undef  DEBUG_TYPE
609 DEBUG(errs() &lt;&lt; "No debug type\n");
610 #define DEBUG_TYPE "foo"
611 DEBUG(errs() &lt;&lt; "'foo' debug type\n");
612 #undef  DEBUG_TYPE
613 #define DEBUG_TYPE "bar"
614 DEBUG(errs() &lt;&lt; "'bar' debug type\n"));
615 #undef  DEBUG_TYPE
616 #define DEBUG_TYPE ""
617 DEBUG(errs() &lt;&lt; "No debug type (2)\n");
618 </pre>
619 </div>
620
621 <p>Then you can run your pass like this:</p>
622
623 <div class="doc_code">
624 <pre>
625 $ opt &lt; a.bc &gt; /dev/null -mypass
626 <i>&lt;no output&gt;</i>
627 $ opt &lt; a.bc &gt; /dev/null -mypass -debug
628 No debug type
629 'foo' debug type
630 'bar' debug type
631 No debug type (2)
632 $ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=foo
633 'foo' debug type
634 $ opt &lt; a.bc &gt; /dev/null -mypass -debug-only=bar
635 'bar' debug type
636 </pre>
637 </div>
638
639 <p>Of course, in practice, you should only set <tt>DEBUG_TYPE</tt> at the top of
640 a file, to specify the debug type for the entire module (if you do this before
641 you <tt>#include "llvm/Support/Debug.h"</tt>, you don't have to insert the ugly
642 <tt>#undef</tt>'s).  Also, you should use names more meaningful than "foo" and
643 "bar", because there is no system in place to ensure that names do not
644 conflict. If two different modules use the same string, they will all be turned
645 on when the name is specified. This allows, for example, all debug information
646 for instruction scheduling to be enabled with <tt>-debug-type=InstrSched</tt>,
647 even if the source lives in multiple files.</p>
648
649 </div>
650
651 <!-- ======================================================================= -->
652 <div class="doc_subsection">
653   <a name="Statistic">The <tt>Statistic</tt> class &amp; <tt>-stats</tt>
654   option</a>
655 </div>
656
657 <div class="doc_text">
658
659 <p>The "<tt><a
660 href="/doxygen/Statistic_8h-source.html">llvm/ADT/Statistic.h</a></tt>" file
661 provides a class named <tt>Statistic</tt> that is used as a unified way to
662 keep track of what the LLVM compiler is doing and how effective various
663 optimizations are.  It is useful to see what optimizations are contributing to
664 making a particular program run faster.</p>
665
666 <p>Often you may run your pass on some big program, and you're interested to see
667 how many times it makes a certain transformation.  Although you can do this with
668 hand inspection, or some ad-hoc method, this is a real pain and not very useful
669 for big programs.  Using the <tt>Statistic</tt> class makes it very easy to
670 keep track of this information, and the calculated information is presented in a
671 uniform manner with the rest of the passes being executed.</p>
672
673 <p>There are many examples of <tt>Statistic</tt> uses, but the basics of using
674 it are as follows:</p>
675
676 <ol>
677     <li><p>Define your statistic like this:</p>
678
679 <div class="doc_code">
680 <pre>
681 #define <a href="#DEBUG_TYPE">DEBUG_TYPE</a> "mypassname"   <i>// This goes before any #includes.</i>
682 STATISTIC(NumXForms, "The # of times I did stuff");
683 </pre>
684 </div>
685
686   <p>The <tt>STATISTIC</tt> macro defines a static variable, whose name is
687     specified by the first argument.  The pass name is taken from the DEBUG_TYPE
688     macro, and the description is taken from the second argument.  The variable
689     defined ("NumXForms" in this case) acts like an unsigned integer.</p></li>
690
691     <li><p>Whenever you make a transformation, bump the counter:</p>
692
693 <div class="doc_code">
694 <pre>
695 ++NumXForms;   // <i>I did stuff!</i>
696 </pre>
697 </div>
698
699     </li>
700   </ol>
701
702   <p>That's all you have to do.  To get '<tt>opt</tt>' to print out the
703   statistics gathered, use the '<tt>-stats</tt>' option:</p>
704
705 <div class="doc_code">
706 <pre>
707 $ opt -stats -mypassname &lt; program.bc &gt; /dev/null
708 <i>... statistics output ...</i>
709 </pre>
710 </div>
711
712   <p> When running <tt>opt</tt> on a C file from the SPEC benchmark
713 suite, it gives a report that looks like this:</p>
714
715 <div class="doc_code">
716 <pre>
717    7646 bitcodewriter   - Number of normal instructions
718     725 bitcodewriter   - Number of oversized instructions
719  129996 bitcodewriter   - Number of bitcode bytes written
720    2817 raise           - Number of insts DCEd or constprop'd
721    3213 raise           - Number of cast-of-self removed
722    5046 raise           - Number of expression trees converted
723      75 raise           - Number of other getelementptr's formed
724     138 raise           - Number of load/store peepholes
725      42 deadtypeelim    - Number of unused typenames removed from symtab
726     392 funcresolve     - Number of varargs functions resolved
727      27 globaldce       - Number of global variables removed
728       2 adce            - Number of basic blocks removed
729     134 cee             - Number of branches revectored
730      49 cee             - Number of setcc instruction eliminated
731     532 gcse            - Number of loads removed
732    2919 gcse            - Number of instructions removed
733      86 indvars         - Number of canonical indvars added
734      87 indvars         - Number of aux indvars removed
735      25 instcombine     - Number of dead inst eliminate
736     434 instcombine     - Number of insts combined
737     248 licm            - Number of load insts hoisted
738    1298 licm            - Number of insts hoisted to a loop pre-header
739       3 licm            - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
740      75 mem2reg         - Number of alloca's promoted
741    1444 cfgsimplify     - Number of blocks simplified
742 </pre>
743 </div>
744
745 <p>Obviously, with so many optimizations, having a unified framework for this
746 stuff is very nice.  Making your pass fit well into the framework makes it more
747 maintainable and useful.</p>
748
749 </div>
750
751 <!-- ======================================================================= -->
752 <div class="doc_subsection">
753   <a name="ViewGraph">Viewing graphs while debugging code</a>
754 </div>
755
756 <div class="doc_text">
757
758 <p>Several of the important data structures in LLVM are graphs: for example
759 CFGs made out of LLVM <a href="#BasicBlock">BasicBlock</a>s, CFGs made out of
760 LLVM <a href="CodeGenerator.html#machinebasicblock">MachineBasicBlock</a>s, and
761 <a href="CodeGenerator.html#selectiondag_intro">Instruction Selection
762 DAGs</a>.  In many cases, while debugging various parts of the compiler, it is
763 nice to instantly visualize these graphs.</p>
764
765 <p>LLVM provides several callbacks that are available in a debug build to do
766 exactly that.  If you call the <tt>Function::viewCFG()</tt> method, for example,
767 the current LLVM tool will pop up a window containing the CFG for the function
768 where each basic block is a node in the graph, and each node contains the
769 instructions in the block.  Similarly, there also exists 
770 <tt>Function::viewCFGOnly()</tt> (does not include the instructions), the
771 <tt>MachineFunction::viewCFG()</tt> and <tt>MachineFunction::viewCFGOnly()</tt>,
772 and the <tt>SelectionDAG::viewGraph()</tt> methods.  Within GDB, for example,
773 you can usually use something like <tt>call DAG.viewGraph()</tt> to pop
774 up a window.  Alternatively, you can sprinkle calls to these functions in your
775 code in places you want to debug.</p>
776
777 <p>Getting this to work requires a small amount of configuration.  On Unix
778 systems with X11, install the <a href="http://www.graphviz.org">graphviz</a>
779 toolkit, and make sure 'dot' and 'gv' are in your path.  If you are running on
780 Mac OS/X, download and install the Mac OS/X <a 
781 href="http://www.pixelglow.com/graphviz/">Graphviz program</a>, and add
782 <tt>/Applications/Graphviz.app/Contents/MacOS/</tt> (or wherever you install
783 it) to your path.  Once in your system and path are set up, rerun the LLVM
784 configure script and rebuild LLVM to enable this functionality.</p>
785
786 <p><tt>SelectionDAG</tt> has been extended to make it easier to locate
787 <i>interesting</i> nodes in large complex graphs.  From gdb, if you
788 <tt>call DAG.setGraphColor(<i>node</i>, "<i>color</i>")</tt>, then the
789 next <tt>call DAG.viewGraph()</tt> would highlight the node in the
790 specified color (choices of colors can be found at <a
791 href="http://www.graphviz.org/doc/info/colors.html">colors</a>.) More
792 complex node attributes can be provided with <tt>call
793 DAG.setGraphAttrs(<i>node</i>, "<i>attributes</i>")</tt> (choices can be
794 found at <a href="http://www.graphviz.org/doc/info/attrs.html">Graph
795 Attributes</a>.)  If you want to restart and clear all the current graph
796 attributes, then you can <tt>call DAG.clearGraphAttrs()</tt>. </p>
797
798 </div>
799
800 <!-- *********************************************************************** -->
801 <div class="doc_section">
802   <a name="datastructure">Picking the Right Data Structure for a Task</a>
803 </div>
804 <!-- *********************************************************************** -->
805
806 <div class="doc_text">
807
808 <p>LLVM has a plethora of data structures in the <tt>llvm/ADT/</tt> directory,
809  and we commonly use STL data structures.  This section describes the trade-offs
810  you should consider when you pick one.</p>
811
812 <p>
813 The first step is a choose your own adventure: do you want a sequential
814 container, a set-like container, or a map-like container?  The most important
815 thing when choosing a container is the algorithmic properties of how you plan to
816 access the container.  Based on that, you should use:</p>
817
818 <ul>
819 <li>a <a href="#ds_map">map-like</a> container if you need efficient look-up
820     of an value based on another value.  Map-like containers also support
821     efficient queries for containment (whether a key is in the map).  Map-like
822     containers generally do not support efficient reverse mapping (values to
823     keys).  If you need that, use two maps.  Some map-like containers also
824     support efficient iteration through the keys in sorted order.  Map-like
825     containers are the most expensive sort, only use them if you need one of
826     these capabilities.</li>
827
828 <li>a <a href="#ds_set">set-like</a> container if you need to put a bunch of
829     stuff into a container that automatically eliminates duplicates.  Some
830     set-like containers support efficient iteration through the elements in
831     sorted order.  Set-like containers are more expensive than sequential
832     containers.
833 </li>
834
835 <li>a <a href="#ds_sequential">sequential</a> container provides
836     the most efficient way to add elements and keeps track of the order they are
837     added to the collection.  They permit duplicates and support efficient
838     iteration, but do not support efficient look-up based on a key.
839 </li>
840
841 <li>a <a href="#ds_string">string</a> container is a specialized sequential
842     container or reference structure that is used for character or byte
843     arrays.</li>
844
845 <li>a <a href="#ds_bit">bit</a> container provides an efficient way to store and
846     perform set operations on sets of numeric id's, while automatically
847     eliminating duplicates.  Bit containers require a maximum of 1 bit for each
848     identifier you want to store.
849 </li>
850 </ul>
851
852 <p>
853 Once the proper category of container is determined, you can fine tune the
854 memory use, constant factors, and cache behaviors of access by intelligently
855 picking a member of the category.  Note that constant factors and cache behavior
856 can be a big deal.  If you have a vector that usually only contains a few
857 elements (but could contain many), for example, it's much better to use
858 <a href="#dss_smallvector">SmallVector</a> than <a href="#dss_vector">vector</a>
859 .  Doing so avoids (relatively) expensive malloc/free calls, which dwarf the
860 cost of adding the elements to the container. </p>
861
862 </div>
863
864 <!-- ======================================================================= -->
865 <div class="doc_subsection">
866   <a name="ds_sequential">Sequential Containers (std::vector, std::list, etc)</a>
867 </div>
868
869 <div class="doc_text">
870 There are a variety of sequential containers available for you, based on your
871 needs.  Pick the first in this section that will do what you want.
872 </div>
873
874 <!-- _______________________________________________________________________ -->
875 <div class="doc_subsubsection">
876   <a name="dss_fixedarrays">Fixed Size Arrays</a>
877 </div>
878
879 <div class="doc_text">
880 <p>Fixed size arrays are very simple and very fast.  They are good if you know
881 exactly how many elements you have, or you have a (low) upper bound on how many
882 you have.</p>
883 </div>
884
885 <!-- _______________________________________________________________________ -->
886 <div class="doc_subsubsection">
887   <a name="dss_heaparrays">Heap Allocated Arrays</a>
888 </div>
889
890 <div class="doc_text">
891 <p>Heap allocated arrays (new[] + delete[]) are also simple.  They are good if
892 the number of elements is variable, if you know how many elements you will need
893 before the array is allocated, and if the array is usually large (if not,
894 consider a <a href="#dss_smallvector">SmallVector</a>).  The cost of a heap
895 allocated array is the cost of the new/delete (aka malloc/free).  Also note that
896 if you are allocating an array of a type with a constructor, the constructor and
897 destructors will be run for every element in the array (re-sizable vectors only
898 construct those elements actually used).</p>
899 </div>
900
901 <!-- _______________________________________________________________________ -->
902 <div class="doc_subsubsection">
903   <a name="dss_smallvector">"llvm/ADT/SmallVector.h"</a>
904 </div>
905
906 <div class="doc_text">
907 <p><tt>SmallVector&lt;Type, N&gt;</tt> is a simple class that looks and smells
908 just like <tt>vector&lt;Type&gt;</tt>:
909 it supports efficient iteration, lays out elements in memory order (so you can
910 do pointer arithmetic between elements), supports efficient push_back/pop_back
911 operations, supports efficient random access to its elements, etc.</p>
912
913 <p>The advantage of SmallVector is that it allocates space for
914 some number of elements (N) <b>in the object itself</b>.  Because of this, if
915 the SmallVector is dynamically smaller than N, no malloc is performed.  This can
916 be a big win in cases where the malloc/free call is far more expensive than the
917 code that fiddles around with the elements.</p>
918
919 <p>This is good for vectors that are "usually small" (e.g. the number of
920 predecessors/successors of a block is usually less than 8).  On the other hand,
921 this makes the size of the SmallVector itself large, so you don't want to
922 allocate lots of them (doing so will waste a lot of space).  As such,
923 SmallVectors are most useful when on the stack.</p>
924
925 <p>SmallVector also provides a nice portable and efficient replacement for
926 <tt>alloca</tt>.</p>
927
928 </div>
929
930 <!-- _______________________________________________________________________ -->
931 <div class="doc_subsubsection">
932   <a name="dss_vector">&lt;vector&gt;</a>
933 </div>
934
935 <div class="doc_text">
936 <p>
937 std::vector is well loved and respected.  It is useful when SmallVector isn't:
938 when the size of the vector is often large (thus the small optimization will
939 rarely be a benefit) or if you will be allocating many instances of the vector
940 itself (which would waste space for elements that aren't in the container).
941 vector is also useful when interfacing with code that expects vectors :).
942 </p>
943
944 <p>One worthwhile note about std::vector: avoid code like this:</p>
945
946 <div class="doc_code">
947 <pre>
948 for ( ... ) {
949    std::vector&lt;foo&gt; V;
950    use V;
951 }
952 </pre>
953 </div>
954
955 <p>Instead, write this as:</p>
956
957 <div class="doc_code">
958 <pre>
959 std::vector&lt;foo&gt; V;
960 for ( ... ) {
961    use V;
962    V.clear();
963 }
964 </pre>
965 </div>
966
967 <p>Doing so will save (at least) one heap allocation and free per iteration of
968 the loop.</p>
969
970 </div>
971
972 <!-- _______________________________________________________________________ -->
973 <div class="doc_subsubsection">
974   <a name="dss_deque">&lt;deque&gt;</a>
975 </div>
976
977 <div class="doc_text">
978 <p>std::deque is, in some senses, a generalized version of std::vector.  Like
979 std::vector, it provides constant time random access and other similar
980 properties, but it also provides efficient access to the front of the list.  It
981 does not guarantee continuity of elements within memory.</p>
982
983 <p>In exchange for this extra flexibility, std::deque has significantly higher
984 constant factor costs than std::vector.  If possible, use std::vector or
985 something cheaper.</p>
986 </div>
987
988 <!-- _______________________________________________________________________ -->
989 <div class="doc_subsubsection">
990   <a name="dss_list">&lt;list&gt;</a>
991 </div>
992
993 <div class="doc_text">
994 <p>std::list is an extremely inefficient class that is rarely useful.
995 It performs a heap allocation for every element inserted into it, thus having an
996 extremely high constant factor, particularly for small data types.  std::list
997 also only supports bidirectional iteration, not random access iteration.</p>
998
999 <p>In exchange for this high cost, std::list supports efficient access to both
1000 ends of the list (like std::deque, but unlike std::vector or SmallVector).  In
1001 addition, the iterator invalidation characteristics of std::list are stronger
1002 than that of a vector class: inserting or removing an element into the list does
1003 not invalidate iterator or pointers to other elements in the list.</p>
1004 </div>
1005
1006 <!-- _______________________________________________________________________ -->
1007 <div class="doc_subsubsection">
1008   <a name="dss_ilist">llvm/ADT/ilist.h</a>
1009 </div>
1010
1011 <div class="doc_text">
1012 <p><tt>ilist&lt;T&gt;</tt> implements an 'intrusive' doubly-linked list.  It is
1013 intrusive, because it requires the element to store and provide access to the
1014 prev/next pointers for the list.</p>
1015
1016 <p><tt>ilist</tt> has the same drawbacks as <tt>std::list</tt>, and additionally
1017 requires an <tt>ilist_traits</tt> implementation for the element type, but it
1018 provides some novel characteristics.  In particular, it can efficiently store
1019 polymorphic objects, the traits class is informed when an element is inserted or
1020 removed from the list, and <tt>ilist</tt>s are guaranteed to support a
1021 constant-time splice operation.</p>
1022
1023 <p>These properties are exactly what we want for things like
1024 <tt>Instruction</tt>s and basic blocks, which is why these are implemented with
1025 <tt>ilist</tt>s.</p>
1026
1027 Related classes of interest are explained in the following subsections:
1028     <ul>
1029       <li><a href="#dss_ilist_traits">ilist_traits</a></li>
1030       <li><a href="#dss_iplist">iplist</a></li>
1031       <li><a href="#dss_ilist_node">llvm/ADT/ilist_node.h</a></li>
1032       <li><a href="#dss_ilist_sentinel">Sentinels</a></li>
1033     </ul>
1034 </div>
1035
1036 <!-- _______________________________________________________________________ -->
1037 <div class="doc_subsubsection">
1038   <a name="dss_ilist_traits">ilist_traits</a>
1039 </div>
1040
1041 <div class="doc_text">
1042 <p><tt>ilist_traits&lt;T&gt;</tt> is <tt>ilist&lt;T&gt;</tt>'s customization
1043 mechanism. <tt>iplist&lt;T&gt;</tt> (and consequently <tt>ilist&lt;T&gt;</tt>)
1044 publicly derive from this traits class.</p>
1045 </div>
1046
1047 <!-- _______________________________________________________________________ -->
1048 <div class="doc_subsubsection">
1049   <a name="dss_iplist">iplist</a>
1050 </div>
1051
1052 <div class="doc_text">
1053 <p><tt>iplist&lt;T&gt;</tt> is <tt>ilist&lt;T&gt;</tt>'s base and as such
1054 supports a slightly narrower interface. Notably, inserters from
1055 <tt>T&amp;</tt> are absent.</p>
1056
1057 <p><tt>ilist_traits&lt;T&gt;</tt> is a public base of this class and can be
1058 used for a wide variety of customizations.</p>
1059 </div>
1060
1061 <!-- _______________________________________________________________________ -->
1062 <div class="doc_subsubsection">
1063   <a name="dss_ilist_node">llvm/ADT/ilist_node.h</a>
1064 </div>
1065
1066 <div class="doc_text">
1067 <p><tt>ilist_node&lt;T&gt;</tt> implements a the forward and backward links
1068 that are expected by the <tt>ilist&lt;T&gt;</tt> (and analogous containers)
1069 in the default manner.</p>
1070
1071 <p><tt>ilist_node&lt;T&gt;</tt>s are meant to be embedded in the node type
1072 <tt>T</tt>, usually <tt>T</tt> publicly derives from
1073 <tt>ilist_node&lt;T&gt;</tt>.</p>
1074 </div>
1075
1076 <!-- _______________________________________________________________________ -->
1077 <div class="doc_subsubsection">
1078   <a name="dss_ilist_sentinel">Sentinels</a>
1079 </div>
1080
1081 <div class="doc_text">
1082 <p><tt>ilist</tt>s have another speciality that must be considered. To be a good
1083 citizen in the C++ ecosystem, it needs to support the standard container
1084 operations, such as <tt>begin</tt> and <tt>end</tt> iterators, etc. Also, the
1085 <tt>operator--</tt> must work correctly on the <tt>end</tt> iterator in the
1086 case of non-empty <tt>ilist</tt>s.</p>
1087
1088 <p>The only sensible solution to this problem is to allocate a so-called
1089 <i>sentinel</i> along with the intrusive list, which serves as the <tt>end</tt>
1090 iterator, providing the back-link to the last element. However conforming to the
1091 C++ convention it is illegal to <tt>operator++</tt> beyond the sentinel and it
1092 also must not be dereferenced.</p>
1093
1094 <p>These constraints allow for some implementation freedom to the <tt>ilist</tt>
1095 how to allocate and store the sentinel. The corresponding policy is dictated
1096 by <tt>ilist_traits&lt;T&gt;</tt>. By default a <tt>T</tt> gets heap-allocated
1097 whenever the need for a sentinel arises.</p>
1098
1099 <p>While the default policy is sufficient in most cases, it may break down when
1100 <tt>T</tt> does not provide a default constructor. Also, in the case of many
1101 instances of <tt>ilist</tt>s, the memory overhead of the associated sentinels
1102 is wasted. To alleviate the situation with numerous and voluminous
1103 <tt>T</tt>-sentinels, sometimes a trick is employed, leading to <i>ghostly
1104 sentinels</i>.</p>
1105
1106 <p>Ghostly sentinels are obtained by specially-crafted <tt>ilist_traits&lt;T&gt;</tt>
1107 which superpose the sentinel with the <tt>ilist</tt> instance in memory. Pointer
1108 arithmetic is used to obtain the sentinel, which is relative to the
1109 <tt>ilist</tt>'s <tt>this</tt> pointer. The <tt>ilist</tt> is augmented by an
1110 extra pointer, which serves as the back-link of the sentinel. This is the only
1111 field in the ghostly sentinel which can be legally accessed.</p>
1112 </div>
1113
1114 <!-- _______________________________________________________________________ -->
1115 <div class="doc_subsubsection">
1116   <a name="dss_other">Other Sequential Container options</a>
1117 </div>
1118
1119 <div class="doc_text">
1120 <p>Other STL containers are available, such as std::string.</p>
1121
1122 <p>There are also various STL adapter classes such as std::queue,
1123 std::priority_queue, std::stack, etc.  These provide simplified access to an
1124 underlying container but don't affect the cost of the container itself.</p>
1125
1126 </div>
1127
1128
1129 <!-- ======================================================================= -->
1130 <div class="doc_subsection">
1131   <a name="ds_set">Set-Like Containers (std::set, SmallSet, SetVector, etc)</a>
1132 </div>
1133
1134 <div class="doc_text">
1135
1136 <p>Set-like containers are useful when you need to canonicalize multiple values
1137 into a single representation.  There are several different choices for how to do
1138 this, providing various trade-offs.</p>
1139
1140 </div>
1141
1142
1143 <!-- _______________________________________________________________________ -->
1144 <div class="doc_subsubsection">
1145   <a name="dss_sortedvectorset">A sorted 'vector'</a>
1146 </div>
1147
1148 <div class="doc_text">
1149
1150 <p>If you intend to insert a lot of elements, then do a lot of queries, a
1151 great approach is to use a vector (or other sequential container) with
1152 std::sort+std::unique to remove duplicates.  This approach works really well if
1153 your usage pattern has these two distinct phases (insert then query), and can be
1154 coupled with a good choice of <a href="#ds_sequential">sequential container</a>.
1155 </p>
1156
1157 <p>
1158 This combination provides the several nice properties: the result data is
1159 contiguous in memory (good for cache locality), has few allocations, is easy to
1160 address (iterators in the final vector are just indices or pointers), and can be
1161 efficiently queried with a standard binary or radix search.</p>
1162
1163 </div>
1164
1165 <!-- _______________________________________________________________________ -->
1166 <div class="doc_subsubsection">
1167   <a name="dss_smallset">"llvm/ADT/SmallSet.h"</a>
1168 </div>
1169
1170 <div class="doc_text">
1171
1172 <p>If you have a set-like data structure that is usually small and whose elements
1173 are reasonably small, a <tt>SmallSet&lt;Type, N&gt;</tt> is a good choice.  This set
1174 has space for N elements in place (thus, if the set is dynamically smaller than
1175 N, no malloc traffic is required) and accesses them with a simple linear search.
1176 When the set grows beyond 'N' elements, it allocates a more expensive representation that
1177 guarantees efficient access (for most types, it falls back to std::set, but for
1178 pointers it uses something far better, <a
1179 href="#dss_smallptrset">SmallPtrSet</a>).</p>
1180
1181 <p>The magic of this class is that it handles small sets extremely efficiently,
1182 but gracefully handles extremely large sets without loss of efficiency.  The
1183 drawback is that the interface is quite small: it supports insertion, queries
1184 and erasing, but does not support iteration.</p>
1185
1186 </div>
1187
1188 <!-- _______________________________________________________________________ -->
1189 <div class="doc_subsubsection">
1190   <a name="dss_smallptrset">"llvm/ADT/SmallPtrSet.h"</a>
1191 </div>
1192
1193 <div class="doc_text">
1194
1195 <p>SmallPtrSet has all the advantages of SmallSet (and a SmallSet of pointers is 
1196 transparently implemented with a SmallPtrSet), but also supports iterators.  If
1197 more than 'N' insertions are performed, a single quadratically
1198 probed hash table is allocated and grows as needed, providing extremely
1199 efficient access (constant time insertion/deleting/queries with low constant
1200 factors) and is very stingy with malloc traffic.</p>
1201
1202 <p>Note that, unlike std::set, the iterators of SmallPtrSet are invalidated
1203 whenever an insertion occurs.  Also, the values visited by the iterators are not
1204 visited in sorted order.</p>
1205
1206 </div>
1207
1208 <!-- _______________________________________________________________________ -->
1209 <div class="doc_subsubsection">
1210   <a name="dss_denseset">"llvm/ADT/DenseSet.h"</a>
1211 </div>
1212
1213 <div class="doc_text">
1214
1215 <p>
1216 DenseSet is a simple quadratically probed hash table.  It excels at supporting
1217 small values: it uses a single allocation to hold all of the pairs that
1218 are currently inserted in the set.  DenseSet is a great way to unique small
1219 values that are not simple pointers (use <a 
1220 href="#dss_smallptrset">SmallPtrSet</a> for pointers).  Note that DenseSet has
1221 the same requirements for the value type that <a 
1222 href="#dss_densemap">DenseMap</a> has.
1223 </p>
1224
1225 </div>
1226
1227 <!-- _______________________________________________________________________ -->
1228 <div class="doc_subsubsection">
1229   <a name="dss_FoldingSet">"llvm/ADT/FoldingSet.h"</a>
1230 </div>
1231
1232 <div class="doc_text">
1233
1234 <p>
1235 FoldingSet is an aggregate class that is really good at uniquing
1236 expensive-to-create or polymorphic objects.  It is a combination of a chained
1237 hash table with intrusive links (uniqued objects are required to inherit from
1238 FoldingSetNode) that uses <a href="#dss_smallvector">SmallVector</a> as part of
1239 its ID process.</p>
1240
1241 <p>Consider a case where you want to implement a "getOrCreateFoo" method for
1242 a complex object (for example, a node in the code generator).  The client has a
1243 description of *what* it wants to generate (it knows the opcode and all the
1244 operands), but we don't want to 'new' a node, then try inserting it into a set
1245 only to find out it already exists, at which point we would have to delete it
1246 and return the node that already exists.
1247 </p>
1248
1249 <p>To support this style of client, FoldingSet perform a query with a
1250 FoldingSetNodeID (which wraps SmallVector) that can be used to describe the
1251 element that we want to query for.  The query either returns the element
1252 matching the ID or it returns an opaque ID that indicates where insertion should
1253 take place.  Construction of the ID usually does not require heap traffic.</p>
1254
1255 <p>Because FoldingSet uses intrusive links, it can support polymorphic objects
1256 in the set (for example, you can have SDNode instances mixed with LoadSDNodes).
1257 Because the elements are individually allocated, pointers to the elements are
1258 stable: inserting or removing elements does not invalidate any pointers to other
1259 elements.
1260 </p>
1261
1262 </div>
1263
1264 <!-- _______________________________________________________________________ -->
1265 <div class="doc_subsubsection">
1266   <a name="dss_set">&lt;set&gt;</a>
1267 </div>
1268
1269 <div class="doc_text">
1270
1271 <p><tt>std::set</tt> is a reasonable all-around set class, which is decent at
1272 many things but great at nothing.  std::set allocates memory for each element
1273 inserted (thus it is very malloc intensive) and typically stores three pointers
1274 per element in the set (thus adding a large amount of per-element space
1275 overhead).  It offers guaranteed log(n) performance, which is not particularly
1276 fast from a complexity standpoint (particularly if the elements of the set are
1277 expensive to compare, like strings), and has extremely high constant factors for
1278 lookup, insertion and removal.</p>
1279
1280 <p>The advantages of std::set are that its iterators are stable (deleting or
1281 inserting an element from the set does not affect iterators or pointers to other
1282 elements) and that iteration over the set is guaranteed to be in sorted order.
1283 If the elements in the set are large, then the relative overhead of the pointers
1284 and malloc traffic is not a big deal, but if the elements of the set are small,
1285 std::set is almost never a good choice.</p>
1286
1287 </div>
1288
1289 <!-- _______________________________________________________________________ -->
1290 <div class="doc_subsubsection">
1291   <a name="dss_setvector">"llvm/ADT/SetVector.h"</a>
1292 </div>
1293
1294 <div class="doc_text">
1295 <p>LLVM's SetVector&lt;Type&gt; is an adapter class that combines your choice of
1296 a set-like container along with a <a href="#ds_sequential">Sequential 
1297 Container</a>.  The important property
1298 that this provides is efficient insertion with uniquing (duplicate elements are
1299 ignored) with iteration support.  It implements this by inserting elements into
1300 both a set-like container and the sequential container, using the set-like
1301 container for uniquing and the sequential container for iteration.
1302 </p>
1303
1304 <p>The difference between SetVector and other sets is that the order of
1305 iteration is guaranteed to match the order of insertion into the SetVector.
1306 This property is really important for things like sets of pointers.  Because
1307 pointer values are non-deterministic (e.g. vary across runs of the program on
1308 different machines), iterating over the pointers in the set will
1309 not be in a well-defined order.</p>
1310
1311 <p>
1312 The drawback of SetVector is that it requires twice as much space as a normal
1313 set and has the sum of constant factors from the set-like container and the 
1314 sequential container that it uses.  Use it *only* if you need to iterate over 
1315 the elements in a deterministic order.  SetVector is also expensive to delete
1316 elements out of (linear time), unless you use it's "pop_back" method, which is
1317 faster.
1318 </p>
1319
1320 <p>SetVector is an adapter class that defaults to using std::vector and std::set
1321 for the underlying containers, so it is quite expensive.  However,
1322 <tt>"llvm/ADT/SetVector.h"</tt> also provides a SmallSetVector class, which
1323 defaults to using a SmallVector and SmallSet of a specified size.  If you use
1324 this, and if your sets are dynamically smaller than N, you will save a lot of 
1325 heap traffic.</p>
1326
1327 </div>
1328
1329 <!-- _______________________________________________________________________ -->
1330 <div class="doc_subsubsection">
1331   <a name="dss_uniquevector">"llvm/ADT/UniqueVector.h"</a>
1332 </div>
1333
1334 <div class="doc_text">
1335
1336 <p>
1337 UniqueVector is similar to <a href="#dss_setvector">SetVector</a>, but it
1338 retains a unique ID for each element inserted into the set.  It internally
1339 contains a map and a vector, and it assigns a unique ID for each value inserted
1340 into the set.</p>
1341
1342 <p>UniqueVector is very expensive: its cost is the sum of the cost of
1343 maintaining both the map and vector, it has high complexity, high constant
1344 factors, and produces a lot of malloc traffic.  It should be avoided.</p>
1345
1346 </div>
1347
1348
1349 <!-- _______________________________________________________________________ -->
1350 <div class="doc_subsubsection">
1351   <a name="dss_otherset">Other Set-Like Container Options</a>
1352 </div>
1353
1354 <div class="doc_text">
1355
1356 <p>
1357 The STL provides several other options, such as std::multiset and the various 
1358 "hash_set" like containers (whether from C++ TR1 or from the SGI library). We
1359 never use hash_set and unordered_set because they are generally very expensive 
1360 (each insertion requires a malloc) and very non-portable.
1361 </p>
1362
1363 <p>std::multiset is useful if you're not interested in elimination of
1364 duplicates, but has all the drawbacks of std::set.  A sorted vector (where you 
1365 don't delete duplicate entries) or some other approach is almost always
1366 better.</p>
1367
1368 </div>
1369
1370 <!-- ======================================================================= -->
1371 <div class="doc_subsection">
1372   <a name="ds_map">Map-Like Containers (std::map, DenseMap, etc)</a>
1373 </div>
1374
1375 <div class="doc_text">
1376 Map-like containers are useful when you want to associate data to a key.  As
1377 usual, there are a lot of different ways to do this. :)
1378 </div>
1379
1380 <!-- _______________________________________________________________________ -->
1381 <div class="doc_subsubsection">
1382   <a name="dss_sortedvectormap">A sorted 'vector'</a>
1383 </div>
1384
1385 <div class="doc_text">
1386
1387 <p>
1388 If your usage pattern follows a strict insert-then-query approach, you can
1389 trivially use the same approach as <a href="#dss_sortedvectorset">sorted vectors
1390 for set-like containers</a>.  The only difference is that your query function
1391 (which uses std::lower_bound to get efficient log(n) lookup) should only compare
1392 the key, not both the key and value.  This yields the same advantages as sorted
1393 vectors for sets.
1394 </p>
1395 </div>
1396
1397 <!-- _______________________________________________________________________ -->
1398 <div class="doc_subsubsection">
1399   <a name="dss_stringmap">"llvm/ADT/StringMap.h"</a>
1400 </div>
1401
1402 <div class="doc_text">
1403
1404 <p>
1405 Strings are commonly used as keys in maps, and they are difficult to support
1406 efficiently: they are variable length, inefficient to hash and compare when
1407 long, expensive to copy, etc.  StringMap is a specialized container designed to
1408 cope with these issues.  It supports mapping an arbitrary range of bytes to an
1409 arbitrary other object.</p>
1410
1411 <p>The StringMap implementation uses a quadratically-probed hash table, where
1412 the buckets store a pointer to the heap allocated entries (and some other
1413 stuff).  The entries in the map must be heap allocated because the strings are
1414 variable length.  The string data (key) and the element object (value) are
1415 stored in the same allocation with the string data immediately after the element
1416 object.  This container guarantees the "<tt>(char*)(&amp;Value+1)</tt>" points
1417 to the key string for a value.</p>
1418
1419 <p>The StringMap is very fast for several reasons: quadratic probing is very
1420 cache efficient for lookups, the hash value of strings in buckets is not
1421 recomputed when lookup up an element, StringMap rarely has to touch the
1422 memory for unrelated objects when looking up a value (even when hash collisions
1423 happen), hash table growth does not recompute the hash values for strings
1424 already in the table, and each pair in the map is store in a single allocation
1425 (the string data is stored in the same allocation as the Value of a pair).</p>
1426
1427 <p>StringMap also provides query methods that take byte ranges, so it only ever
1428 copies a string if a value is inserted into the table.</p>
1429 </div>
1430
1431 <!-- _______________________________________________________________________ -->
1432 <div class="doc_subsubsection">
1433   <a name="dss_indexedmap">"llvm/ADT/IndexedMap.h"</a>
1434 </div>
1435
1436 <div class="doc_text">
1437 <p>
1438 IndexedMap is a specialized container for mapping small dense integers (or
1439 values that can be mapped to small dense integers) to some other type.  It is
1440 internally implemented as a vector with a mapping function that maps the keys to
1441 the dense integer range.
1442 </p>
1443
1444 <p>
1445 This is useful for cases like virtual registers in the LLVM code generator: they
1446 have a dense mapping that is offset by a compile-time constant (the first
1447 virtual register ID).</p>
1448
1449 </div>
1450
1451 <!-- _______________________________________________________________________ -->
1452 <div class="doc_subsubsection">
1453   <a name="dss_densemap">"llvm/ADT/DenseMap.h"</a>
1454 </div>
1455
1456 <div class="doc_text">
1457
1458 <p>
1459 DenseMap is a simple quadratically probed hash table.  It excels at supporting
1460 small keys and values: it uses a single allocation to hold all of the pairs that
1461 are currently inserted in the map.  DenseMap is a great way to map pointers to
1462 pointers, or map other small types to each other.
1463 </p>
1464
1465 <p>
1466 There are several aspects of DenseMap that you should be aware of, however.  The
1467 iterators in a densemap are invalidated whenever an insertion occurs, unlike
1468 map.  Also, because DenseMap allocates space for a large number of key/value
1469 pairs (it starts with 64 by default), it will waste a lot of space if your keys
1470 or values are large.  Finally, you must implement a partial specialization of
1471 DenseMapInfo for the key that you want, if it isn't already supported.  This
1472 is required to tell DenseMap about two special marker values (which can never be
1473 inserted into the map) that it needs internally.</p>
1474
1475 </div>
1476
1477 <!-- _______________________________________________________________________ -->
1478 <div class="doc_subsubsection">
1479   <a name="dss_map">&lt;map&gt;</a>
1480 </div>
1481
1482 <div class="doc_text">
1483
1484 <p>
1485 std::map has similar characteristics to <a href="#dss_set">std::set</a>: it uses
1486 a single allocation per pair inserted into the map, it offers log(n) lookup with
1487 an extremely large constant factor, imposes a space penalty of 3 pointers per
1488 pair in the map, etc.</p>
1489
1490 <p>std::map is most useful when your keys or values are very large, if you need
1491 to iterate over the collection in sorted order, or if you need stable iterators
1492 into the map (i.e. they don't get invalidated if an insertion or deletion of
1493 another element takes place).</p>
1494
1495 </div>
1496
1497 <!-- _______________________________________________________________________ -->
1498 <div class="doc_subsubsection">
1499   <a name="dss_othermap">Other Map-Like Container Options</a>
1500 </div>
1501
1502 <div class="doc_text">
1503
1504 <p>
1505 The STL provides several other options, such as std::multimap and the various 
1506 "hash_map" like containers (whether from C++ TR1 or from the SGI library). We
1507 never use hash_set and unordered_set because they are generally very expensive 
1508 (each insertion requires a malloc) and very non-portable.</p>
1509
1510 <p>std::multimap is useful if you want to map a key to multiple values, but has
1511 all the drawbacks of std::map.  A sorted vector or some other approach is almost
1512 always better.</p>
1513
1514 </div>
1515
1516 <!-- ======================================================================= -->
1517 <div class="doc_subsection">
1518   <a name="ds_string">String-like containers</a>
1519 </div>
1520
1521 <div class="doc_text">
1522
1523 <p>
1524 TODO: const char* vs stringref vs smallstring vs std::string.  Describe twine,
1525 xref to #string_apis.
1526 </p>
1527
1528 </div>
1529
1530 <!-- ======================================================================= -->
1531 <div class="doc_subsection">
1532   <a name="ds_bit">Bit storage containers (BitVector, SparseBitVector)</a>
1533 </div>
1534
1535 <div class="doc_text">
1536 <p>Unlike the other containers, there are only two bit storage containers, and 
1537 choosing when to use each is relatively straightforward.</p>
1538
1539 <p>One additional option is 
1540 <tt>std::vector&lt;bool&gt;</tt>: we discourage its use for two reasons 1) the
1541 implementation in many common compilers (e.g. commonly available versions of 
1542 GCC) is extremely inefficient and 2) the C++ standards committee is likely to
1543 deprecate this container and/or change it significantly somehow.  In any case,
1544 please don't use it.</p>
1545 </div>
1546
1547 <!-- _______________________________________________________________________ -->
1548 <div class="doc_subsubsection">
1549   <a name="dss_bitvector">BitVector</a>
1550 </div>
1551
1552 <div class="doc_text">
1553 <p> The BitVector container provides a fixed size set of bits for manipulation.
1554 It supports individual bit setting/testing, as well as set operations.  The set
1555 operations take time O(size of bitvector), but operations are performed one word
1556 at a time, instead of one bit at a time.  This makes the BitVector very fast for
1557 set operations compared to other containers.  Use the BitVector when you expect
1558 the number of set bits to be high (IE a dense set).
1559 </p>
1560 </div>
1561
1562 <!-- _______________________________________________________________________ -->
1563 <div class="doc_subsubsection">
1564   <a name="dss_sparsebitvector">SparseBitVector</a>
1565 </div>
1566
1567 <div class="doc_text">
1568 <p> The SparseBitVector container is much like BitVector, with one major
1569 difference: Only the bits that are set, are stored.  This makes the
1570 SparseBitVector much more space efficient than BitVector when the set is sparse,
1571 as well as making set operations O(number of set bits) instead of O(size of
1572 universe).  The downside to the SparseBitVector is that setting and testing of random bits is O(N), and on large SparseBitVectors, this can be slower than BitVector. In our implementation, setting or testing bits in sorted order
1573 (either forwards or reverse) is O(1) worst case.  Testing and setting bits within 128 bits (depends on size) of the current bit is also O(1).  As a general statement, testing/setting bits in a SparseBitVector is O(distance away from last set bit).
1574 </p>
1575 </div>
1576
1577 <!-- *********************************************************************** -->
1578 <div class="doc_section">
1579   <a name="common">Helpful Hints for Common Operations</a>
1580 </div>
1581 <!-- *********************************************************************** -->
1582
1583 <div class="doc_text">
1584
1585 <p>This section describes how to perform some very simple transformations of
1586 LLVM code.  This is meant to give examples of common idioms used, showing the
1587 practical side of LLVM transformations.  <p> Because this is a "how-to" section,
1588 you should also read about the main classes that you will be working with.  The
1589 <a href="#coreclasses">Core LLVM Class Hierarchy Reference</a> contains details
1590 and descriptions of the main classes that you should know about.</p>
1591
1592 </div>
1593
1594 <!-- NOTE: this section should be heavy on example code -->
1595 <!-- ======================================================================= -->
1596 <div class="doc_subsection">
1597   <a name="inspection">Basic Inspection and Traversal Routines</a>
1598 </div>
1599
1600 <div class="doc_text">
1601
1602 <p>The LLVM compiler infrastructure have many different data structures that may
1603 be traversed.  Following the example of the C++ standard template library, the
1604 techniques used to traverse these various data structures are all basically the
1605 same.  For a enumerable sequence of values, the <tt>XXXbegin()</tt> function (or
1606 method) returns an iterator to the start of the sequence, the <tt>XXXend()</tt>
1607 function returns an iterator pointing to one past the last valid element of the
1608 sequence, and there is some <tt>XXXiterator</tt> data type that is common
1609 between the two operations.</p>
1610
1611 <p>Because the pattern for iteration is common across many different aspects of
1612 the program representation, the standard template library algorithms may be used
1613 on them, and it is easier to remember how to iterate. First we show a few common
1614 examples of the data structures that need to be traversed.  Other data
1615 structures are traversed in very similar ways.</p>
1616
1617 </div>
1618
1619 <!-- _______________________________________________________________________ -->
1620 <div class="doc_subsubsection">
1621   <a name="iterate_function">Iterating over the </a><a
1622   href="#BasicBlock"><tt>BasicBlock</tt></a>s in a <a
1623   href="#Function"><tt>Function</tt></a>
1624 </div>
1625
1626 <div class="doc_text">
1627
1628 <p>It's quite common to have a <tt>Function</tt> instance that you'd like to
1629 transform in some way; in particular, you'd like to manipulate its
1630 <tt>BasicBlock</tt>s.  To facilitate this, you'll need to iterate over all of
1631 the <tt>BasicBlock</tt>s that constitute the <tt>Function</tt>. The following is
1632 an example that prints the name of a <tt>BasicBlock</tt> and the number of
1633 <tt>Instruction</tt>s it contains:</p>
1634
1635 <div class="doc_code">
1636 <pre>
1637 // <i>func is a pointer to a Function instance</i>
1638 for (Function::iterator i = func-&gt;begin(), e = func-&gt;end(); i != e; ++i)
1639   // <i>Print out the name of the basic block if it has one, and then the</i>
1640   // <i>number of instructions that it contains</i>
1641   llvm::cerr &lt;&lt; "Basic block (name=" &lt;&lt; i-&gt;getName() &lt;&lt; ") has "
1642              &lt;&lt; i-&gt;size() &lt;&lt; " instructions.\n";
1643 </pre>
1644 </div>
1645
1646 <p>Note that i can be used as if it were a pointer for the purposes of
1647 invoking member functions of the <tt>Instruction</tt> class.  This is
1648 because the indirection operator is overloaded for the iterator
1649 classes.  In the above code, the expression <tt>i-&gt;size()</tt> is
1650 exactly equivalent to <tt>(*i).size()</tt> just like you'd expect.</p>
1651
1652 </div>
1653
1654 <!-- _______________________________________________________________________ -->
1655 <div class="doc_subsubsection">
1656   <a name="iterate_basicblock">Iterating over the </a><a
1657   href="#Instruction"><tt>Instruction</tt></a>s in a <a
1658   href="#BasicBlock"><tt>BasicBlock</tt></a>
1659 </div>
1660
1661 <div class="doc_text">
1662
1663 <p>Just like when dealing with <tt>BasicBlock</tt>s in <tt>Function</tt>s, it's
1664 easy to iterate over the individual instructions that make up
1665 <tt>BasicBlock</tt>s. Here's a code snippet that prints out each instruction in
1666 a <tt>BasicBlock</tt>:</p>
1667
1668 <div class="doc_code">
1669 <pre>
1670 // <i>blk is a pointer to a BasicBlock instance</i>
1671 for (BasicBlock::iterator i = blk-&gt;begin(), e = blk-&gt;end(); i != e; ++i)
1672    // <i>The next statement works since operator&lt;&lt;(ostream&amp;,...)</i>
1673    // <i>is overloaded for Instruction&amp;</i>
1674    llvm::cerr &lt;&lt; *i &lt;&lt; "\n";
1675 </pre>
1676 </div>
1677
1678 <p>However, this isn't really the best way to print out the contents of a
1679 <tt>BasicBlock</tt>!  Since the ostream operators are overloaded for virtually
1680 anything you'll care about, you could have just invoked the print routine on the
1681 basic block itself: <tt>llvm::cerr &lt;&lt; *blk &lt;&lt; "\n";</tt>.</p>
1682
1683 </div>
1684
1685 <!-- _______________________________________________________________________ -->
1686 <div class="doc_subsubsection">
1687   <a name="iterate_institer">Iterating over the </a><a
1688   href="#Instruction"><tt>Instruction</tt></a>s in a <a
1689   href="#Function"><tt>Function</tt></a>
1690 </div>
1691
1692 <div class="doc_text">
1693
1694 <p>If you're finding that you commonly iterate over a <tt>Function</tt>'s
1695 <tt>BasicBlock</tt>s and then that <tt>BasicBlock</tt>'s <tt>Instruction</tt>s,
1696 <tt>InstIterator</tt> should be used instead. You'll need to include <a
1697 href="/doxygen/InstIterator_8h-source.html"><tt>llvm/Support/InstIterator.h</tt></a>,
1698 and then instantiate <tt>InstIterator</tt>s explicitly in your code.  Here's a
1699 small example that shows how to dump all instructions in a function to the standard error stream:<p>
1700
1701 <div class="doc_code">
1702 <pre>
1703 #include "<a href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h</a>"
1704
1705 // <i>F is a pointer to a Function instance</i>
1706 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
1707   llvm::cerr &lt;&lt; *I &lt;&lt; "\n";
1708 </pre>
1709 </div>
1710
1711 <p>Easy, isn't it?  You can also use <tt>InstIterator</tt>s to fill a
1712 work list with its initial contents.  For example, if you wanted to
1713 initialize a work list to contain all instructions in a <tt>Function</tt>
1714 F, all you would need to do is something like:</p>
1715
1716 <div class="doc_code">
1717 <pre>
1718 std::set&lt;Instruction*&gt; worklist;
1719 // or better yet, SmallPtrSet&lt;Instruction*, 64&gt; worklist;
1720
1721 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
1722    worklist.insert(&amp;*I);
1723 </pre>
1724 </div>
1725
1726 <p>The STL set <tt>worklist</tt> would now contain all instructions in the
1727 <tt>Function</tt> pointed to by F.</p>
1728
1729 </div>
1730
1731 <!-- _______________________________________________________________________ -->
1732 <div class="doc_subsubsection">
1733   <a name="iterate_convert">Turning an iterator into a class pointer (and
1734   vice-versa)</a>
1735 </div>
1736
1737 <div class="doc_text">
1738
1739 <p>Sometimes, it'll be useful to grab a reference (or pointer) to a class
1740 instance when all you've got at hand is an iterator.  Well, extracting
1741 a reference or a pointer from an iterator is very straight-forward.
1742 Assuming that <tt>i</tt> is a <tt>BasicBlock::iterator</tt> and <tt>j</tt>
1743 is a <tt>BasicBlock::const_iterator</tt>:</p>
1744
1745 <div class="doc_code">
1746 <pre>
1747 Instruction&amp; inst = *i;   // <i>Grab reference to instruction reference</i>
1748 Instruction* pinst = &amp;*i; // <i>Grab pointer to instruction reference</i>
1749 const Instruction&amp; inst = *j;
1750 </pre>
1751 </div>
1752
1753 <p>However, the iterators you'll be working with in the LLVM framework are
1754 special: they will automatically convert to a ptr-to-instance type whenever they
1755 need to.  Instead of dereferencing the iterator and then taking the address of
1756 the result, you can simply assign the iterator to the proper pointer type and
1757 you get the dereference and address-of operation as a result of the assignment
1758 (behind the scenes, this is a result of overloading casting mechanisms).  Thus
1759 the last line of the last example,</p>
1760
1761 <div class="doc_code">
1762 <pre>
1763 Instruction *pinst = &amp;*i;
1764 </pre>
1765 </div>
1766
1767 <p>is semantically equivalent to</p>
1768
1769 <div class="doc_code">
1770 <pre>
1771 Instruction *pinst = i;
1772 </pre>
1773 </div>
1774
1775 <p>It's also possible to turn a class pointer into the corresponding iterator,
1776 and this is a constant time operation (very efficient).  The following code
1777 snippet illustrates use of the conversion constructors provided by LLVM
1778 iterators.  By using these, you can explicitly grab the iterator of something
1779 without actually obtaining it via iteration over some structure:</p>
1780
1781 <div class="doc_code">
1782 <pre>
1783 void printNextInstruction(Instruction* inst) {
1784   BasicBlock::iterator it(inst);
1785   ++it; // <i>After this line, it refers to the instruction after *inst</i>
1786   if (it != inst-&gt;getParent()-&gt;end()) llvm::cerr &lt;&lt; *it &lt;&lt; "\n";
1787 }
1788 </pre>
1789 </div>
1790
1791 </div>
1792
1793 <!--_______________________________________________________________________-->
1794 <div class="doc_subsubsection">
1795   <a name="iterate_complex">Finding call sites: a slightly more complex
1796   example</a>
1797 </div>
1798
1799 <div class="doc_text">
1800
1801 <p>Say that you're writing a FunctionPass and would like to count all the
1802 locations in the entire module (that is, across every <tt>Function</tt>) where a
1803 certain function (i.e., some <tt>Function</tt>*) is already in scope.  As you'll
1804 learn later, you may want to use an <tt>InstVisitor</tt> to accomplish this in a
1805 much more straight-forward manner, but this example will allow us to explore how
1806 you'd do it if you didn't have <tt>InstVisitor</tt> around. In pseudo-code, this
1807 is what we want to do:</p>
1808
1809 <div class="doc_code">
1810 <pre>
1811 initialize callCounter to zero
1812 for each Function f in the Module
1813   for each BasicBlock b in f
1814     for each Instruction i in b
1815       if (i is a CallInst and calls the given function)
1816         increment callCounter
1817 </pre>
1818 </div>
1819
1820 <p>And the actual code is (remember, because we're writing a
1821 <tt>FunctionPass</tt>, our <tt>FunctionPass</tt>-derived class simply has to
1822 override the <tt>runOnFunction</tt> method):</p>
1823
1824 <div class="doc_code">
1825 <pre>
1826 Function* targetFunc = ...;
1827
1828 class OurFunctionPass : public FunctionPass {
1829   public:
1830     OurFunctionPass(): callCounter(0) { }
1831
1832     virtual runOnFunction(Function&amp; F) {
1833       for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
1834         for (BasicBlock::iterator i = b-&gt;begin(), ie = b-&gt;end(); i != ie; ++i) {
1835           if (<a href="#CallInst">CallInst</a>* callInst = <a href="#isa">dyn_cast</a>&lt;<a
1836  href="#CallInst">CallInst</a>&gt;(&amp;*i)) {
1837             // <i>We know we've encountered a call instruction, so we</i>
1838             // <i>need to determine if it's a call to the</i>
1839             // <i>function pointed to by m_func or not.</i>
1840             if (callInst-&gt;getCalledFunction() == targetFunc)
1841               ++callCounter;
1842           }
1843         }
1844       }
1845     }
1846
1847   private:
1848     unsigned callCounter;
1849 };
1850 </pre>
1851 </div>
1852
1853 </div>
1854
1855 <!--_______________________________________________________________________-->
1856 <div class="doc_subsubsection">
1857   <a name="calls_and_invokes">Treating calls and invokes the same way</a>
1858 </div>
1859
1860 <div class="doc_text">
1861
1862 <p>You may have noticed that the previous example was a bit oversimplified in
1863 that it did not deal with call sites generated by 'invoke' instructions. In
1864 this, and in other situations, you may find that you want to treat
1865 <tt>CallInst</tt>s and <tt>InvokeInst</tt>s the same way, even though their
1866 most-specific common base class is <tt>Instruction</tt>, which includes lots of
1867 less closely-related things. For these cases, LLVM provides a handy wrapper
1868 class called <a
1869 href="http://llvm.org/doxygen/classllvm_1_1CallSite.html"><tt>CallSite</tt></a>.
1870 It is essentially a wrapper around an <tt>Instruction</tt> pointer, with some
1871 methods that provide functionality common to <tt>CallInst</tt>s and
1872 <tt>InvokeInst</tt>s.</p>
1873
1874 <p>This class has "value semantics": it should be passed by value, not by
1875 reference and it should not be dynamically allocated or deallocated using
1876 <tt>operator new</tt> or <tt>operator delete</tt>. It is efficiently copyable,
1877 assignable and constructable, with costs equivalents to that of a bare pointer.
1878 If you look at its definition, it has only a single pointer member.</p>
1879
1880 </div>
1881
1882 <!--_______________________________________________________________________-->
1883 <div class="doc_subsubsection">
1884   <a name="iterate_chains">Iterating over def-use &amp; use-def chains</a>
1885 </div>
1886
1887 <div class="doc_text">
1888
1889 <p>Frequently, we might have an instance of the <a
1890 href="/doxygen/classllvm_1_1Value.html">Value Class</a> and we want to
1891 determine which <tt>User</tt>s use the <tt>Value</tt>.  The list of all
1892 <tt>User</tt>s of a particular <tt>Value</tt> is called a <i>def-use</i> chain.
1893 For example, let's say we have a <tt>Function*</tt> named <tt>F</tt> to a
1894 particular function <tt>foo</tt>. Finding all of the instructions that
1895 <i>use</i> <tt>foo</tt> is as simple as iterating over the <i>def-use</i> chain
1896 of <tt>F</tt>:</p>
1897
1898 <div class="doc_code">
1899 <pre>
1900 Function *F = ...;
1901
1902 for (Value::use_iterator i = F-&gt;use_begin(), e = F-&gt;use_end(); i != e; ++i)
1903   if (Instruction *Inst = dyn_cast&lt;Instruction&gt;(*i)) {
1904     llvm::cerr &lt;&lt; "F is used in instruction:\n";
1905     llvm::cerr &lt;&lt; *Inst &lt;&lt; "\n";
1906   }
1907 </pre>
1908 </div>
1909
1910 <p>Alternately, it's common to have an instance of the <a
1911 href="/doxygen/classllvm_1_1User.html">User Class</a> and need to know what
1912 <tt>Value</tt>s are used by it.  The list of all <tt>Value</tt>s used by a
1913 <tt>User</tt> is known as a <i>use-def</i> chain.  Instances of class
1914 <tt>Instruction</tt> are common <tt>User</tt>s, so we might want to iterate over
1915 all of the values that a particular instruction uses (that is, the operands of
1916 the particular <tt>Instruction</tt>):</p>
1917
1918 <div class="doc_code">
1919 <pre>
1920 Instruction *pi = ...;
1921
1922 for (User::op_iterator i = pi-&gt;op_begin(), e = pi-&gt;op_end(); i != e; ++i) {
1923   Value *v = *i;
1924   // <i>...</i>
1925 }
1926 </pre>
1927 </div>
1928
1929 <!--
1930   def-use chains ("finding all users of"): Value::use_begin/use_end
1931   use-def chains ("finding all values used"): User::op_begin/op_end [op=operand]
1932 -->
1933
1934 </div>
1935
1936 <!--_______________________________________________________________________-->
1937 <div class="doc_subsubsection">
1938   <a name="iterate_preds">Iterating over predecessors &amp;
1939 successors of blocks</a>
1940 </div>
1941
1942 <div class="doc_text">
1943
1944 <p>Iterating over the predecessors and successors of a block is quite easy
1945 with the routines defined in <tt>"llvm/Support/CFG.h"</tt>.  Just use code like
1946 this to iterate over all predecessors of BB:</p>
1947
1948 <div class="doc_code">
1949 <pre>
1950 #include "llvm/Support/CFG.h"
1951 BasicBlock *BB = ...;
1952
1953 for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
1954   BasicBlock *Pred = *PI;
1955   // <i>...</i>
1956 }
1957 </pre>
1958 </div>
1959
1960 <p>Similarly, to iterate over successors use
1961 succ_iterator/succ_begin/succ_end.</p>
1962
1963 </div>
1964
1965
1966 <!-- ======================================================================= -->
1967 <div class="doc_subsection">
1968   <a name="simplechanges">Making simple changes</a>
1969 </div>
1970
1971 <div class="doc_text">
1972
1973 <p>There are some primitive transformation operations present in the LLVM
1974 infrastructure that are worth knowing about.  When performing
1975 transformations, it's fairly common to manipulate the contents of basic
1976 blocks. This section describes some of the common methods for doing so
1977 and gives example code.</p>
1978
1979 </div>
1980
1981 <!--_______________________________________________________________________-->
1982 <div class="doc_subsubsection">
1983   <a name="schanges_creating">Creating and inserting new
1984   <tt>Instruction</tt>s</a>
1985 </div>
1986
1987 <div class="doc_text">
1988
1989 <p><i>Instantiating Instructions</i></p>
1990
1991 <p>Creation of <tt>Instruction</tt>s is straight-forward: simply call the
1992 constructor for the kind of instruction to instantiate and provide the necessary
1993 parameters. For example, an <tt>AllocaInst</tt> only <i>requires</i> a
1994 (const-ptr-to) <tt>Type</tt>. Thus:</p> 
1995
1996 <div class="doc_code">
1997 <pre>
1998 AllocaInst* ai = new AllocaInst(Type::Int32Ty);
1999 </pre>
2000 </div>
2001
2002 <p>will create an <tt>AllocaInst</tt> instance that represents the allocation of
2003 one integer in the current stack frame, at run time. Each <tt>Instruction</tt>
2004 subclass is likely to have varying default parameters which change the semantics
2005 of the instruction, so refer to the <a
2006 href="/doxygen/classllvm_1_1Instruction.html">doxygen documentation for the subclass of
2007 Instruction</a> that you're interested in instantiating.</p>
2008
2009 <p><i>Naming values</i></p>
2010
2011 <p>It is very useful to name the values of instructions when you're able to, as
2012 this facilitates the debugging of your transformations.  If you end up looking
2013 at generated LLVM machine code, you definitely want to have logical names
2014 associated with the results of instructions!  By supplying a value for the
2015 <tt>Name</tt> (default) parameter of the <tt>Instruction</tt> constructor, you
2016 associate a logical name with the result of the instruction's execution at
2017 run time.  For example, say that I'm writing a transformation that dynamically
2018 allocates space for an integer on the stack, and that integer is going to be
2019 used as some kind of index by some other code.  To accomplish this, I place an
2020 <tt>AllocaInst</tt> at the first point in the first <tt>BasicBlock</tt> of some
2021 <tt>Function</tt>, and I'm intending to use it within the same
2022 <tt>Function</tt>. I might do:</p>
2023
2024 <div class="doc_code">
2025 <pre>
2026 AllocaInst* pa = new AllocaInst(Type::Int32Ty, 0, "indexLoc");
2027 </pre>
2028 </div>
2029
2030 <p>where <tt>indexLoc</tt> is now the logical name of the instruction's
2031 execution value, which is a pointer to an integer on the run time stack.</p>
2032
2033 <p><i>Inserting instructions</i></p>
2034
2035 <p>There are essentially two ways to insert an <tt>Instruction</tt>
2036 into an existing sequence of instructions that form a <tt>BasicBlock</tt>:</p>
2037
2038 <ul>
2039   <li>Insertion into an explicit instruction list
2040
2041     <p>Given a <tt>BasicBlock* pb</tt>, an <tt>Instruction* pi</tt> within that
2042     <tt>BasicBlock</tt>, and a newly-created instruction we wish to insert
2043     before <tt>*pi</tt>, we do the following: </p>
2044
2045 <div class="doc_code">
2046 <pre>
2047 BasicBlock *pb = ...;
2048 Instruction *pi = ...;
2049 Instruction *newInst = new Instruction(...);
2050
2051 pb-&gt;getInstList().insert(pi, newInst); // <i>Inserts newInst before pi in pb</i>
2052 </pre>
2053 </div>
2054
2055     <p>Appending to the end of a <tt>BasicBlock</tt> is so common that
2056     the <tt>Instruction</tt> class and <tt>Instruction</tt>-derived
2057     classes provide constructors which take a pointer to a
2058     <tt>BasicBlock</tt> to be appended to. For example code that
2059     looked like: </p>
2060
2061 <div class="doc_code">
2062 <pre>
2063 BasicBlock *pb = ...;
2064 Instruction *newInst = new Instruction(...);
2065
2066 pb-&gt;getInstList().push_back(newInst); // <i>Appends newInst to pb</i>
2067 </pre>
2068 </div>
2069
2070     <p>becomes: </p>
2071
2072 <div class="doc_code">
2073 <pre>
2074 BasicBlock *pb = ...;
2075 Instruction *newInst = new Instruction(..., pb);
2076 </pre>
2077 </div>
2078
2079     <p>which is much cleaner, especially if you are creating
2080     long instruction streams.</p></li>
2081
2082   <li>Insertion into an implicit instruction list
2083
2084     <p><tt>Instruction</tt> instances that are already in <tt>BasicBlock</tt>s
2085     are implicitly associated with an existing instruction list: the instruction
2086     list of the enclosing basic block. Thus, we could have accomplished the same
2087     thing as the above code without being given a <tt>BasicBlock</tt> by doing:
2088     </p>
2089
2090 <div class="doc_code">
2091 <pre>
2092 Instruction *pi = ...;
2093 Instruction *newInst = new Instruction(...);
2094
2095 pi-&gt;getParent()-&gt;getInstList().insert(pi, newInst);
2096 </pre>
2097 </div>
2098
2099     <p>In fact, this sequence of steps occurs so frequently that the
2100     <tt>Instruction</tt> class and <tt>Instruction</tt>-derived classes provide
2101     constructors which take (as a default parameter) a pointer to an
2102     <tt>Instruction</tt> which the newly-created <tt>Instruction</tt> should
2103     precede.  That is, <tt>Instruction</tt> constructors are capable of
2104     inserting the newly-created instance into the <tt>BasicBlock</tt> of a
2105     provided instruction, immediately before that instruction.  Using an
2106     <tt>Instruction</tt> constructor with a <tt>insertBefore</tt> (default)
2107     parameter, the above code becomes:</p>
2108
2109 <div class="doc_code">
2110 <pre>
2111 Instruction* pi = ...;
2112 Instruction* newInst = new Instruction(..., pi);
2113 </pre>
2114 </div>
2115
2116     <p>which is much cleaner, especially if you're creating a lot of
2117     instructions and adding them to <tt>BasicBlock</tt>s.</p></li>
2118 </ul>
2119
2120 </div>
2121
2122 <!--_______________________________________________________________________-->
2123 <div class="doc_subsubsection">
2124   <a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a>
2125 </div>
2126
2127 <div class="doc_text">
2128
2129 <p>Deleting an instruction from an existing sequence of instructions that form a
2130 <a href="#BasicBlock"><tt>BasicBlock</tt></a> is very straight-forward. First,
2131 you must have a pointer to the instruction that you wish to delete.  Second, you
2132 need to obtain the pointer to that instruction's basic block. You use the
2133 pointer to the basic block to get its list of instructions and then use the
2134 erase function to remove your instruction. For example:</p>
2135
2136 <div class="doc_code">
2137 <pre>
2138 <a href="#Instruction">Instruction</a> *I = .. ;
2139 I-&gt;eraseFromParent();
2140 </pre>
2141 </div>
2142
2143 </div>
2144
2145 <!--_______________________________________________________________________-->
2146 <div class="doc_subsubsection">
2147   <a name="schanges_replacing">Replacing an <tt>Instruction</tt> with another
2148   <tt>Value</tt></a>
2149 </div>
2150
2151 <div class="doc_text">
2152
2153 <p><i>Replacing individual instructions</i></p>
2154
2155 <p>Including "<a href="/doxygen/BasicBlockUtils_8h-source.html">llvm/Transforms/Utils/BasicBlockUtils.h</a>"
2156 permits use of two very useful replace functions: <tt>ReplaceInstWithValue</tt>
2157 and <tt>ReplaceInstWithInst</tt>.</p>
2158
2159 <h4><a name="schanges_deleting">Deleting <tt>Instruction</tt>s</a></h4>
2160
2161 <ul>
2162   <li><tt>ReplaceInstWithValue</tt>
2163
2164     <p>This function replaces all uses of a given instruction with a value,
2165     and then removes the original instruction. The following example
2166     illustrates the replacement of the result of a particular
2167     <tt>AllocaInst</tt> that allocates memory for a single integer with a null
2168     pointer to an integer.</p>
2169
2170 <div class="doc_code">
2171 <pre>
2172 AllocaInst* instToReplace = ...;
2173 BasicBlock::iterator ii(instToReplace);
2174
2175 ReplaceInstWithValue(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
2176                      Constant::getNullValue(PointerType::getUnqual(Type::Int32Ty)));
2177 </pre></div></li>
2178
2179   <li><tt>ReplaceInstWithInst</tt> 
2180
2181     <p>This function replaces a particular instruction with another
2182     instruction, inserting the new instruction into the basic block at the
2183     location where the old instruction was, and replacing any uses of the old
2184     instruction with the new instruction. The following example illustrates
2185     the replacement of one <tt>AllocaInst</tt> with another.</p>
2186
2187 <div class="doc_code">
2188 <pre>
2189 AllocaInst* instToReplace = ...;
2190 BasicBlock::iterator ii(instToReplace);
2191
2192 ReplaceInstWithInst(instToReplace-&gt;getParent()-&gt;getInstList(), ii,
2193                     new AllocaInst(Type::Int32Ty, 0, "ptrToReplacedInt"));
2194 </pre></div></li>
2195 </ul>
2196
2197 <p><i>Replacing multiple uses of <tt>User</tt>s and <tt>Value</tt>s</i></p>
2198
2199 <p>You can use <tt>Value::replaceAllUsesWith</tt> and
2200 <tt>User::replaceUsesOfWith</tt> to change more than one use at a time.  See the
2201 doxygen documentation for the <a href="/doxygen/classllvm_1_1Value.html">Value Class</a>
2202 and <a href="/doxygen/classllvm_1_1User.html">User Class</a>, respectively, for more
2203 information.</p>
2204
2205 <!-- Value::replaceAllUsesWith User::replaceUsesOfWith Point out:
2206 include/llvm/Transforms/Utils/ especially BasicBlockUtils.h with:
2207 ReplaceInstWithValue, ReplaceInstWithInst -->
2208
2209 </div>
2210
2211 <!--_______________________________________________________________________-->
2212 <div class="doc_subsubsection">
2213   <a name="schanges_deletingGV">Deleting <tt>GlobalVariable</tt>s</a>
2214 </div>
2215
2216 <div class="doc_text">
2217
2218 <p>Deleting a global variable from a module is just as easy as deleting an 
2219 Instruction. First, you must have a pointer to the global variable that you wish
2220  to delete.  You use this pointer to erase it from its parent, the module.
2221  For example:</p>
2222
2223 <div class="doc_code">
2224 <pre>
2225 <a href="#GlobalVariable">GlobalVariable</a> *GV = .. ;
2226
2227 GV-&gt;eraseFromParent();
2228 </pre>
2229 </div>
2230
2231 </div>
2232
2233 <!-- ======================================================================= -->
2234 <div class="doc_subsection">
2235   <a name="create_types">How to Create Types</a>
2236 </div>
2237
2238 <div class="doc_text">
2239
2240 <p>In generating IR, you may need some complex types.  If you know these types
2241 statically, you can use <tt>TypeBuilder&lt;...&gt;::get()</tt>, defined
2242 in <tt>llvm/Support/TypeBuilder.h</tt>, to retrieve them.  <tt>TypeBuilder</tt>
2243 has two forms depending on whether you're building types for cross-compilation
2244 or native library use.  <tt>TypeBuilder&lt;T, true&gt;</tt> requires
2245 that <tt>T</tt> be independent of the host environment, meaning that it's built
2246 out of types from
2247 the <a href="/doxygen/namespacellvm_1_1types.html"><tt>llvm::types</tt></a>
2248 namespace and pointers, functions, arrays, etc. built of
2249 those.  <tt>TypeBuilder&lt;T, false&gt;</tt> additionally allows native C types
2250 whose size may depend on the host compiler.  For example,</p>
2251
2252 <div class="doc_code">
2253 <pre>
2254 FunctionType *ft = TypeBuilder&lt;types::i&lt;8&gt;(types::i&lt;32&gt;*), true&gt;::get();
2255 </pre>
2256 </div>
2257
2258 <p>is easier to read and write than the equivalent</p>
2259
2260 <div class="doc_code">
2261 <pre>
2262 std::vector&lt;const Type*&gt; params;
2263 params.push_back(PointerType::getUnqual(Type::Int32Ty));
2264 FunctionType *ft = FunctionType::get(Type::Int8Ty, params, false);
2265 </pre>
2266 </div>
2267
2268 <p>See the <a href="/doxygen/TypeBuilder_8h-source.html#l00001">class
2269 comment</a> for more details.</p>
2270
2271 </div>
2272
2273 <!-- *********************************************************************** -->
2274 <div class="doc_section">
2275   <a name="threading">Threads and LLVM</a>
2276 </div>
2277 <!-- *********************************************************************** -->
2278
2279 <div class="doc_text">
2280 <p>
2281 This section describes the interaction of the LLVM APIs with multithreading,
2282 both on the part of client applications, and in the JIT, in the hosted
2283 application.
2284 </p>
2285
2286 <p>
2287 Note that LLVM's support for multithreading is still relatively young.  Up 
2288 through version 2.5, the execution of threaded hosted applications was
2289 supported, but not threaded client access to the APIs.  While this use case is
2290 now supported, clients <em>must</em> adhere to the guidelines specified below to
2291 ensure proper operation in multithreaded mode.
2292 </p>
2293
2294 <p>
2295 Note that, on Unix-like platforms, LLVM requires the presence of GCC's atomic
2296 intrinsics in order to support threaded operation.  If you need a
2297 multhreading-capable LLVM on a platform without a suitably modern system
2298 compiler, consider compiling LLVM and LLVM-GCC in single-threaded mode, and 
2299 using the resultant compiler to build a copy of LLVM with multithreading
2300 support.
2301 </p>
2302 </div>
2303
2304 <!-- ======================================================================= -->
2305 <div class="doc_subsection">
2306   <a name="startmultithreaded">Entering and Exiting Multithreaded Mode</a>
2307 </div>
2308
2309 <div class="doc_text">
2310
2311 <p>
2312 In order to properly protect its internal data structures while avoiding 
2313 excessive locking overhead in the single-threaded case, the LLVM must intialize
2314 certain data structures necessary to provide guards around its internals.  To do
2315 so, the client program must invoke <tt>llvm_start_multithreaded()</tt> before
2316 making any concurrent LLVM API calls.  To subsequently tear down these
2317 structures, use the <tt>llvm_stop_multithreaded()</tt> call.  You can also use
2318 the <tt>llvm_is_multithreaded()</tt> call to check the status of multithreaded
2319 mode.
2320 </p>
2321
2322 <p>
2323 Note that both of these calls must be made <em>in isolation</em>.  That is to
2324 say that no other LLVM API calls may be executing at any time during the 
2325 execution of <tt>llvm_start_multithreaded()</tt> or <tt>llvm_stop_multithreaded
2326 </tt>.  It's is the client's responsibility to enforce this isolation.
2327 </p>
2328
2329 <p>
2330 The return value of <tt>llvm_start_multithreaded()</tt> indicates the success or
2331 failure of the initialization.  Failure typically indicates that your copy of
2332 LLVM was built without multithreading support, typically because GCC atomic
2333 intrinsics were not found in your system compiler.  In this case, the LLVM API
2334 will not be safe for concurrent calls.  However, it <em>will</em> be safe for
2335 hosting threaded applications in the JIT, though care must be taken to ensure
2336 that side exits and the like do not accidentally result in concurrent LLVM API
2337 calls.
2338 </p>
2339 </div>
2340
2341 <!-- ======================================================================= -->
2342 <div class="doc_subsection">
2343   <a name="shutdown">Ending Execution with <tt>llvm_shutdown()</tt></a>
2344 </div>
2345
2346 <div class="doc_text">
2347 <p>
2348 When you are done using the LLVM APIs, you should call <tt>llvm_shutdown()</tt>
2349 to deallocate memory used for internal structures.  This will also invoke 
2350 <tt>llvm_stop_multithreaded()</tt> if LLVM is operating in multithreaded mode.
2351 As such, <tt>llvm_shutdown()</tt> requires the same isolation guarantees as
2352 <tt>llvm_stop_multithreaded()</tt>.
2353 </p>
2354
2355 <p>
2356 Note that, if you use scope-based shutdown, you can use the
2357 <tt>llvm_shutdown_obj</tt> class, which calls <tt>llvm_shutdown()</tt> in its
2358 destructor.
2359 </div>
2360
2361 <!-- ======================================================================= -->
2362 <div class="doc_subsection">
2363   <a name="managedstatic">Lazy Initialization with <tt>ManagedStatic</tt></a>
2364 </div>
2365
2366 <div class="doc_text">
2367 <p>
2368 <tt>ManagedStatic</tt> is a utility class in LLVM used to implement static
2369 initialization of static resources, such as the global type tables.  Before the
2370 invocation of <tt>llvm_shutdown()</tt>, it implements a simple lazy 
2371 initialization scheme.  Once <tt>llvm_start_multithreaded()</tt> returns,
2372 however, it uses double-checked locking to implement thread-safe lazy
2373 initialization.
2374 </p>
2375
2376 <p>
2377 Note that, because no other threads are allowed to issue LLVM API calls before
2378 <tt>llvm_start_multithreaded()</tt> returns, it is possible to have 
2379 <tt>ManagedStatic</tt>s of <tt>llvm::sys::Mutex</tt>s.
2380 </p>
2381
2382 <p>
2383 The <tt>llvm_acquire_global_lock()</tt> and <tt>llvm_release_global_lock</tt> 
2384 APIs provide access to the global lock used to implement the double-checked
2385 locking for lazy initialization.  These should only be used internally to LLVM,
2386 and only if you know what you're doing!
2387 </p>
2388 </div>
2389
2390 <!-- *********************************************************************** -->
2391 <div class="doc_section">
2392   <a name="advanced">Advanced Topics</a>
2393 </div>
2394 <!-- *********************************************************************** -->
2395
2396 <div class="doc_text">
2397 <p>
2398 This section describes some of the advanced or obscure API's that most clients
2399 do not need to be aware of.  These API's tend manage the inner workings of the
2400 LLVM system, and only need to be accessed in unusual circumstances.
2401 </p>
2402 </div>
2403
2404 <!-- ======================================================================= -->
2405 <div class="doc_subsection">
2406   <a name="TypeResolve">LLVM Type Resolution</a>
2407 </div>
2408
2409 <div class="doc_text">
2410
2411 <p>
2412 The LLVM type system has a very simple goal: allow clients to compare types for
2413 structural equality with a simple pointer comparison (aka a shallow compare).
2414 This goal makes clients much simpler and faster, and is used throughout the LLVM
2415 system.
2416 </p>
2417
2418 <p>
2419 Unfortunately achieving this goal is not a simple matter.  In particular,
2420 recursive types and late resolution of opaque types makes the situation very
2421 difficult to handle.  Fortunately, for the most part, our implementation makes
2422 most clients able to be completely unaware of the nasty internal details.  The
2423 primary case where clients are exposed to the inner workings of it are when
2424 building a recursive type.  In addition to this case, the LLVM bitcode reader,
2425 assembly parser, and linker also have to be aware of the inner workings of this
2426 system.
2427 </p>
2428
2429 <p>
2430 For our purposes below, we need three concepts.  First, an "Opaque Type" is 
2431 exactly as defined in the <a href="LangRef.html#t_opaque">language 
2432 reference</a>.  Second an "Abstract Type" is any type which includes an 
2433 opaque type as part of its type graph (for example "<tt>{ opaque, i32 }</tt>").
2434 Third, a concrete type is a type that is not an abstract type (e.g. "<tt>{ i32, 
2435 float }</tt>").
2436 </p>
2437
2438 </div>
2439
2440 <!-- ______________________________________________________________________ -->
2441 <div class="doc_subsubsection">
2442   <a name="BuildRecType">Basic Recursive Type Construction</a>
2443 </div>
2444
2445 <div class="doc_text">
2446
2447 <p>
2448 Because the most common question is "how do I build a recursive type with LLVM",
2449 we answer it now and explain it as we go.  Here we include enough to cause this
2450 to be emitted to an output .ll file:
2451 </p>
2452
2453 <div class="doc_code">
2454 <pre>
2455 %mylist = type { %mylist*, i32 }
2456 </pre>
2457 </div>
2458
2459 <p>
2460 To build this, use the following LLVM APIs:
2461 </p>
2462
2463 <div class="doc_code">
2464 <pre>
2465 // <i>Create the initial outer struct</i>
2466 <a href="#PATypeHolder">PATypeHolder</a> StructTy = OpaqueType::get();
2467 std::vector&lt;const Type*&gt; Elts;
2468 Elts.push_back(PointerType::getUnqual(StructTy));
2469 Elts.push_back(Type::Int32Ty);
2470 StructType *NewSTy = StructType::get(Elts);
2471
2472 // <i>At this point, NewSTy = "{ opaque*, i32 }". Tell VMCore that</i>
2473 // <i>the struct and the opaque type are actually the same.</i>
2474 cast&lt;OpaqueType&gt;(StructTy.get())-&gt;<a href="#refineAbstractTypeTo">refineAbstractTypeTo</a>(NewSTy);
2475
2476 // <i>NewSTy is potentially invalidated, but StructTy (a <a href="#PATypeHolder">PATypeHolder</a>) is</i>
2477 // <i>kept up-to-date</i>
2478 NewSTy = cast&lt;StructType&gt;(StructTy.get());
2479
2480 // <i>Add a name for the type to the module symbol table (optional)</i>
2481 MyModule-&gt;addTypeName("mylist", NewSTy);
2482 </pre>
2483 </div>
2484
2485 <p>
2486 This code shows the basic approach used to build recursive types: build a
2487 non-recursive type using 'opaque', then use type unification to close the cycle.
2488 The type unification step is performed by the <tt><a
2489 href="#refineAbstractTypeTo">refineAbstractTypeTo</a></tt> method, which is
2490 described next.  After that, we describe the <a
2491 href="#PATypeHolder">PATypeHolder class</a>.
2492 </p>
2493
2494 </div>
2495
2496 <!-- ______________________________________________________________________ -->
2497 <div class="doc_subsubsection">
2498   <a name="refineAbstractTypeTo">The <tt>refineAbstractTypeTo</tt> method</a>
2499 </div>
2500
2501 <div class="doc_text">
2502 <p>
2503 The <tt>refineAbstractTypeTo</tt> method starts the type unification process.
2504 While this method is actually a member of the DerivedType class, it is most
2505 often used on OpaqueType instances.  Type unification is actually a recursive
2506 process.  After unification, types can become structurally isomorphic to
2507 existing types, and all duplicates are deleted (to preserve pointer equality).
2508 </p>
2509
2510 <p>
2511 In the example above, the OpaqueType object is definitely deleted.
2512 Additionally, if there is an "{ \2*, i32}" type already created in the system,
2513 the pointer and struct type created are <b>also</b> deleted.  Obviously whenever
2514 a type is deleted, any "Type*" pointers in the program are invalidated.  As
2515 such, it is safest to avoid having <i>any</i> "Type*" pointers to abstract types
2516 live across a call to <tt>refineAbstractTypeTo</tt> (note that non-abstract
2517 types can never move or be deleted).  To deal with this, the <a
2518 href="#PATypeHolder">PATypeHolder</a> class is used to maintain a stable
2519 reference to a possibly refined type, and the <a
2520 href="#AbstractTypeUser">AbstractTypeUser</a> class is used to update more
2521 complex datastructures.
2522 </p>
2523
2524 </div>
2525
2526 <!-- ______________________________________________________________________ -->
2527 <div class="doc_subsubsection">
2528   <a name="PATypeHolder">The PATypeHolder Class</a>
2529 </div>
2530
2531 <div class="doc_text">
2532 <p>
2533 PATypeHolder is a form of a "smart pointer" for Type objects.  When VMCore
2534 happily goes about nuking types that become isomorphic to existing types, it
2535 automatically updates all PATypeHolder objects to point to the new type.  In the
2536 example above, this allows the code to maintain a pointer to the resultant
2537 resolved recursive type, even though the Type*'s are potentially invalidated.
2538 </p>
2539
2540 <p>
2541 PATypeHolder is an extremely light-weight object that uses a lazy union-find
2542 implementation to update pointers.  For example the pointer from a Value to its
2543 Type is maintained by PATypeHolder objects.
2544 </p>
2545
2546 </div>
2547
2548 <!-- ______________________________________________________________________ -->
2549 <div class="doc_subsubsection">
2550   <a name="AbstractTypeUser">The AbstractTypeUser Class</a>
2551 </div>
2552
2553 <div class="doc_text">
2554
2555 <p>
2556 Some data structures need more to perform more complex updates when types get
2557 resolved.  To support this, a class can derive from the AbstractTypeUser class.
2558 This class
2559 allows it to get callbacks when certain types are resolved.  To register to get
2560 callbacks for a particular type, the DerivedType::{add/remove}AbstractTypeUser
2561 methods can be called on a type.  Note that these methods only work for <i>
2562   abstract</i> types.  Concrete types (those that do not include any opaque 
2563 objects) can never be refined.
2564 </p>
2565 </div>
2566
2567
2568 <!-- ======================================================================= -->
2569 <div class="doc_subsection">
2570   <a name="SymbolTable">The <tt>ValueSymbolTable</tt> and
2571    <tt>TypeSymbolTable</tt> classes</a>
2572 </div>
2573
2574 <div class="doc_text">
2575 <p>The <tt><a href="http://llvm.org/doxygen/classllvm_1_1ValueSymbolTable.html">
2576 ValueSymbolTable</a></tt> class provides a symbol table that the <a
2577 href="#Function"><tt>Function</tt></a> and <a href="#Module">
2578 <tt>Module</tt></a> classes use for naming value definitions. The symbol table
2579 can provide a name for any <a href="#Value"><tt>Value</tt></a>. 
2580 The <tt><a href="http://llvm.org/doxygen/classllvm_1_1TypeSymbolTable.html">
2581 TypeSymbolTable</a></tt> class is used by the <tt>Module</tt> class to store
2582 names for types.</p>
2583
2584 <p>Note that the <tt>SymbolTable</tt> class should not be directly accessed 
2585 by most clients.  It should only be used when iteration over the symbol table 
2586 names themselves are required, which is very special purpose.  Note that not 
2587 all LLVM
2588 <tt><a href="#Value">Value</a></tt>s have names, and those without names (i.e. they have
2589 an empty name) do not exist in the symbol table.
2590 </p>
2591
2592 <p>These symbol tables support iteration over the values/types in the symbol
2593 table with <tt>begin/end/iterator</tt> and supports querying to see if a
2594 specific name is in the symbol table (with <tt>lookup</tt>).  The
2595 <tt>ValueSymbolTable</tt> class exposes no public mutator methods, instead,
2596 simply call <tt>setName</tt> on a value, which will autoinsert it into the
2597 appropriate symbol table.  For types, use the Module::addTypeName method to
2598 insert entries into the symbol table.</p>
2599
2600 </div>
2601
2602
2603
2604 <!-- ======================================================================= -->
2605 <div class="doc_subsection">
2606   <a name="UserLayout">The <tt>User</tt> and owned <tt>Use</tt> classes' memory layout</a>
2607 </div>
2608
2609 <div class="doc_text">
2610 <p>The <tt><a href="http://llvm.org/doxygen/classllvm_1_1User.html">
2611 User</a></tt> class provides a basis for expressing the ownership of <tt>User</tt>
2612 towards other <tt><a href="http://llvm.org/doxygen/classllvm_1_1Value.html">
2613 Value</a></tt>s. The <tt><a href="http://llvm.org/doxygen/classllvm_1_1Use.html">
2614 Use</a></tt> helper class is employed to do the bookkeeping and to facilitate <i>O(1)</i>
2615 addition and removal.</p>
2616
2617 <!-- ______________________________________________________________________ -->
2618 <div class="doc_subsubsection">
2619   <a name="Use2User">Interaction and relationship between <tt>User</tt> and <tt>Use</tt> objects</a>
2620 </div>
2621
2622 <div class="doc_text">
2623 <p>
2624 A subclass of <tt>User</tt> can choose between incorporating its <tt>Use</tt> objects
2625 or refer to them out-of-line by means of a pointer. A mixed variant
2626 (some <tt>Use</tt>s inline others hung off) is impractical and breaks the invariant
2627 that the <tt>Use</tt> objects belonging to the same <tt>User</tt> form a contiguous array.
2628 </p>
2629 </div>
2630
2631 <p>
2632 We have 2 different layouts in the <tt>User</tt> (sub)classes:
2633 <ul>
2634 <li><p>Layout a)
2635 The <tt>Use</tt> object(s) are inside (resp. at fixed offset) of the <tt>User</tt>
2636 object and there are a fixed number of them.</p>
2637
2638 <li><p>Layout b)
2639 The <tt>Use</tt> object(s) are referenced by a pointer to an
2640 array from the <tt>User</tt> object and there may be a variable
2641 number of them.</p>
2642 </ul>
2643 <p>
2644 As of v2.4 each layout still possesses a direct pointer to the
2645 start of the array of <tt>Use</tt>s. Though not mandatory for layout a),
2646 we stick to this redundancy for the sake of simplicity.
2647 The <tt>User</tt> object also stores the number of <tt>Use</tt> objects it
2648 has. (Theoretically this information can also be calculated
2649 given the scheme presented below.)</p>
2650 <p>
2651 Special forms of allocation operators (<tt>operator new</tt>)
2652 enforce the following memory layouts:</p>
2653
2654 <ul>
2655 <li><p>Layout a) is modelled by prepending the <tt>User</tt> object by the <tt>Use[]</tt> array.</p>
2656
2657 <pre>
2658 ...---.---.---.---.-------...
2659   | P | P | P | P | User
2660 '''---'---'---'---'-------'''
2661 </pre>
2662
2663 <li><p>Layout b) is modelled by pointing at the <tt>Use[]</tt> array.</p>
2664 <pre>
2665 .-------...
2666 | User
2667 '-------'''
2668     |
2669     v
2670     .---.---.---.---...
2671     | P | P | P | P |
2672     '---'---'---'---'''
2673 </pre>
2674 </ul>
2675 <i>(In the above figures '<tt>P</tt>' stands for the <tt>Use**</tt> that
2676     is stored in each <tt>Use</tt> object in the member <tt>Use::Prev</tt>)</i>
2677
2678 <!-- ______________________________________________________________________ -->
2679 <div class="doc_subsubsection">
2680   <a name="Waymarking">The waymarking algorithm</a>
2681 </div>
2682
2683 <div class="doc_text">
2684 <p>
2685 Since the <tt>Use</tt> objects are deprived of the direct (back)pointer to
2686 their <tt>User</tt> objects, there must be a fast and exact method to
2687 recover it. This is accomplished by the following scheme:</p>
2688 </div>
2689
2690 A bit-encoding in the 2 LSBits (least significant bits) of the <tt>Use::Prev</tt> allows to find the
2691 start of the <tt>User</tt> object:
2692 <ul>
2693 <li><tt>00</tt> &mdash;&gt; binary digit 0</li>
2694 <li><tt>01</tt> &mdash;&gt; binary digit 1</li>
2695 <li><tt>10</tt> &mdash;&gt; stop and calculate (<tt>s</tt>)</li>
2696 <li><tt>11</tt> &mdash;&gt; full stop (<tt>S</tt>)</li>
2697 </ul>
2698 <p>
2699 Given a <tt>Use*</tt>, all we have to do is to walk till we get
2700 a stop and we either have a <tt>User</tt> immediately behind or
2701 we have to walk to the next stop picking up digits
2702 and calculating the offset:</p>
2703 <pre>
2704 .---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.---.----------------
2705 | 1 | s | 1 | 0 | 1 | 0 | s | 1 | 1 | 0 | s | 1 | 1 | s | 1 | S | User (or User*)
2706 '---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'---'----------------
2707     |+15                |+10            |+6         |+3     |+1
2708     |                   |               |           |       |__>
2709     |                   |               |           |__________>
2710     |                   |               |______________________>
2711     |                   |______________________________________>
2712     |__________________________________________________________>
2713 </pre>
2714 <p>
2715 Only the significant number of bits need to be stored between the
2716 stops, so that the <i>worst case is 20 memory accesses</i> when there are
2717 1000 <tt>Use</tt> objects associated with a <tt>User</tt>.</p>
2718
2719 <!-- ______________________________________________________________________ -->
2720 <div class="doc_subsubsection">
2721   <a name="ReferenceImpl">Reference implementation</a>
2722 </div>
2723
2724 <div class="doc_text">
2725 <p>
2726 The following literate Haskell fragment demonstrates the concept:</p>
2727 </div>
2728
2729 <div class="doc_code">
2730 <pre>
2731 > import Test.QuickCheck
2732
2733 > digits :: Int -> [Char] -> [Char]
2734 > digits 0 acc = '0' : acc
2735 > digits 1 acc = '1' : acc
2736 > digits n acc = digits (n `div` 2) $ digits (n `mod` 2) acc
2737
2738 > dist :: Int -> [Char] -> [Char]
2739 > dist 0 [] = ['S']
2740 > dist 0 acc = acc
2741 > dist 1 acc = let r = dist 0 acc in 's' : digits (length r) r
2742 > dist n acc = dist (n - 1) $ dist 1 acc
2743
2744 > takeLast n ss = reverse $ take n $ reverse ss
2745
2746 > test = takeLast 40 $ dist 20 []
2747
2748 </pre>
2749 </div>
2750 <p>
2751 Printing &lt;test&gt; gives: <tt>"1s100000s11010s10100s1111s1010s110s11s1S"</tt></p>
2752 <p>
2753 The reverse algorithm computes the length of the string just by examining
2754 a certain prefix:</p>
2755
2756 <div class="doc_code">
2757 <pre>
2758 > pref :: [Char] -> Int
2759 > pref "S" = 1
2760 > pref ('s':'1':rest) = decode 2 1 rest
2761 > pref (_:rest) = 1 + pref rest
2762
2763 > decode walk acc ('0':rest) = decode (walk + 1) (acc * 2) rest
2764 > decode walk acc ('1':rest) = decode (walk + 1) (acc * 2 + 1) rest
2765 > decode walk acc _ = walk + acc
2766
2767 </pre>
2768 </div>
2769 <p>
2770 Now, as expected, printing &lt;pref test&gt; gives <tt>40</tt>.</p>
2771 <p>
2772 We can <i>quickCheck</i> this with following property:</p>
2773
2774 <div class="doc_code">
2775 <pre>
2776 > testcase = dist 2000 []
2777 > testcaseLength = length testcase
2778
2779 > identityProp n = n > 0 && n <= testcaseLength ==> length arr == pref arr
2780 >     where arr = takeLast n testcase
2781
2782 </pre>
2783 </div>
2784 <p>
2785 As expected &lt;quickCheck identityProp&gt; gives:</p>
2786
2787 <pre>
2788 *Main> quickCheck identityProp
2789 OK, passed 100 tests.
2790 </pre>
2791 <p>
2792 Let's be a bit more exhaustive:</p>
2793
2794 <div class="doc_code">
2795 <pre>
2796
2797 > deepCheck p = check (defaultConfig { configMaxTest = 500 }) p
2798
2799 </pre>
2800 </div>
2801 <p>
2802 And here is the result of &lt;deepCheck identityProp&gt;:</p>
2803
2804 <pre>
2805 *Main> deepCheck identityProp
2806 OK, passed 500 tests.
2807 </pre>
2808
2809 <!-- ______________________________________________________________________ -->
2810 <div class="doc_subsubsection">
2811   <a name="Tagging">Tagging considerations</a>
2812 </div>
2813
2814 <p>
2815 To maintain the invariant that the 2 LSBits of each <tt>Use**</tt> in <tt>Use</tt>
2816 never change after being set up, setters of <tt>Use::Prev</tt> must re-tag the
2817 new <tt>Use**</tt> on every modification. Accordingly getters must strip the
2818 tag bits.</p>
2819 <p>
2820 For layout b) instead of the <tt>User</tt> we find a pointer (<tt>User*</tt> with LSBit set).
2821 Following this pointer brings us to the <tt>User</tt>. A portable trick ensures
2822 that the first bytes of <tt>User</tt> (if interpreted as a pointer) never has
2823 the LSBit set. (Portability is relying on the fact that all known compilers place the
2824 <tt>vptr</tt> in the first word of the instances.)</p>
2825
2826 </div>
2827
2828   <!-- *********************************************************************** -->
2829 <div class="doc_section">
2830   <a name="coreclasses">The Core LLVM Class Hierarchy Reference </a>
2831 </div>
2832 <!-- *********************************************************************** -->
2833
2834 <div class="doc_text">
2835 <p><tt>#include "<a href="/doxygen/Type_8h-source.html">llvm/Type.h</a>"</tt>
2836 <br>doxygen info: <a href="/doxygen/classllvm_1_1Type.html">Type Class</a></p>
2837
2838 <p>The Core LLVM classes are the primary means of representing the program
2839 being inspected or transformed.  The core LLVM classes are defined in
2840 header files in the <tt>include/llvm/</tt> directory, and implemented in
2841 the <tt>lib/VMCore</tt> directory.</p>
2842
2843 </div>
2844
2845 <!-- ======================================================================= -->
2846 <div class="doc_subsection">
2847   <a name="Type">The <tt>Type</tt> class and Derived Types</a>
2848 </div>
2849
2850 <div class="doc_text">
2851
2852   <p><tt>Type</tt> is a superclass of all type classes. Every <tt>Value</tt> has
2853   a <tt>Type</tt>. <tt>Type</tt> cannot be instantiated directly but only
2854   through its subclasses. Certain primitive types (<tt>VoidType</tt>,
2855   <tt>LabelType</tt>, <tt>FloatType</tt> and <tt>DoubleType</tt>) have hidden 
2856   subclasses. They are hidden because they offer no useful functionality beyond
2857   what the <tt>Type</tt> class offers except to distinguish themselves from 
2858   other subclasses of <tt>Type</tt>.</p>
2859   <p>All other types are subclasses of <tt>DerivedType</tt>.  Types can be 
2860   named, but this is not a requirement. There exists exactly 
2861   one instance of a given shape at any one time.  This allows type equality to
2862   be performed with address equality of the Type Instance. That is, given two 
2863   <tt>Type*</tt> values, the types are identical if the pointers are identical.
2864   </p>
2865 </div>
2866
2867 <!-- _______________________________________________________________________ -->
2868 <div class="doc_subsubsection">
2869   <a name="m_Type">Important Public Methods</a>
2870 </div>
2871
2872 <div class="doc_text">
2873
2874 <ul>
2875   <li><tt>bool isInteger() const</tt>: Returns true for any integer type.</li>
2876
2877   <li><tt>bool isFloatingPoint()</tt>: Return true if this is one of the two
2878   floating point types.</li>
2879
2880   <li><tt>bool isAbstract()</tt>: Return true if the type is abstract (contains
2881   an OpaqueType anywhere in its definition).</li>
2882
2883   <li><tt>bool isSized()</tt>: Return true if the type has known size. Things
2884   that don't have a size are abstract types, labels and void.</li>
2885
2886 </ul>
2887 </div>
2888
2889 <!-- _______________________________________________________________________ -->
2890 <div class="doc_subsubsection">
2891   <a name="derivedtypes">Important Derived Types</a>
2892 </div>
2893 <div class="doc_text">
2894 <dl>
2895   <dt><tt>IntegerType</tt></dt>
2896   <dd>Subclass of DerivedType that represents integer types of any bit width. 
2897   Any bit width between <tt>IntegerType::MIN_INT_BITS</tt> (1) and 
2898   <tt>IntegerType::MAX_INT_BITS</tt> (~8 million) can be represented.
2899   <ul>
2900     <li><tt>static const IntegerType* get(unsigned NumBits)</tt>: get an integer
2901     type of a specific bit width.</li>
2902     <li><tt>unsigned getBitWidth() const</tt>: Get the bit width of an integer
2903     type.</li>
2904   </ul>
2905   </dd>
2906   <dt><tt>SequentialType</tt></dt>
2907   <dd>This is subclassed by ArrayType and PointerType
2908     <ul>
2909       <li><tt>const Type * getElementType() const</tt>: Returns the type of each
2910       of the elements in the sequential type. </li>
2911     </ul>
2912   </dd>
2913   <dt><tt>ArrayType</tt></dt>
2914   <dd>This is a subclass of SequentialType and defines the interface for array 
2915   types.
2916     <ul>
2917       <li><tt>unsigned getNumElements() const</tt>: Returns the number of 
2918       elements in the array. </li>
2919     </ul>
2920   </dd>
2921   <dt><tt>PointerType</tt></dt>
2922   <dd>Subclass of SequentialType for pointer types.</dd>
2923   <dt><tt>VectorType</tt></dt>
2924   <dd>Subclass of SequentialType for vector types. A 
2925   vector type is similar to an ArrayType but is distinguished because it is 
2926   a first class type wherease ArrayType is not. Vector types are used for 
2927   vector operations and are usually small vectors of of an integer or floating 
2928   point type.</dd>
2929   <dt><tt>StructType</tt></dt>
2930   <dd>Subclass of DerivedTypes for struct types.</dd>
2931   <dt><tt><a name="FunctionType">FunctionType</a></tt></dt>
2932   <dd>Subclass of DerivedTypes for function types.
2933     <ul>
2934       <li><tt>bool isVarArg() const</tt>: Returns true if its a vararg
2935       function</li>
2936       <li><tt> const Type * getReturnType() const</tt>: Returns the
2937       return type of the function.</li>
2938       <li><tt>const Type * getParamType (unsigned i)</tt>: Returns
2939       the type of the ith parameter.</li>
2940       <li><tt> const unsigned getNumParams() const</tt>: Returns the
2941       number of formal parameters.</li>
2942     </ul>
2943   </dd>
2944   <dt><tt>OpaqueType</tt></dt>
2945   <dd>Sublcass of DerivedType for abstract types. This class 
2946   defines no content and is used as a placeholder for some other type. Note 
2947   that OpaqueType is used (temporarily) during type resolution for forward 
2948   references of types. Once the referenced type is resolved, the OpaqueType 
2949   is replaced with the actual type. OpaqueType can also be used for data 
2950   abstraction. At link time opaque types can be resolved to actual types 
2951   of the same name.</dd>
2952 </dl>
2953 </div>
2954
2955
2956
2957 <!-- ======================================================================= -->
2958 <div class="doc_subsection">
2959   <a name="Module">The <tt>Module</tt> class</a>
2960 </div>
2961
2962 <div class="doc_text">
2963
2964 <p><tt>#include "<a
2965 href="/doxygen/Module_8h-source.html">llvm/Module.h</a>"</tt><br> doxygen info:
2966 <a href="/doxygen/classllvm_1_1Module.html">Module Class</a></p>
2967
2968 <p>The <tt>Module</tt> class represents the top level structure present in LLVM
2969 programs.  An LLVM module is effectively either a translation unit of the
2970 original program or a combination of several translation units merged by the
2971 linker.  The <tt>Module</tt> class keeps track of a list of <a
2972 href="#Function"><tt>Function</tt></a>s, a list of <a
2973 href="#GlobalVariable"><tt>GlobalVariable</tt></a>s, and a <a
2974 href="#SymbolTable"><tt>SymbolTable</tt></a>.  Additionally, it contains a few
2975 helpful member functions that try to make common operations easy.</p>
2976
2977 </div>
2978
2979 <!-- _______________________________________________________________________ -->
2980 <div class="doc_subsubsection">
2981   <a name="m_Module">Important Public Members of the <tt>Module</tt> class</a>
2982 </div>
2983
2984 <div class="doc_text">
2985
2986 <ul>
2987   <li><tt>Module::Module(std::string name = "")</tt></li>
2988 </ul>
2989
2990 <p>Constructing a <a href="#Module">Module</a> is easy. You can optionally
2991 provide a name for it (probably based on the name of the translation unit).</p>
2992
2993 <ul>
2994   <li><tt>Module::iterator</tt> - Typedef for function list iterator<br>
2995     <tt>Module::const_iterator</tt> - Typedef for const_iterator.<br>
2996
2997     <tt>begin()</tt>, <tt>end()</tt>
2998     <tt>size()</tt>, <tt>empty()</tt>
2999
3000     <p>These are forwarding methods that make it easy to access the contents of
3001     a <tt>Module</tt> object's <a href="#Function"><tt>Function</tt></a>
3002     list.</p></li>
3003
3004   <li><tt>Module::FunctionListType &amp;getFunctionList()</tt>
3005
3006     <p> Returns the list of <a href="#Function"><tt>Function</tt></a>s.  This is
3007     necessary to use when you need to update the list or perform a complex
3008     action that doesn't have a forwarding method.</p>
3009
3010     <p><!--  Global Variable --></p></li> 
3011 </ul>
3012
3013 <hr>
3014
3015 <ul>
3016   <li><tt>Module::global_iterator</tt> - Typedef for global variable list iterator<br>
3017
3018     <tt>Module::const_global_iterator</tt> - Typedef for const_iterator.<br>
3019
3020     <tt>global_begin()</tt>, <tt>global_end()</tt>
3021     <tt>global_size()</tt>, <tt>global_empty()</tt>
3022
3023     <p> These are forwarding methods that make it easy to access the contents of
3024     a <tt>Module</tt> object's <a
3025     href="#GlobalVariable"><tt>GlobalVariable</tt></a> list.</p></li>
3026
3027   <li><tt>Module::GlobalListType &amp;getGlobalList()</tt>
3028
3029     <p>Returns the list of <a
3030     href="#GlobalVariable"><tt>GlobalVariable</tt></a>s.  This is necessary to
3031     use when you need to update the list or perform a complex action that
3032     doesn't have a forwarding method.</p>
3033
3034     <p><!--  Symbol table stuff --> </p></li>
3035 </ul>
3036
3037 <hr>
3038
3039 <ul>
3040   <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
3041
3042     <p>Return a reference to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
3043     for this <tt>Module</tt>.</p>
3044
3045     <p><!--  Convenience methods --></p></li>
3046 </ul>
3047
3048 <hr>
3049
3050 <ul>
3051   <li><tt><a href="#Function">Function</a> *getFunction(const std::string
3052   &amp;Name, const <a href="#FunctionType">FunctionType</a> *Ty)</tt>
3053
3054     <p>Look up the specified function in the <tt>Module</tt> <a
3055     href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, return
3056     <tt>null</tt>.</p></li>
3057
3058   <li><tt><a href="#Function">Function</a> *getOrInsertFunction(const
3059   std::string &amp;Name, const <a href="#FunctionType">FunctionType</a> *T)</tt>
3060
3061     <p>Look up the specified function in the <tt>Module</tt> <a
3062     href="#SymbolTable"><tt>SymbolTable</tt></a>. If it does not exist, add an
3063     external declaration for the function and return it.</p></li>
3064
3065   <li><tt>std::string getTypeName(const <a href="#Type">Type</a> *Ty)</tt>
3066
3067     <p>If there is at least one entry in the <a
3068     href="#SymbolTable"><tt>SymbolTable</tt></a> for the specified <a
3069     href="#Type"><tt>Type</tt></a>, return it.  Otherwise return the empty
3070     string.</p></li>
3071
3072   <li><tt>bool addTypeName(const std::string &amp;Name, const <a
3073   href="#Type">Type</a> *Ty)</tt>
3074
3075     <p>Insert an entry in the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
3076     mapping <tt>Name</tt> to <tt>Ty</tt>. If there is already an entry for this
3077     name, true is returned and the <a
3078     href="#SymbolTable"><tt>SymbolTable</tt></a> is not modified.</p></li>
3079 </ul>
3080
3081 </div>
3082
3083
3084 <!-- ======================================================================= -->
3085 <div class="doc_subsection">
3086   <a name="Value">The <tt>Value</tt> class</a>
3087 </div>
3088
3089 <div class="doc_text">
3090
3091 <p><tt>#include "<a href="/doxygen/Value_8h-source.html">llvm/Value.h</a>"</tt>
3092 <br> 
3093 doxygen info: <a href="/doxygen/classllvm_1_1Value.html">Value Class</a></p>
3094
3095 <p>The <tt>Value</tt> class is the most important class in the LLVM Source
3096 base.  It represents a typed value that may be used (among other things) as an
3097 operand to an instruction.  There are many different types of <tt>Value</tt>s,
3098 such as <a href="#Constant"><tt>Constant</tt></a>s,<a
3099 href="#Argument"><tt>Argument</tt></a>s. Even <a
3100 href="#Instruction"><tt>Instruction</tt></a>s and <a
3101 href="#Function"><tt>Function</tt></a>s are <tt>Value</tt>s.</p>
3102
3103 <p>A particular <tt>Value</tt> may be used many times in the LLVM representation
3104 for a program.  For example, an incoming argument to a function (represented
3105 with an instance of the <a href="#Argument">Argument</a> class) is "used" by
3106 every instruction in the function that references the argument.  To keep track
3107 of this relationship, the <tt>Value</tt> class keeps a list of all of the <a
3108 href="#User"><tt>User</tt></a>s that is using it (the <a
3109 href="#User"><tt>User</tt></a> class is a base class for all nodes in the LLVM
3110 graph that can refer to <tt>Value</tt>s).  This use list is how LLVM represents
3111 def-use information in the program, and is accessible through the <tt>use_</tt>*
3112 methods, shown below.</p>
3113
3114 <p>Because LLVM is a typed representation, every LLVM <tt>Value</tt> is typed,
3115 and this <a href="#Type">Type</a> is available through the <tt>getType()</tt>
3116 method. In addition, all LLVM values can be named.  The "name" of the
3117 <tt>Value</tt> is a symbolic string printed in the LLVM code:</p>
3118
3119 <div class="doc_code">
3120 <pre>
3121 %<b>foo</b> = add i32 1, 2
3122 </pre>
3123 </div>
3124
3125 <p><a name="nameWarning">The name of this instruction is "foo".</a> <b>NOTE</b>
3126 that the name of any value may be missing (an empty string), so names should
3127 <b>ONLY</b> be used for debugging (making the source code easier to read,
3128 debugging printouts), they should not be used to keep track of values or map
3129 between them.  For this purpose, use a <tt>std::map</tt> of pointers to the
3130 <tt>Value</tt> itself instead.</p>
3131
3132 <p>One important aspect of LLVM is that there is no distinction between an SSA
3133 variable and the operation that produces it.  Because of this, any reference to
3134 the value produced by an instruction (or the value available as an incoming
3135 argument, for example) is represented as a direct pointer to the instance of
3136 the class that
3137 represents this value.  Although this may take some getting used to, it
3138 simplifies the representation and makes it easier to manipulate.</p>
3139
3140 </div>
3141
3142 <!-- _______________________________________________________________________ -->
3143 <div class="doc_subsubsection">
3144   <a name="m_Value">Important Public Members of the <tt>Value</tt> class</a>
3145 </div>
3146
3147 <div class="doc_text">
3148
3149 <ul>
3150   <li><tt>Value::use_iterator</tt> - Typedef for iterator over the
3151 use-list<br>
3152     <tt>Value::use_const_iterator</tt> - Typedef for const_iterator over
3153 the use-list<br>
3154     <tt>unsigned use_size()</tt> - Returns the number of users of the
3155 value.<br>
3156     <tt>bool use_empty()</tt> - Returns true if there are no users.<br>
3157     <tt>use_iterator use_begin()</tt> - Get an iterator to the start of
3158 the use-list.<br>
3159     <tt>use_iterator use_end()</tt> - Get an iterator to the end of the
3160 use-list.<br>
3161     <tt><a href="#User">User</a> *use_back()</tt> - Returns the last
3162 element in the list.
3163     <p> These methods are the interface to access the def-use
3164 information in LLVM.  As with all other iterators in LLVM, the naming
3165 conventions follow the conventions defined by the <a href="#stl">STL</a>.</p>
3166   </li>
3167   <li><tt><a href="#Type">Type</a> *getType() const</tt>
3168     <p>This method returns the Type of the Value.</p>
3169   </li>
3170   <li><tt>bool hasName() const</tt><br>
3171     <tt>std::string getName() const</tt><br>
3172     <tt>void setName(const std::string &amp;Name)</tt>
3173     <p> This family of methods is used to access and assign a name to a <tt>Value</tt>,
3174 be aware of the <a href="#nameWarning">precaution above</a>.</p>
3175   </li>
3176   <li><tt>void replaceAllUsesWith(Value *V)</tt>
3177
3178     <p>This method traverses the use list of a <tt>Value</tt> changing all <a
3179     href="#User"><tt>User</tt>s</a> of the current value to refer to
3180     "<tt>V</tt>" instead.  For example, if you detect that an instruction always
3181     produces a constant value (for example through constant folding), you can
3182     replace all uses of the instruction with the constant like this:</p>
3183
3184 <div class="doc_code">
3185 <pre>
3186 Inst-&gt;replaceAllUsesWith(ConstVal);
3187 </pre>
3188 </div>
3189
3190 </ul>
3191
3192 </div>
3193
3194 <!-- ======================================================================= -->
3195 <div class="doc_subsection">
3196   <a name="User">The <tt>User</tt> class</a>
3197 </div>
3198
3199 <div class="doc_text">
3200   
3201 <p>
3202 <tt>#include "<a href="/doxygen/User_8h-source.html">llvm/User.h</a>"</tt><br>
3203 doxygen info: <a href="/doxygen/classllvm_1_1User.html">User Class</a><br>
3204 Superclass: <a href="#Value"><tt>Value</tt></a></p>
3205
3206 <p>The <tt>User</tt> class is the common base class of all LLVM nodes that may
3207 refer to <a href="#Value"><tt>Value</tt></a>s.  It exposes a list of "Operands"
3208 that are all of the <a href="#Value"><tt>Value</tt></a>s that the User is
3209 referring to.  The <tt>User</tt> class itself is a subclass of
3210 <tt>Value</tt>.</p>
3211
3212 <p>The operands of a <tt>User</tt> point directly to the LLVM <a
3213 href="#Value"><tt>Value</tt></a> that it refers to.  Because LLVM uses Static
3214 Single Assignment (SSA) form, there can only be one definition referred to,
3215 allowing this direct connection.  This connection provides the use-def
3216 information in LLVM.</p>
3217
3218 </div>
3219
3220 <!-- _______________________________________________________________________ -->
3221 <div class="doc_subsubsection">
3222   <a name="m_User">Important Public Members of the <tt>User</tt> class</a>
3223 </div>
3224
3225 <div class="doc_text">
3226
3227 <p>The <tt>User</tt> class exposes the operand list in two ways: through
3228 an index access interface and through an iterator based interface.</p>
3229
3230 <ul>
3231   <li><tt>Value *getOperand(unsigned i)</tt><br>
3232     <tt>unsigned getNumOperands()</tt>
3233     <p> These two methods expose the operands of the <tt>User</tt> in a
3234 convenient form for direct access.</p></li>
3235
3236   <li><tt>User::op_iterator</tt> - Typedef for iterator over the operand
3237 list<br>
3238     <tt>op_iterator op_begin()</tt> - Get an iterator to the start of 
3239 the operand list.<br>
3240     <tt>op_iterator op_end()</tt> - Get an iterator to the end of the
3241 operand list.
3242     <p> Together, these methods make up the iterator based interface to
3243 the operands of a <tt>User</tt>.</p></li>
3244 </ul>
3245
3246 </div>    
3247
3248 <!-- ======================================================================= -->
3249 <div class="doc_subsection">
3250   <a name="Instruction">The <tt>Instruction</tt> class</a>
3251 </div>
3252
3253 <div class="doc_text">
3254
3255 <p><tt>#include "</tt><tt><a
3256 href="/doxygen/Instruction_8h-source.html">llvm/Instruction.h</a>"</tt><br>
3257 doxygen info: <a href="/doxygen/classllvm_1_1Instruction.html">Instruction Class</a><br>
3258 Superclasses: <a href="#User"><tt>User</tt></a>, <a
3259 href="#Value"><tt>Value</tt></a></p>
3260
3261 <p>The <tt>Instruction</tt> class is the common base class for all LLVM
3262 instructions.  It provides only a few methods, but is a very commonly used
3263 class.  The primary data tracked by the <tt>Instruction</tt> class itself is the
3264 opcode (instruction type) and the parent <a
3265 href="#BasicBlock"><tt>BasicBlock</tt></a> the <tt>Instruction</tt> is embedded
3266 into.  To represent a specific type of instruction, one of many subclasses of
3267 <tt>Instruction</tt> are used.</p>
3268
3269 <p> Because the <tt>Instruction</tt> class subclasses the <a
3270 href="#User"><tt>User</tt></a> class, its operands can be accessed in the same
3271 way as for other <a href="#User"><tt>User</tt></a>s (with the
3272 <tt>getOperand()</tt>/<tt>getNumOperands()</tt> and
3273 <tt>op_begin()</tt>/<tt>op_end()</tt> methods).</p> <p> An important file for
3274 the <tt>Instruction</tt> class is the <tt>llvm/Instruction.def</tt> file. This
3275 file contains some meta-data about the various different types of instructions
3276 in LLVM.  It describes the enum values that are used as opcodes (for example
3277 <tt>Instruction::Add</tt> and <tt>Instruction::ICmp</tt>), as well as the
3278 concrete sub-classes of <tt>Instruction</tt> that implement the instruction (for
3279 example <tt><a href="#BinaryOperator">BinaryOperator</a></tt> and <tt><a
3280 href="#CmpInst">CmpInst</a></tt>).  Unfortunately, the use of macros in
3281 this file confuses doxygen, so these enum values don't show up correctly in the
3282 <a href="/doxygen/classllvm_1_1Instruction.html">doxygen output</a>.</p>
3283
3284 </div>
3285
3286 <!-- _______________________________________________________________________ -->
3287 <div class="doc_subsubsection">
3288   <a name="s_Instruction">Important Subclasses of the <tt>Instruction</tt>
3289   class</a>
3290 </div>
3291 <div class="doc_text">
3292   <ul>
3293     <li><tt><a name="BinaryOperator">BinaryOperator</a></tt>
3294     <p>This subclasses represents all two operand instructions whose operands
3295     must be the same type, except for the comparison instructions.</p></li>
3296     <li><tt><a name="CastInst">CastInst</a></tt>
3297     <p>This subclass is the parent of the 12 casting instructions. It provides
3298     common operations on cast instructions.</p>
3299     <li><tt><a name="CmpInst">CmpInst</a></tt>
3300     <p>This subclass respresents the two comparison instructions, 
3301     <a href="LangRef.html#i_icmp">ICmpInst</a> (integer opreands), and
3302     <a href="LangRef.html#i_fcmp">FCmpInst</a> (floating point operands).</p>
3303     <li><tt><a name="TerminatorInst">TerminatorInst</a></tt>
3304     <p>This subclass is the parent of all terminator instructions (those which
3305     can terminate a block).</p>
3306   </ul>
3307   </div>
3308
3309 <!-- _______________________________________________________________________ -->
3310 <div class="doc_subsubsection">
3311   <a name="m_Instruction">Important Public Members of the <tt>Instruction</tt>
3312   class</a>
3313 </div>
3314
3315 <div class="doc_text">
3316
3317 <ul>
3318   <li><tt><a href="#BasicBlock">BasicBlock</a> *getParent()</tt>
3319     <p>Returns the <a href="#BasicBlock"><tt>BasicBlock</tt></a> that
3320 this  <tt>Instruction</tt> is embedded into.</p></li>
3321   <li><tt>bool mayWriteToMemory()</tt>
3322     <p>Returns true if the instruction writes to memory, i.e. it is a
3323       <tt>call</tt>,<tt>free</tt>,<tt>invoke</tt>, or <tt>store</tt>.</p></li>
3324   <li><tt>unsigned getOpcode()</tt>
3325     <p>Returns the opcode for the <tt>Instruction</tt>.</p></li>
3326   <li><tt><a href="#Instruction">Instruction</a> *clone() const</tt>
3327     <p>Returns another instance of the specified instruction, identical
3328 in all ways to the original except that the instruction has no parent
3329 (ie it's not embedded into a <a href="#BasicBlock"><tt>BasicBlock</tt></a>),
3330 and it has no name</p></li>
3331 </ul>
3332
3333 </div>
3334
3335 <!-- ======================================================================= -->
3336 <div class="doc_subsection">
3337   <a name="Constant">The <tt>Constant</tt> class and subclasses</a>
3338 </div>
3339
3340 <div class="doc_text">
3341
3342 <p>Constant represents a base class for different types of constants. It
3343 is subclassed by ConstantInt, ConstantArray, etc. for representing 
3344 the various types of Constants.  <a href="#GlobalValue">GlobalValue</a> is also
3345 a subclass, which represents the address of a global variable or function.
3346 </p>
3347
3348 </div>
3349
3350 <!-- _______________________________________________________________________ -->
3351 <div class="doc_subsubsection">Important Subclasses of Constant </div>
3352 <div class="doc_text">
3353 <ul>
3354   <li>ConstantInt : This subclass of Constant represents an integer constant of
3355   any width.
3356     <ul>
3357       <li><tt>const APInt&amp; getValue() const</tt>: Returns the underlying
3358       value of this constant, an APInt value.</li>
3359       <li><tt>int64_t getSExtValue() const</tt>: Converts the underlying APInt
3360       value to an int64_t via sign extension. If the value (not the bit width)
3361       of the APInt is too large to fit in an int64_t, an assertion will result.
3362       For this reason, use of this method is discouraged.</li>
3363       <li><tt>uint64_t getZExtValue() const</tt>: Converts the underlying APInt
3364       value to a uint64_t via zero extension. IF the value (not the bit width)
3365       of the APInt is too large to fit in a uint64_t, an assertion will result.
3366       For this reason, use of this method is discouraged.</li>
3367       <li><tt>static ConstantInt* get(const APInt&amp; Val)</tt>: Returns the
3368       ConstantInt object that represents the value provided by <tt>Val</tt>.
3369       The type is implied as the IntegerType that corresponds to the bit width
3370       of <tt>Val</tt>.</li>
3371       <li><tt>static ConstantInt* get(const Type *Ty, uint64_t Val)</tt>: 
3372       Returns the ConstantInt object that represents the value provided by 
3373       <tt>Val</tt> for integer type <tt>Ty</tt>.</li>
3374     </ul>
3375   </li>
3376   <li>ConstantFP : This class represents a floating point constant.
3377     <ul>
3378       <li><tt>double getValue() const</tt>: Returns the underlying value of 
3379       this constant. </li>
3380     </ul>
3381   </li>
3382   <li>ConstantArray : This represents a constant array.
3383     <ul>
3384       <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns 
3385       a vector of component constants that makeup this array. </li>
3386     </ul>
3387   </li>
3388   <li>ConstantStruct : This represents a constant struct.
3389     <ul>
3390       <li><tt>const std::vector&lt;Use&gt; &amp;getValues() const</tt>: Returns 
3391       a vector of component constants that makeup this array. </li>
3392     </ul>
3393   </li>
3394   <li>GlobalValue : This represents either a global variable or a function. In 
3395   either case, the value is a constant fixed address (after linking). 
3396   </li>
3397 </ul>
3398 </div>
3399
3400
3401 <!-- ======================================================================= -->
3402 <div class="doc_subsection">
3403   <a name="GlobalValue">The <tt>GlobalValue</tt> class</a>
3404 </div>
3405
3406 <div class="doc_text">
3407
3408 <p><tt>#include "<a
3409 href="/doxygen/GlobalValue_8h-source.html">llvm/GlobalValue.h</a>"</tt><br>
3410 doxygen info: <a href="/doxygen/classllvm_1_1GlobalValue.html">GlobalValue
3411 Class</a><br>
3412 Superclasses: <a href="#Constant"><tt>Constant</tt></a>, 
3413 <a href="#User"><tt>User</tt></a>, <a href="#Value"><tt>Value</tt></a></p>
3414
3415 <p>Global values (<a href="#GlobalVariable"><tt>GlobalVariable</tt></a>s or <a
3416 href="#Function"><tt>Function</tt></a>s) are the only LLVM values that are
3417 visible in the bodies of all <a href="#Function"><tt>Function</tt></a>s.
3418 Because they are visible at global scope, they are also subject to linking with
3419 other globals defined in different translation units.  To control the linking
3420 process, <tt>GlobalValue</tt>s know their linkage rules. Specifically,
3421 <tt>GlobalValue</tt>s know whether they have internal or external linkage, as
3422 defined by the <tt>LinkageTypes</tt> enumeration.</p>
3423
3424 <p>If a <tt>GlobalValue</tt> has internal linkage (equivalent to being
3425 <tt>static</tt> in C), it is not visible to code outside the current translation
3426 unit, and does not participate in linking.  If it has external linkage, it is
3427 visible to external code, and does participate in linking.  In addition to
3428 linkage information, <tt>GlobalValue</tt>s keep track of which <a
3429 href="#Module"><tt>Module</tt></a> they are currently part of.</p>
3430
3431 <p>Because <tt>GlobalValue</tt>s are memory objects, they are always referred to
3432 by their <b>address</b>. As such, the <a href="#Type"><tt>Type</tt></a> of a
3433 global is always a pointer to its contents. It is important to remember this
3434 when using the <tt>GetElementPtrInst</tt> instruction because this pointer must
3435 be dereferenced first. For example, if you have a <tt>GlobalVariable</tt> (a
3436 subclass of <tt>GlobalValue)</tt> that is an array of 24 ints, type <tt>[24 x
3437 i32]</tt>, then the <tt>GlobalVariable</tt> is a pointer to that array. Although
3438 the address of the first element of this array and the value of the
3439 <tt>GlobalVariable</tt> are the same, they have different types. The
3440 <tt>GlobalVariable</tt>'s type is <tt>[24 x i32]</tt>. The first element's type
3441 is <tt>i32.</tt> Because of this, accessing a global value requires you to
3442 dereference the pointer with <tt>GetElementPtrInst</tt> first, then its elements
3443 can be accessed. This is explained in the <a href="LangRef.html#globalvars">LLVM
3444 Language Reference Manual</a>.</p>
3445
3446 </div>
3447
3448 <!-- _______________________________________________________________________ -->
3449 <div class="doc_subsubsection">
3450   <a name="m_GlobalValue">Important Public Members of the <tt>GlobalValue</tt>
3451   class</a>
3452 </div>
3453
3454 <div class="doc_text">
3455
3456 <ul>
3457   <li><tt>bool hasInternalLinkage() const</tt><br>
3458     <tt>bool hasExternalLinkage() const</tt><br>
3459     <tt>void setInternalLinkage(bool HasInternalLinkage)</tt>
3460     <p> These methods manipulate the linkage characteristics of the <tt>GlobalValue</tt>.</p>
3461     <p> </p>
3462   </li>
3463   <li><tt><a href="#Module">Module</a> *getParent()</tt>
3464     <p> This returns the <a href="#Module"><tt>Module</tt></a> that the
3465 GlobalValue is currently embedded into.</p></li>
3466 </ul>
3467
3468 </div>
3469
3470 <!-- ======================================================================= -->
3471 <div class="doc_subsection">
3472   <a name="Function">The <tt>Function</tt> class</a>
3473 </div>
3474
3475 <div class="doc_text">
3476
3477 <p><tt>#include "<a
3478 href="/doxygen/Function_8h-source.html">llvm/Function.h</a>"</tt><br> doxygen
3479 info: <a href="/doxygen/classllvm_1_1Function.html">Function Class</a><br>
3480 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>, 
3481 <a href="#Constant"><tt>Constant</tt></a>, 
3482 <a href="#User"><tt>User</tt></a>, 
3483 <a href="#Value"><tt>Value</tt></a></p>
3484
3485 <p>The <tt>Function</tt> class represents a single procedure in LLVM.  It is
3486 actually one of the more complex classes in the LLVM heirarchy because it must
3487 keep track of a large amount of data.  The <tt>Function</tt> class keeps track
3488 of a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, a list of formal 
3489 <a href="#Argument"><tt>Argument</tt></a>s, and a 
3490 <a href="#SymbolTable"><tt>SymbolTable</tt></a>.</p>
3491
3492 <p>The list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s is the most
3493 commonly used part of <tt>Function</tt> objects.  The list imposes an implicit
3494 ordering of the blocks in the function, which indicate how the code will be
3495 layed out by the backend.  Additionally, the first <a
3496 href="#BasicBlock"><tt>BasicBlock</tt></a> is the implicit entry node for the
3497 <tt>Function</tt>.  It is not legal in LLVM to explicitly branch to this initial
3498 block.  There are no implicit exit nodes, and in fact there may be multiple exit
3499 nodes from a single <tt>Function</tt>.  If the <a
3500 href="#BasicBlock"><tt>BasicBlock</tt></a> list is empty, this indicates that
3501 the <tt>Function</tt> is actually a function declaration: the actual body of the
3502 function hasn't been linked in yet.</p>
3503
3504 <p>In addition to a list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s, the
3505 <tt>Function</tt> class also keeps track of the list of formal <a
3506 href="#Argument"><tt>Argument</tt></a>s that the function receives.  This
3507 container manages the lifetime of the <a href="#Argument"><tt>Argument</tt></a>
3508 nodes, just like the <a href="#BasicBlock"><tt>BasicBlock</tt></a> list does for
3509 the <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.</p>
3510
3511 <p>The <a href="#SymbolTable"><tt>SymbolTable</tt></a> is a very rarely used
3512 LLVM feature that is only used when you have to look up a value by name.  Aside
3513 from that, the <a href="#SymbolTable"><tt>SymbolTable</tt></a> is used
3514 internally to make sure that there are not conflicts between the names of <a
3515 href="#Instruction"><tt>Instruction</tt></a>s, <a
3516 href="#BasicBlock"><tt>BasicBlock</tt></a>s, or <a
3517 href="#Argument"><tt>Argument</tt></a>s in the function body.</p>
3518
3519 <p>Note that <tt>Function</tt> is a <a href="#GlobalValue">GlobalValue</a>
3520 and therefore also a <a href="#Constant">Constant</a>. The value of the function
3521 is its address (after linking) which is guaranteed to be constant.</p>
3522 </div>
3523
3524 <!-- _______________________________________________________________________ -->
3525 <div class="doc_subsubsection">
3526   <a name="m_Function">Important Public Members of the <tt>Function</tt>
3527   class</a>
3528 </div>
3529
3530 <div class="doc_text">
3531
3532 <ul>
3533   <li><tt>Function(const </tt><tt><a href="#FunctionType">FunctionType</a>
3534   *Ty, LinkageTypes Linkage, const std::string &amp;N = "", Module* Parent = 0)</tt>
3535
3536     <p>Constructor used when you need to create new <tt>Function</tt>s to add
3537     the the program.  The constructor must specify the type of the function to
3538     create and what type of linkage the function should have. The <a 
3539     href="#FunctionType"><tt>FunctionType</tt></a> argument
3540     specifies the formal arguments and return value for the function. The same
3541     <a href="#FunctionType"><tt>FunctionType</tt></a> value can be used to
3542     create multiple functions. The <tt>Parent</tt> argument specifies the Module
3543     in which the function is defined. If this argument is provided, the function
3544     will automatically be inserted into that module's list of
3545     functions.</p></li>
3546
3547   <li><tt>bool isDeclaration()</tt>
3548
3549     <p>Return whether or not the <tt>Function</tt> has a body defined.  If the
3550     function is "external", it does not have a body, and thus must be resolved
3551     by linking with a function defined in a different translation unit.</p></li>
3552
3553   <li><tt>Function::iterator</tt> - Typedef for basic block list iterator<br>
3554     <tt>Function::const_iterator</tt> - Typedef for const_iterator.<br>
3555
3556     <tt>begin()</tt>, <tt>end()</tt>
3557     <tt>size()</tt>, <tt>empty()</tt>
3558
3559     <p>These are forwarding methods that make it easy to access the contents of
3560     a <tt>Function</tt> object's <a href="#BasicBlock"><tt>BasicBlock</tt></a>
3561     list.</p></li>
3562
3563   <li><tt>Function::BasicBlockListType &amp;getBasicBlockList()</tt>
3564
3565     <p>Returns the list of <a href="#BasicBlock"><tt>BasicBlock</tt></a>s.  This
3566     is necessary to use when you need to update the list or perform a complex
3567     action that doesn't have a forwarding method.</p></li>
3568
3569   <li><tt>Function::arg_iterator</tt> - Typedef for the argument list
3570 iterator<br>
3571     <tt>Function::const_arg_iterator</tt> - Typedef for const_iterator.<br>
3572
3573     <tt>arg_begin()</tt>, <tt>arg_end()</tt>
3574     <tt>arg_size()</tt>, <tt>arg_empty()</tt>
3575
3576     <p>These are forwarding methods that make it easy to access the contents of
3577     a <tt>Function</tt> object's <a href="#Argument"><tt>Argument</tt></a>
3578     list.</p></li>
3579
3580   <li><tt>Function::ArgumentListType &amp;getArgumentList()</tt>
3581
3582     <p>Returns the list of <a href="#Argument"><tt>Argument</tt></a>s.  This is
3583     necessary to use when you need to update the list or perform a complex
3584     action that doesn't have a forwarding method.</p></li>
3585
3586   <li><tt><a href="#BasicBlock">BasicBlock</a> &amp;getEntryBlock()</tt>
3587
3588     <p>Returns the entry <a href="#BasicBlock"><tt>BasicBlock</tt></a> for the
3589     function.  Because the entry block for the function is always the first
3590     block, this returns the first block of the <tt>Function</tt>.</p></li>
3591
3592   <li><tt><a href="#Type">Type</a> *getReturnType()</tt><br>
3593     <tt><a href="#FunctionType">FunctionType</a> *getFunctionType()</tt>
3594
3595     <p>This traverses the <a href="#Type"><tt>Type</tt></a> of the
3596     <tt>Function</tt> and returns the return type of the function, or the <a
3597     href="#FunctionType"><tt>FunctionType</tt></a> of the actual
3598     function.</p></li>
3599
3600   <li><tt><a href="#SymbolTable">SymbolTable</a> *getSymbolTable()</tt>
3601
3602     <p> Return a pointer to the <a href="#SymbolTable"><tt>SymbolTable</tt></a>
3603     for this <tt>Function</tt>.</p></li>
3604 </ul>
3605
3606 </div>
3607
3608 <!-- ======================================================================= -->
3609 <div class="doc_subsection">
3610   <a name="GlobalVariable">The <tt>GlobalVariable</tt> class</a>
3611 </div>
3612
3613 <div class="doc_text">
3614
3615 <p><tt>#include "<a
3616 href="/doxygen/GlobalVariable_8h-source.html">llvm/GlobalVariable.h</a>"</tt>
3617 <br>
3618 doxygen info: <a href="/doxygen/classllvm_1_1GlobalVariable.html">GlobalVariable
3619  Class</a><br>
3620 Superclasses: <a href="#GlobalValue"><tt>GlobalValue</tt></a>, 
3621 <a href="#Constant"><tt>Constant</tt></a>,
3622 <a href="#User"><tt>User</tt></a>,
3623 <a href="#Value"><tt>Value</tt></a></p>
3624
3625 <p>Global variables are represented with the (suprise suprise)
3626 <tt>GlobalVariable</tt> class. Like functions, <tt>GlobalVariable</tt>s are also
3627 subclasses of <a href="#GlobalValue"><tt>GlobalValue</tt></a>, and as such are
3628 always referenced by their address (global values must live in memory, so their
3629 "name" refers to their constant address). See 
3630 <a href="#GlobalValue"><tt>GlobalValue</tt></a> for more on this.  Global 
3631 variables may have an initial value (which must be a 
3632 <a href="#Constant"><tt>Constant</tt></a>), and if they have an initializer, 
3633 they may be marked as "constant" themselves (indicating that their contents 
3634 never change at runtime).</p>
3635 </div>
3636
3637 <!-- _______________________________________________________________________ -->
3638 <div class="doc_subsubsection">
3639   <a name="m_GlobalVariable">Important Public Members of the
3640   <tt>GlobalVariable</tt> class</a>
3641 </div>
3642
3643 <div class="doc_text">
3644
3645 <ul>
3646   <li><tt>GlobalVariable(const </tt><tt><a href="#Type">Type</a> *Ty, bool
3647   isConstant, LinkageTypes&amp; Linkage, <a href="#Constant">Constant</a>
3648   *Initializer = 0, const std::string &amp;Name = "", Module* Parent = 0)</tt>
3649
3650     <p>Create a new global variable of the specified type. If
3651     <tt>isConstant</tt> is true then the global variable will be marked as
3652     unchanging for the program. The Linkage parameter specifies the type of
3653     linkage (internal, external, weak, linkonce, appending) for the variable.
3654     If the linkage is InternalLinkage, WeakAnyLinkage, WeakODRLinkage,
3655     LinkOnceAnyLinkage or LinkOnceODRLinkage,&nbsp; then the resultant
3656     global variable will have internal linkage.  AppendingLinkage concatenates
3657     together all instances (in different translation units) of the variable
3658     into a single variable but is only applicable to arrays.  &nbsp;See
3659     the <a href="LangRef.html#modulestructure">LLVM Language Reference</a> for
3660     further details on linkage types. Optionally an initializer, a name, and the
3661     module to put the variable into may be specified for the global variable as
3662     well.</p></li>
3663
3664   <li><tt>bool isConstant() const</tt>
3665
3666     <p>Returns true if this is a global variable that is known not to
3667     be modified at runtime.</p></li>
3668
3669   <li><tt>bool hasInitializer()</tt>
3670
3671     <p>Returns true if this <tt>GlobalVariable</tt> has an intializer.</p></li>
3672
3673   <li><tt><a href="#Constant">Constant</a> *getInitializer()</tt>
3674
3675     <p>Returns the intial value for a <tt>GlobalVariable</tt>.  It is not legal
3676     to call this method if there is no initializer.</p></li>
3677 </ul>
3678
3679 </div>
3680
3681
3682 <!-- ======================================================================= -->
3683 <div class="doc_subsection">
3684   <a name="BasicBlock">The <tt>BasicBlock</tt> class</a>
3685 </div>
3686
3687 <div class="doc_text">
3688
3689 <p><tt>#include "<a
3690 href="/doxygen/BasicBlock_8h-source.html">llvm/BasicBlock.h</a>"</tt><br>
3691 doxygen info: <a href="/doxygen/classllvm_1_1BasicBlock.html">BasicBlock
3692 Class</a><br>
3693 Superclass: <a href="#Value"><tt>Value</tt></a></p>
3694
3695 <p>This class represents a single entry multiple exit section of the code,
3696 commonly known as a basic block by the compiler community.  The
3697 <tt>BasicBlock</tt> class maintains a list of <a
3698 href="#Instruction"><tt>Instruction</tt></a>s, which form the body of the block.
3699 Matching the language definition, the last element of this list of instructions
3700 is always a terminator instruction (a subclass of the <a
3701 href="#TerminatorInst"><tt>TerminatorInst</tt></a> class).</p>
3702
3703 <p>In addition to tracking the list of instructions that make up the block, the
3704 <tt>BasicBlock</tt> class also keeps track of the <a
3705 href="#Function"><tt>Function</tt></a> that it is embedded into.</p>
3706
3707 <p>Note that <tt>BasicBlock</tt>s themselves are <a
3708 href="#Value"><tt>Value</tt></a>s, because they are referenced by instructions
3709 like branches and can go in the switch tables. <tt>BasicBlock</tt>s have type
3710 <tt>label</tt>.</p>
3711
3712 </div>
3713
3714 <!-- _______________________________________________________________________ -->
3715 <div class="doc_subsubsection">
3716   <a name="m_BasicBlock">Important Public Members of the <tt>BasicBlock</tt>
3717   class</a>
3718 </div>
3719
3720 <div class="doc_text">
3721 <ul>
3722
3723 <li><tt>BasicBlock(const std::string &amp;Name = "", </tt><tt><a
3724  href="#Function">Function</a> *Parent = 0)</tt>
3725
3726 <p>The <tt>BasicBlock</tt> constructor is used to create new basic blocks for
3727 insertion into a function.  The constructor optionally takes a name for the new
3728 block, and a <a href="#Function"><tt>Function</tt></a> to insert it into.  If
3729 the <tt>Parent</tt> parameter is specified, the new <tt>BasicBlock</tt> is
3730 automatically inserted at the end of the specified <a
3731 href="#Function"><tt>Function</tt></a>, if not specified, the BasicBlock must be
3732 manually inserted into the <a href="#Function"><tt>Function</tt></a>.</p></li>
3733
3734 <li><tt>BasicBlock::iterator</tt> - Typedef for instruction list iterator<br>
3735 <tt>BasicBlock::const_iterator</tt> - Typedef for const_iterator.<br>
3736 <tt>begin()</tt>, <tt>end()</tt>, <tt>front()</tt>, <tt>back()</tt>,
3737 <tt>size()</tt>, <tt>empty()</tt>
3738 STL-style functions for accessing the instruction list.
3739
3740 <p>These methods and typedefs are forwarding functions that have the same
3741 semantics as the standard library methods of the same names.  These methods
3742 expose the underlying instruction list of a basic block in a way that is easy to
3743 manipulate.  To get the full complement of container operations (including
3744 operations to update the list), you must use the <tt>getInstList()</tt>
3745 method.</p></li>
3746
3747 <li><tt>BasicBlock::InstListType &amp;getInstList()</tt>
3748
3749 <p>This method is used to get access to the underlying container that actually
3750 holds the Instructions.  This method must be used when there isn't a forwarding
3751 function in the <tt>BasicBlock</tt> class for the operation that you would like
3752 to perform.  Because there are no forwarding functions for "updating"
3753 operations, you need to use this if you want to update the contents of a
3754 <tt>BasicBlock</tt>.</p></li>
3755
3756 <li><tt><a href="#Function">Function</a> *getParent()</tt>
3757
3758 <p> Returns a pointer to <a href="#Function"><tt>Function</tt></a> the block is
3759 embedded into, or a null pointer if it is homeless.</p></li>
3760
3761 <li><tt><a href="#TerminatorInst">TerminatorInst</a> *getTerminator()</tt>
3762
3763 <p> Returns a pointer to the terminator instruction that appears at the end of
3764 the <tt>BasicBlock</tt>.  If there is no terminator instruction, or if the last
3765 instruction in the block is not a terminator, then a null pointer is
3766 returned.</p></li>
3767
3768 </ul>
3769
3770 </div>
3771
3772
3773 <!-- ======================================================================= -->
3774 <div class="doc_subsection">
3775   <a name="Argument">The <tt>Argument</tt> class</a>
3776 </div>
3777
3778 <div class="doc_text">
3779
3780 <p>This subclass of Value defines the interface for incoming formal
3781 arguments to a function. A Function maintains a list of its formal
3782 arguments. An argument has a pointer to the parent Function.</p>
3783
3784 </div>
3785
3786 <!-- *********************************************************************** -->
3787 <hr>
3788 <address>
3789   <a href="http://jigsaw.w3.org/css-validator/check/referer"><img
3790   src="http://jigsaw.w3.org/css-validator/images/vcss-blue" alt="Valid CSS"></a>
3791   <a href="http://validator.w3.org/check/referer"><img
3792   src="http://www.w3.org/Icons/valid-html401" alt="Valid HTML 4.01 Strict"></a>
3793
3794   <a href="mailto:dhurjati@cs.uiuc.edu">Dinakar Dhurjati</a> and
3795   <a href="mailto:sabre@nondot.org">Chris Lattner</a><br>
3796   <a href="http://llvm.org">The LLVM Compiler Infrastructure</a><br>
3797   Last modified: $Date$
3798 </address>
3799
3800 </body>
3801 </html>