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