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