4e754cb1a361194c36eb3e39c426805b3ac11afb
[oota-llvm.git] / docs / WritingAnLLVMPass.html
1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2 <html><head><title>Writing an LLVM Pass</title></head>
3
4 <body bgcolor=white>
5
6 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
7 <tr><td>&nbsp; <font size=+3 color="#EEEEFF" face="Georgia,Palatino,Times,Roman"><b>Writing an LLVM Pass</b></font></td>
8 </tr></table>
9
10
11 <ol>
12   <li><a href="#introduction">Introduction - What is a pass?</a>
13   <li><a href="#quickstart">Quick Start - Writing hello world</a>
14     <ul>
15     <li><a href="#makefile">Setting up the build environment</a>
16     <li><a href="#basiccode">Basic code required</a>
17     <li><a href="#running">Running a pass with <tt>opt</tt>
18          or <tt>analyze</tt></a>
19     </ul>
20   <li><a href="#passtype">Pass classes and requirements</a>
21      <ul>
22      <li><a href="#Pass">The <tt>Pass</tt> class</a>
23         <ul>
24         <li><a href="#run">The <tt>run</tt> method</a>
25         </ul>
26      <li><a href="#FunctionPass">The <tt>FunctionPass</tt> class</a>
27         <ul>
28         <li><a href="#doInitialization_mod">The <tt>doInitialization(Module
29                                             &amp;)</tt> method</a>
30         <li><a href="#runOnFunction">The <tt>runOnFunction</tt> method</a>
31         <li><a href="#doFinalization_mod">The <tt>doFinalization(Module
32                                             &amp;)</tt> method</a>
33         </ul>
34      <li><a href="#BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
35         <ul>
36         <li><a href="#doInitialization_fn">The <tt>doInitialization(Function
37                                              &amp;)</tt> method</a>
38         <li><a href="#runOnBasicBlock">The <tt>runOnBasicBlock</tt> method</a>
39         <li><a href="#doFinalization_fn">The <tt>doFinalization(Function
40                                              &amp;)</tt> method</a>
41         </ul>
42      </ul>
43   <li><a href="#registration">Pass Registration</a>
44      <ul>
45      <li><a href="#print">The <tt>print</tt> method</a>
46      </ul>
47   <li><a href="#interaction">Specifying interactions between passes</a>
48      <ul>
49      <li><a href="#getAnalysisUsage">The <tt>getAnalysisUsage</tt> method</a>
50      <li><a href="#getAnalysis">The <tt>getAnalysis</tt> method</a>
51      </ul>
52   <li><a href="#analysisgroup">Implementing Analysis Groups</a>
53      <ul>
54      <li><a href="#agconcepts">Analysis Group Concepts</a>
55      <li><a href="#registerag">Using <tt>RegisterAnalysisGroup</tt></a>
56      </ul>
57   <li><a href="#passmanager">What PassManager does</a>
58     <ul>
59     <li><a href="#releaseMemory">The <tt>releaseMemory</tt> method</a>
60     </ul>
61   <li><a href="#debughints">Using GDB with dynamically loaded passes</a>
62     <ul>
63     <li><a href="#breakpoint">Setting a breakpoint in your pass
64     <li><a href="#debugmisc">Miscellaneous Problems
65     </ul>
66   <li><a href="#future">Future extensions planned</a>
67     <ul>
68     <li><a href="#SMP">Multithreaded LLVM</a>
69     <li><a href="#ModuleSource">A new <tt>ModuleSource</tt> interface</a>
70     <li><a href="#PassFunctionPass"><tt>Pass</tt>'s requiring <tt>FunctionPass</tt>'s</a>
71     </ul>
72
73   <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
74 </ol><p>
75
76
77
78 <!-- *********************************************************************** -->
79 <table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
80 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
81 <a name="introduction">Introduction - What is a pass?
82 </b></font></td></tr></table><ul>
83 <!-- *********************************************************************** -->
84
85 The LLVM Pass Framework is an important part of the LLVM system, because LLVM
86 passes are where the interesting parts of the compiler exist.  Passes perform
87 the transformations and optimizations that make up the compiler, they build
88 the analysis results that are used by these transformations, and they are, above
89 all, a structuring technique for compiler code.<p>
90
91 All LLVM passes are subclasses of the <tt><a
92 href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt> class, which
93 implement functionality by overriding virtual methods inherited from
94 <tt>Pass</tt>.  Depending on how your pass works, you may be able to inherit
95 from the <tt><a
96 href="http://llvm.cs.uiuc.edu/doxygen/structFunctionPass.html">FunctionPass</a></tt>
97 or <tt><a
98 href="http://llvm.cs.uiuc.edu/doxygen/structBasicBlockPass.html">BasicBlockPass</a></tt>,
99 which gives the system more information about what your pass does, and how it
100 can be combined with other passes.  One of the main features of the LLVM Pass
101 Framework is that it schedules passes to run in an efficient way based on the
102 constraints that your pass has.<p>
103
104 We start by showing you how to construct a pass, everything from setting up the
105 code, to compiling, loading, and executing it.  After the basics are down, more
106 advanced features are discussed.<p>
107
108
109 <!-- *********************************************************************** -->
110 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
111 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
112 <a name="quickstart">Quick Start - Writing hello world
113 </b></font></td></tr></table><ul>
114 <!-- *********************************************************************** -->
115
116 Here we describe how to write the "hello world" of passes.  The "Hello" pass is
117 designed to simply print out the name of non-external functions that exist in
118 the program being compiled.  It does not modify the program at all, just
119 inspects it.  The source code and files for this pass are available in the LLVM
120 source tree in the <tt>lib/Transforms/Hello</tt> directory.<p>
121
122
123 <!-- ======================================================================= -->
124 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
125 <tr><td>&nbsp;</td><td width="100%">&nbsp; 
126 <font color="#EEEEFF" face="Georgia,Palatino"><b>
127 <a name="makefile">Setting up the build environment
128 </b></font></td></tr></table><ul>
129
130 First thing you need to do is create a new directory somewhere in the LLVM
131 source base.  For this example, we'll assume that you made
132 "<tt>lib/Transforms/Hello</tt>".  The first thing you must do is set up a build
133 script (Makefile) that will compile the source code for the new pass.  To do
134 this, copy this into "<tt>Makefile</tt>":<p>
135
136 </ul><hr><ul><pre>
137 # Makefile for hello pass
138
139 # Path to top level of LLVM heirarchy
140 LEVEL = ../../..
141
142 # Name of the library to build
143 LIBRARYNAME = hello
144
145 # Build a dynamically loadable shared object
146 SHARED_LIBRARY = 1
147
148 # Include the makefile implementation stuff
149 include $(LEVEL)/Makefile.common
150 </pre></ul><hr><ul><p>
151
152 This makefile specifies that all of the <tt>.cpp</tt> files in the current
153 directory are to be compiled and linked together into a
154 <tt>lib/Debug/libhello.so</tt> shared object that can be dynamically loaded by
155 the <tt>opt</tt> or <tt>analyze</tt> tools.<p>
156
157 Now that we have the build scripts set up, we just need to write the code for
158 the pass itself.<p>
159
160
161 <!-- ======================================================================= -->
162 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
163 <tr><td>&nbsp;</td><td width="100%">&nbsp; 
164 <font color="#EEEEFF" face="Georgia,Palatino"><b>
165 <a name="basiccode">Basic code required
166 </b></font></td></tr></table><ul>
167
168 Now that we have a way to compile our new pass, we just have to write it.  Start
169 out with:<p>
170
171 <pre>
172 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
173 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Function_8h-source.html">llvm/Function.h</a>"
174 </pre>
175
176 Which are needed because we are writing a <tt><a
177 href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt>, and we are
178 operating on <tt><a
179 href="http://llvm.cs.uiuc.edu/doxygen/classFunction.html">Function</a></tt>'s.<p>
180
181 Next we have:<p>
182
183 <pre>
184 <b>namespace</b> {
185 </pre><p>
186
187 ... which starts out an anonymous namespace.  Anonymous namespaces are to C++
188 what the "<tt>static</tt>" keyword is to C (at global scope).  It makes the
189 things declared inside of the anonymous namespace only visible to the current
190 file.  If you're not familiar with them, consult a decent C++ book for more
191 information.<p>
192
193 Next, we declare our pass itself:<p>
194
195 <pre>
196   <b>struct</b> Hello : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
197 </pre><p>
198
199 This declares a "<tt>Hello</tt>" class that is a subclass of <tt><a
200 href="http://llvm.cs.uiuc.edu/doxygen/structFunctionPass.html">FunctionPass</a></tt>.
201 The different builtin pass subclasses are described in detail <a
202 href="#passtype">later</a>, but for now, know that <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s
203 operate a function at a time.<p>
204
205 <pre>
206     <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &F) {
207       std::cerr &lt;&lt; "<i>Hello: </i>" &lt;&lt; F.getName() &lt;&lt; "\n";
208       <b>return false</b>;
209     }
210   };  <i>// end of struct Hello</i>
211 </pre>
212
213 We declare a "<a href="#runOnFunction"><tt>runOnFunction</tt></a>" method, which
214 overloads an abstract virtual method inherited from <a
215 href="#FunctionPass"><tt>FunctionPass</tt></a>.  This is where we are supposed
216 to do our thing, so we just print out our message with the name of each
217 function.<p>
218
219 <pre>
220   RegisterOpt&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>");
221 }  <i>// end of anonymous namespace</i>
222 </pre><p>
223
224 Lastly, we register our class <tt>Hello</tt>, giving it a command line argument
225 "<tt>hello</tt>", and a name "<tt>Hello World Pass</tt>".  There are several
226 different ways of <a href="#registration">registering your pass</a>, depending
227 on what it is to be used for.  For "optimizations" we use the
228 <tt>RegisterOpt</tt> template.<p>
229
230 As a whole, the <tt>.cpp</tt> file looks like:<p>
231
232 <pre>
233 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Pass_8h-source.html">llvm/Pass.h</a>"
234 <b>#include</b> "<a href="http://llvm.cs.uiuc.edu/doxygen/Function_8h-source.html">llvm/Function.h</a>"
235
236 <b>namespace</b> {
237   <b>struct Hello</b> : <b>public</b> <a href="#FunctionPass">FunctionPass</a> {
238     <b>virtual bool</b> <a href="#runOnFunction">runOnFunction</a>(Function &F) {
239       std::cerr &lt;&lt; "<i>Hello: </i>" &lt;&lt; F.getName() &lt;&lt; "\n";
240       <b>return false</b>;
241     }
242   };
243   
244   RegisterOpt&lt;Hello&gt; X("<i>hello</i>", "<i>Hello World Pass</i>");
245 }
246 </pre><p>
247
248 Now that it's all together, compile the file with a simple "<tt>gmake</tt>"
249 command in the local directory and you should get a new
250 "<tt>lib/Debug/libhello.so</tt> file.  Note that everything in this file is
251 contained in an anonymous namespace: this reflects the fact that passes are self
252 contained units that do not need external interfaces (although they can have
253 them) to be useful.<p>
254
255
256 <!-- ======================================================================= -->
257 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
258 <tr><td>&nbsp;</td><td width="100%">&nbsp; 
259 <font color="#EEEEFF" face="Georgia,Palatino"><b>
260 <a name="running">Running a pass with <tt>opt</tt> or <tt>analyze</tt>
261 </b></font></td></tr></table><ul>
262
263 Now that you have a brand new shiny <tt>.so</tt> file, we can use the
264 <tt>opt</tt> command to run an LLVM program through your pass.  Because you
265 registered your pass with the <tt>RegisterOpt</tt> template, you will be able to
266 use the <tt>opt</tt> tool to access it, once loaded.<p>
267
268 To test it, follow the example at the end of the <a
269 href="GettingStarted.html">Getting Started Guide</a> to compile "Hello World" to
270 LLVM.  We can now run the bytecode file (<tt>hello.bc</tt>) for the program
271 through our transformation like this (or course, any bytecode file will
272 work):<p>
273
274 <pre>
275 $ opt -load ../../../lib/Debug/libhello.so -hello &lt; hello.bc &gt; /dev/null
276 Hello: __main
277 Hello: puts
278 Hello: main
279 </pre><p>
280
281 The '<tt>-load</tt>' option specifies that '<tt>opt</tt>' should load your pass
282 as a shared object, which makes '<tt>-hello</tt>' a valid command line argument
283 (which is one reason you need to <a href="#registration">register your
284 pass</a>).  Because the hello pass does not modify the program in any
285 interesting way, we just throw away the result of <tt>opt</tt> (sending it to
286 <tt>/dev/null</tt>).<p>
287
288 To see what happened to the other string you registered, try running
289 <tt>opt</tt> with the <tt>--help</tt> option:<p>
290
291 <pre>
292 $ opt -load ../../../lib/Debug/libhello.so --help
293 OVERVIEW: llvm .bc -&gt; .bc modular optimizer
294
295 USAGE: opt [options] &lt;input bytecode&gt;
296
297 OPTIONS:
298   Optimizations available:
299 ...
300     -funcresolve    - Resolve Functions
301     -gcse           - Global Common Subexpression Elimination
302     -globaldce      - Dead Global Elimination
303     <b>-hello          - Hello World Pass</b>
304     -indvars        - Cannonicalize Induction Variables
305     -inline         - Function Integration/Inlining
306     -instcombine    - Combine redundant instructions
307 ...
308 </pre><p>
309
310 The pass name get added as the information string for your pass, giving some
311 documentation to users of <tt>opt</tt>.  Now that you have a working pass, you
312 would go ahead and make it do the cool transformations you want.  Once you get
313 it all working and tested, it may become useful to find out how fast your pass
314 is.  The <a href="#passManager"><tt>PassManager</tt></a> provides a nice command
315 line option (<tt>--time-passes</tt>) that allows you to get information about
316 the execution time of your pass along with the other passes you queue up.  For
317 example:<p>
318
319 <pre>
320 $ opt -load ../../../lib/Debug/libhello.so -hello -time-passes &lt; hello.bc &gt; /dev/null
321 Hello: __main
322 Hello: puts
323 Hello: main
324 ===============================================================================
325                       ... Pass execution timing report ...
326 ===============================================================================
327   Total Execution Time: 0.02 seconds (0.0479059 wall clock)
328
329    ---User Time---   --System Time--   --User+System--   ---Wall Time---  --- Pass Name ---
330    0.0100 (100.0%)   0.0000 (  0.0%)   0.0100 ( 50.0%)   0.0402 ( 84.0%)  Bytecode Writer
331    0.0000 (  0.0%)   0.0100 (100.0%)   0.0100 ( 50.0%)   0.0031 (  6.4%)  Dominator Set Construction
332    0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0013 (  2.7%)  Module Verifier
333  <b>  0.0000 (  0.0%)   0.0000 (  0.0%)   0.0000 (  0.0%)   0.0033 (  6.9%)  Hello World Pass</b>
334    0.0100 (100.0%)   0.0100 (100.0%)   0.0200 (100.0%)   0.0479 (100.0%)  TOTAL
335 </pre><p>
336
337 As you can see, our implementation above is pretty fast :).  The additional
338 passes listed are automatically inserted by the '<tt>opt</tt>' tool to verify
339 that the LLVM emitted by your pass is still valid and well formed LLVM, which
340 hasn't been broken somehow.
341
342 Now that you have seen the basics of the mechanics behind passes, we can talk
343 about some more details of how they work and how to use them.<p>
344
345
346
347 <!-- *********************************************************************** -->
348 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
349 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
350 <a name="passtype">Pass classes and requirements
351 </b></font></td></tr></table><ul>
352 <!-- *********************************************************************** -->
353
354 One of the first things that you should do when designing a new pass is to
355 decide what class you should subclass for your pass.  The <a
356 href="#basiccode">Hello World</a> example uses the <tt><a
357 href="#FunctionPass">FunctionPass</a></tt> class for its implementation, but we
358 did not discuss why or when this should occur.  Here we talk about the classes
359 available, from the most general to the most specific.<p>
360
361 When choosing a superclass for your Pass, you should choose the <b>most
362 specific</b> class possible, while still being able to meet the requirements
363 listed.  This gives the LLVM Pass Infrastructure information neccesary to
364 optimize how passes are run, so that the resultant compiler isn't unneccesarily
365 slow.<p>
366
367
368
369 <!-- ======================================================================= -->
370 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
371 <tr><td>&nbsp;</td><td width="100%">&nbsp; 
372 <font color="#EEEEFF" face="Georgia,Palatino"><b>
373 <a name="Pass">The <tt>Pass</tt> class
374 </b></font></td></tr></table><ul>
375
376 The "<tt><a href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt>"
377 class is the most general of all superclasses that you can use.  Deriving from
378 <tt>Pass</tt> indicates that your pass uses the entire program as a unit,
379 refering to function bodies in no predictable order, or adding and removing
380 functions.  Because nothing is known about the behavior of direct <tt>Pass</tt>
381 subclasses, no optimization can be done for their execution.<p>
382
383 To write a correct <tt>Pass</tt> subclass, derive from <tt>Pass</tt> and
384 overload the <tt>run</tt> method with the following signature:<p>
385
386 <!-- _______________________________________________________________________ -->
387 </ul><h4><a name="run"><hr size=0>The <tt>run</tt> method</h4><ul>
388
389
390 <pre>
391   <b>virtual bool</b> run(Module &amp;M) = 0;
392 </pre><p>
393
394 The <tt>run</tt> method performs the interesting work of the pass, and should
395 return true if the module was modified by the transformation, false
396 otherwise.<p>
397
398
399
400 <!-- ======================================================================= -->
401 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
402 <tr><td>&nbsp;</td><td width="100%">&nbsp; 
403 <font color="#EEEEFF" face="Georgia,Palatino"><b>
404 <a name="FunctionPass">The <tt>FunctionPass</tt> class
405 </b></font></td></tr></table><ul>
406
407 In contrast to direct <tt>Pass</tt> subclasses, direct <tt><a
408 href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">FunctionPass</a></tt>
409 subclasses do have a predictable, local behavior that can be expected by the
410 system.  All <tt>FunctionPass</tt> execute on each function in the program
411 independant of all of the other functions in the program.
412 <tt>FunctionPass</tt>'s do not require that they are executed in a particular
413 order, and <tt>FunctionPass</tt>'s do not modify external functions.<p>
414
415 To be explicit, <tt>FunctionPass</tt> subclasses are not allowed to:<p>
416
417 <ol>
418 <li>Modify a Function other than the one currently being processed.
419 <li>Add or remove Function's from the current Module.
420 <li>Add or remove global variables from the current Module.
421 <li>Maintain state across invocations of
422     <a href="#runOnFunction"><tt>runOnFunction</tt></a> (including global data)
423 </ol><p>
424
425 Implementing a <tt>FunctionPass</tt> is usually straightforward (See the <a
426 href="#basiccode">Hello World</a> pass for example).  <tt>FunctionPass</tt>'s
427 may overload three virtual methods to do their work.  All of these methods
428 should return true if they modified the program, or false if they didn't.<p>
429
430 <!-- _______________________________________________________________________ -->
431 </ul><h4><a name="doInitialization_mod"><hr size=0>The
432 <tt>doInitialization(Module &amp;)</tt> method</h4><ul>
433
434 <pre>
435   <b>virtual bool</b> doInitialization(Module &amp;M);
436 </pre><p>
437
438 The <tt>doIninitialize</tt> method is allowed to do most of the things that
439 <tt>FunctionPass</tt>'s are not allowed to do.  They can add and remove
440 functions, get pointers to functions, etc.  The <tt>doInitialization</tt> method
441 is designed to do simple initialization type of stuff that does not depend on
442 the functions being processed.  The <tt>doInitialization</tt> method call is not
443 scheduled to overlap with any other pass executions (thus it should be very
444 fast).<p>
445
446 A good example of how this method should be used is the <a
447 href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations</a>
448 pass.  This pass converts <tt>malloc</tt> and <tt>free</tt> instructions into
449 platform dependant <tt>malloc()</tt> and <tt>free()</tt> function calls.  It
450 uses the <tt>doInitialization</tt> method to get a reference to the malloc and
451 free functions that it needs, adding prototypes to the module if neccesary.<p>
452
453 <!-- _______________________________________________________________________ -->
454 </ul><h4><a name="runOnFunction"><hr size=0>The <tt>runOnFunction</tt> method</h4><ul>
455
456 <pre>
457   <b>virtual bool</b> runOnFunction(Function &amp;F) = 0;
458 </pre><p>
459
460 The <tt>runOnFunction</tt> method must be implemented by your subclass to do the
461 transformation or analysis work of your pass.  As usual, a true value should be
462 returned if the function is modified.<p>
463
464 <!-- _______________________________________________________________________ -->
465 </ul><h4><a name="doFinalization_mod"><hr size=0>The <tt>doFinalization(Module &amp;)</tt> method</h4><ul>
466
467 <pre>
468   <b>virtual bool</b> doFinalization(Module &amp;M);
469 </pre</p>
470
471 The <tt>doFinalization</tt> method is an infrequently used method that is called
472 when the pass framework has finished calling <a
473 href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
474 program being compiled.<p>
475
476
477
478 <!-- ======================================================================= -->
479 </ul><table width="100%" bgcolor="#441188" border=0 cellpadding=4 cellspacing=0>
480 <tr><td>&nbsp;</td><td width="100%">&nbsp; 
481 <font color="#EEEEFF" face="Georgia,Palatino"><b>
482 <a name="BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
483 </b></font></td></tr></table><ul>
484
485 <tt>BasicBlockPass</tt>'s are just like <a
486 href="#FunctionPass"><tt>FunctionPass</tt></a>'s, except that they must limit
487 their scope of inspection and modification to a single basic block at a time.
488 As such, they are <b>not</b> allowed to do any of the following:<p>
489
490 <ol>
491 <li>Modify or inspect any basic blocks outside of the current one
492 <li>Maintain state across invocations of
493     <a href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a>
494 <li>Modify the constrol flow graph (by altering terminator instructions)
495 <li>Any of the things verboten for
496     <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s.
497 </ol><p>
498
499 <tt>BasicBlockPass</tt>'s are useful for traditional local and "peephole"
500 optimizations.  They may override the same <a
501 href="#doInitialization_mod"><tt>doInitialization(Module &amp;)</tt></a> and <a
502 href="#doFinalization_mod"><tt>doFinalization(Module &amp;)</tt></a> methods that <a
503 href="#FunctionPass"><tt>FunctionPass</tt></a>'s have, but also have the following virtual methods that may also be implemented:<p>
504
505 <!-- _______________________________________________________________________ -->
506 </ul><h4><a name="doInitialization_fn"><hr size=0>The
507 <tt>doInitialization(Function &amp;)</tt> method</h4><ul>
508
509 <pre>
510   <b>virtual bool</b> doInitialization(Function &amp;F);
511 </pre><p>
512
513 The <tt>doIninitialize</tt> method is allowed to do most of the things that
514 <tt>BasicBlockPass</tt>'s are not allowed to do, but that
515 <tt>FunctionPass</tt>'s can.  The <tt>doInitialization</tt> method is designed
516 to do simple initialization type of stuff that does not depend on the
517 BasicBlocks being processed.  The <tt>doInitialization</tt> method call is not
518 scheduled to overlap with any other pass executions (thus it should be very
519 fast).<p>
520
521
522 <!-- _______________________________________________________________________ -->
523 </ul><h4><a name="runOnBasicBlock"><hr size=0>The <tt>runOnBasicBlock</tt> method</h4><ul>
524
525 <pre>
526   <b>virtual bool</b> runOnBasicBlock(BasicBlock &amp;BB) = 0;
527 </pre><p>
528
529 Override this function to do the work of the <tt>BasicBlockPass</tt>.  This
530 function is not allowed to inspect or modify basic blocks other than the
531 parameter, and are not allowed to modify the CFG.  A true value must be returned
532 if the basic block is modified.<p>
533
534
535 <!-- _______________________________________________________________________ -->
536 </ul><h4><a name="doFinalization_fn"><hr size=0>The <tt>doFinalization(Function
537 &amp;)</tt> method</h4><ul>
538
539 <pre>
540   <b>virtual bool</b> doFinalization(Function &amp;F);
541 </pre</p>
542
543 The <tt>doFinalization</tt> method is an infrequently used method that is called
544 when the pass framework has finished calling <a
545 href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a> for every BasicBlock in the
546 program being compiled.  This can be used to perform per-function
547 finalization.<p>
548
549
550
551 <!-- *********************************************************************** -->
552 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
553 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
554 <a name="registration">Pass registration
555 </b></font></td></tr></table><ul>
556 <!-- *********************************************************************** -->
557
558 In the <a href="#basiccode">Hello World</a> example pass we illustrated how pass
559 registration works, and discussed some of the reasons that it is used and what
560 it does.  Here we discuss how and why passes are registered.<p>
561
562 Passes can be registered in several different ways.  Depending on the general
563 classification of the pass, you should use one of the following templates to
564 register the pass:<p>
565
566 <ul>
567 <li><b><tt>RegisterOpt</tt></b> - This template should be used when you are
568 registering a pass that logically should be available for use in the
569 '<tt>opt</tt>' utility.<p>
570
571 <li><b><tt>RegisterAnalysis</tt></b> - This template should be used when you are
572 registering a pass that logically should be available for use in the
573 '<tt>analysis</tt>' utility.<p>
574
575 <li><b><tt>RegisterLLC</tt></b> - This template should be used when you are
576 registering a pass that logically should be available for use in the
577 '<tt>llc</tt>' utility.<p>
578
579 <li><b><tt>RegisterPass</tt></b> - This is the generic form of the
580 <tt>Register*</tt> templates that should be used if you want your pass listed by
581 multiple or no utilities.  This template takes an extra third argument that
582 specifies which tools it should be listed in.  See the <a
583 href="http://llvm.cs.uiuc.edu/doxygen/PassSupport_8h-source.html">PassSupport.h</a>
584 file for more information.<p>
585 </ul><p>
586
587 Regardless of how you register your pass, you must specify at least two
588 parameters.  The first parameter is the name of the pass that is to be used on
589 the command line to specify that the pass should be added to a program (for
590 example <tt>opt</tt> or <tt>analyze</tt>).  The second argument is the name of
591 the pass, which is to be used for the <tt>--help</tt> output of programs, as
592 well as for debug output generated by the <tt>--debug-pass</tt> option.<p>
593
594 If you pass is constructed by its default constructor, you only ever have to
595 pass these two arguments.  If, on the other hand, you require other information
596 (like target specific information), you must pass an additional argument.  This
597 argument is a pointer to a function used to create the pass.  For an example of
598 how this works, look at the <a
599 href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations.cpp</a>
600 file.<p>
601
602 If a pass is registered to be used by the <tt>analyze</tt> utility, you should
603 implement the virtual <tt>print</tt> method:<p>
604
605 <!-- _______________________________________________________________________ -->
606 </ul><h4><a name="print"><hr size=0>The <tt>print</tt> method</h4><ul>
607
608 <pre>
609   <b>virtual void</b> print(std::ostream &amp;O, <b>const</b> Module *M) <b>const</b>;
610 </pre><p>
611
612 The <tt>print</tt> method must be implemented by "analyses" in order to print a
613 human readable version of the analysis results.  This is useful for debugging an
614 analysis itself, as well as for other people to figure out how an analysis
615 works.  The <tt>analyze</tt> tool uses this method to generate its output.<p>
616
617 The <tt>ostream</tt> parameter specifies the stream to write the results on, and
618 the <tt>Module</tt> parameter gives a pointer to the top level module of the
619 program that has been analyzed.  Note however that this pointer may be null in
620 certain circumstances (such as calling the <tt>Pass::dump()</tt> from a
621 debugger), so it should only be used to enhance debug output, it should not be
622 depended on.<p>
623
624
625 <!-- *********************************************************************** -->
626 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
627 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
628 <a name="interaction">Specifying interactions between passes
629 </b></font></td></tr></table><ul>
630 <!-- *********************************************************************** -->
631
632 One of the main responsibilities of the <tt>PassManager</tt> is the make sure
633 that passes interact with each other correctly.  Because <tt>PassManager</tt>
634 tries to <a href="#passmanager">optimize the execution of passes</a> it must
635 know how the passes interact with each other and what dependencies exist between
636 the various passes.  To track this, each pass can declare the set of passes that
637 are required to be executed before the current pass, and the passes which are
638 invalidated by the current pass.<p>
639
640 Typically this functionality is used to require that analysis results are
641 computed before your pass is run.  Running arbitrary transformation passes can
642 invalidate the computed analysis results, which is what the invalidation set
643 specifies.  If a pass does not implement the <tt><a
644 href="#getAnalysisUsage">getAnalysisUsage</a></tt> method, it defaults to not
645 having any prerequisite passes, and invalidating <b>all</b> other passes.<p>
646
647
648 <!-- _______________________________________________________________________ -->
649 </ul><h4><a name="getAnalysisUsage"><hr size=0>The <tt>getAnalysisUsage</tt> method</h4><ul>
650
651 <pre>
652   <b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;Info) <b>const</b>;
653 </pre><p>
654
655 By implementing the <tt>getAnalysisUsage</tt> method, the required and
656 invalidated sets may be specified for your transformation.  The implementation
657 should fill in the <tt><a
658 href="http://llvm.cs.uiuc.edu/doxygen/classAnalysisUsage.html">AnalysisUsage</a></tt>
659 object with information about which passes are required and not invalidated.  To do this, the following set methods are provided by the <tt><a
660 href="http://llvm.cs.uiuc.edu/doxygen/classAnalysisUsage.html">AnalysisUsage</a></tt> class:<p>
661
662 <pre>
663   <i>// addRequires - Add the specified pass to the required set for your pass.</i>
664   <b>template</b>&lt;<b>class</b> PassClass&gt;
665   AnalysisUsage &amp;AnalysisUsage::addRequired();
666
667   <i>// addPreserved - Add the specified pass to the set of analyses preserved by
668   // this pass</i>
669   <b>template</b>&lt;<b>class</b> PassClass&gt;
670   AnalysisUsage &amp;AnalysisUsage::addPreserved();
671
672   <i>// setPreservesAll - Call this if the pass does not modify its input at all</i>
673   <b>void</b> AnalysisUsage::setPreservesAll();
674
675   <i>// preservesCFG - This function should be called by the pass, iff they do not:
676   //
677   //  1. Add or remove basic blocks from the function
678   //  2. Modify terminator instructions in any way.
679   //
680   //  This is automatically implied for <a href="#BasicBlockPass">BasicBlockPass</a>'s
681   //</i>
682   <b>void</b> AnalysisUsage::preservesCFG();
683 </pre><p>
684
685 Some examples of how to use these methods are:<p>
686
687 <pre>
688   <i>// This is an example implementation from an analysis, which does not modify
689   // the program at all, yet has a prerequisite.</i>
690   <b>void</b> <a href="http://llvm.cs.uiuc.edu/doxygen/structPostDominanceFrontier.html">PostDominanceFrontier</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
691     AU.setPreservesAll();
692     AU.addRequired&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structPostDominatorTree.html">PostDominatorTree</a>&gt;();
693   }
694 </pre><p>
695
696 and:<p>
697
698 <pre>
699   <i>// This example modifies the program, but does not modify the CFG</i>
700   <b>void</b> <a href="http://llvm.cs.uiuc.edu/doxygen/structLICM.html">LICM</a>::getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
701     AU.preservesCFG();
702     AU.addRequired&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/classLoopInfo.html">LoopInfo</a>&gt;();
703   }
704 </pre><p>
705
706 <!-- _______________________________________________________________________ -->
707 </ul><h4><a name="getAnalysis"><hr size=0>The <tt>getAnalysis&lt;&gt;</tt> method</h4><ul>
708
709 The <tt>Pass::getAnalysis&lt;&gt;</tt> method is inherited by your class,
710 providing you with access to the passes that you declared that you required with
711 the <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method.  It takes
712 a single template argument that specifies which pass class you want, and returns
713 a reference to that pass.<p>
714
715 <pre>
716   <b>template</b>&lt;<b>typename</b> PassClass&gt;
717   AnalysisType &amp;getAnalysis();
718 </pre><p>
719
720 This method call returns a reference to the pass desired.  You may get a runtime
721 assertion failure if you attempt to get an analysis that you did not declare as
722 required in your <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a>
723 implementation.  This method can be called by your <tt>run*</tt> method
724 implementation, or by any other local method invoked by your <tt>run*</tt>
725 method.<p>
726
727 <!-- *********************************************************************** -->
728 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
729 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
730 <a name="analysisgroup">Implementing Analysis Groups
731 </b></font></td></tr></table><ul>
732 <!-- *********************************************************************** -->
733
734 Now that we understand the basics of how passes are defined, how the are used,
735 and how they are required from other passes, it's time to get a little bit
736 fancier.  All of the pass relationships that we have seen so far are very
737 simple: one pass depends on one other specific pass to be run before it can run.
738 For many applications, this is great, for others, more flexibility is
739 required.<p>
740
741 In particular, some analyses are defined such that there is a single simple
742 interface to the analysis results, but multiple ways of calculating them.
743 Consider alias analysis for example.  The most trivial alias analysis returns
744 "may alias" for any alias query.  The most sophisticated analysis a
745 flow-sensitive, context-sensitive interprocedural analysis that can take a
746 significant amount of time to execute (and obviously, there is a lot of room
747 between these two extremes for other implementations).  To cleanly support
748 situations like this, the LLVM Pass Infrastructure supports the notion of
749 Analysis Groups.<p>
750
751 <!-- _______________________________________________________________________ -->
752 </ul><h4><a name="agconcepts"><hr size=0>Analysis Group Concepts</h4><ul>
753
754 An Analysis Group is a single simple interface that may be implemented by
755 multiple different passes.  Analysis Groups can be given human readable names
756 just like passes, but unlike passes, they need not derive from the <tt>Pass</tt>
757 class.  An analysis group may have one or more implementations, one of which is
758 the "default" implementation.<p>
759
760 Analysis groups are used by client passes just like other passes are: the
761 <tt>AnalysisUsage::addRequired()</tt> and <tt>Pass::getAnalysis()</tt> methods.
762 In order to resolve this requirement, the <a href="#passmanager">PassManager</a>
763 scans the available passes to see if any implementations of the analysis group
764 are available.  If none is available, the default implementation is created for
765 the pass to use.  All standard rules for <A href="#interaction">interaction
766 between passes</a> still apply.<p>
767
768 Although <a href="#registration">Pass Registration</a> is optional for normal
769 passes, all analysis group implementations must be registered, and must use the
770 <A href="#registerag"><tt>RegisterAnalysisGroup</tt></a> template to join the
771 implementation pool.  Also, a default implementation of the interface
772 <b>must</b> be registered with <A
773 href="#registerag"><tt>RegisterAnalysisGroup</tt></a>.<p>
774
775 As a concrete example of an Analysis Group in action, consider the <a
776 href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>
777 analysis group.  The default implementation of the alias analysis interface (the
778 <tt><a
779 href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">basicaa</a></tt>
780 pass) just does a few simple checks that don't require significant analysis to
781 compute (such as: two different globals can never alias each other, etc).
782 Passes that use the <tt><a
783 href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a></tt>
784 interface (for example the <tt><a
785 href="http://llvm.cs.uiuc.edu/doxygen/classGCSE.html">gcse</a></tt> pass), do not care which implementation
786 of alias analysis is actually provided, they just use the designated
787 interface.<p>
788
789 From the user's perspective, commands work just like normal.  Issuing the
790 command '<tt>opt -gcse ...</tt>' will cause the <tt>basicaa</tt> class to be
791 instantiated and added to the pass sequence.  Issuing the command '<tt>opt
792 -somefancyaa -gcse ...</tt>' will cause the <tt>gcse</tt> pass to use the
793 <tt>somefancyaa</tt> alias analysis (which doesn't actually exist, it's just a
794 hypothetical example) instead.<p>
795
796
797 <!-- _______________________________________________________________________ -->
798 </ul><h4><a name="registerag"><hr size=0>Using <tt>RegisterAnalysisGroup</tt></h4><ul>
799
800 The <tt>RegisterAnalysisGroup</tt> template is used to register the analysis
801 group itself as well as add pass implementations to the analysis group.  First,
802 an analysis should be registered, with a human readable name provided for it.
803 Unlike registration of passes, there is no command line argument to be specified
804 for the Analysis Group Interface itself, because it is "abstract":<p>
805
806 <pre>
807   <b>static</b> RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>&gt; A("<i>Alias Analysis</i>");
808 </pre><p>
809
810 Once the analysis is registered, passes can declare that they are valid
811 implementations of the interface by using the following code:<p>
812
813 <pre>
814 <b>namespace</b> {
815   //<i> Analysis Group implementations <b>must</b> be registered normally...</i>
816   RegisterOpt&lt;FancyAA&gt;
817   B("<i>somefancyaa</i>", "<i>A more complex alias analysis implementation</i>");
818
819   //<i> Declare that we implement the AliasAnalysis interface</i>
820   RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>, FancyAA&gt; C;
821 }
822 </pre><p>
823
824 This just shows a class <tt>FancyAA</tt> that is registered normally, then uses
825 the <tt>RegisterAnalysisGroup</tt> template to "join" the <tt><a
826 href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a></tt>
827 analysis group.  Every implementation of an analysis group should join using
828 this template.  A single pass may join multiple different analysis groups with
829 no problem.<p>
830
831 <pre>
832 <b>namespace</b> {
833   //<i> Analysis Group implementations <b>must</b> be registered normally...</i>
834   RegisterOpt&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a>&gt;
835   D("<i>basicaa</i>", "<i>Basic Alias Analysis (default AA impl)</i>");
836
837   //<i> Declare that we implement the AliasAnalysis interface</i>
838   RegisterAnalysisGroup&lt;<a href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>, <a href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a>, <b>true</b>&gt; E;
839 }
840 </pre><p>
841
842 Here we show how the default implementation is specified (using the extra
843 argument to the <tt>RegisterAnalysisGroup</tt> template).  There must be exactly
844 one default implementation available at all times for an Analysis Group to be
845 used.  Here we declare that the <tt><a
846 href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a></tt>
847 pass is the default implementation for the interface.<p>
848
849
850 <!-- *********************************************************************** -->
851 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
852 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
853 <a name="passmanager">What PassManager does
854 </b></font></td></tr></table><ul>
855 <!-- *********************************************************************** -->
856
857 The <a
858 href="http://llvm.cs.uiuc.edu/doxygen/PassManager_8h-source.html"><tt>PassManager</tt></a>
859 <a href="http://llvm.cs.uiuc.edu/doxygen/classPassManager.html">class</a> takes
860 a list of passes, ensures their <a href="#interaction">prerequisites</a> are set
861 up correctly, and then schedules passes to run efficiently.  All of the LLVM
862 tools that run passes use the <tt>PassManager</tt> for execution of these
863 passes.<p>
864
865 The <tt>PassManager</tt> does two main things to try to reduce the execution
866 time of a series of passes:<p>
867
868 <ol>
869 <li><b>Share analysis results</b> - The PassManager attempts to avoid
870 recomputing analysis results as much as possible.  This means keeping track of
871 which analyses are available already, which analyses get invalidated, and which
872 analyses are needed to be run for a pass.  An important part of work is that the
873 <tt>PassManager</tt> tracks the exact lifetime of all analysis results, allowing
874 it to <a href="#releaseMemory">free memory</a> allocated to holding analysis
875 results as soon as they are no longer needed.<p>
876
877 <li><b>Pipeline the execution of passes on the program</b> - The
878 <tt>PassManager</tt> attempts to get better cache and memory usage behavior out
879 of a series of passes by pipelining the passes together.  This means that, given
880 a series of consequtive <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s, it
881 will execute all of the <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s on
882 the first function, then all of the <a
883 href="#FunctionPass"><tt>FunctionPass</tt></a>'s on the second function,
884 etc... until the entire program has been run through the passes.<p>
885
886 This improves the cache behavior of the compiler, because it is only touching
887 the LLVM program representation for a single function at a time, instead of
888 traversing the entire program.  It reduces the memory consumption of compiler,
889 because, for example, only one <a
890 href="http://llvm.cs.uiuc.edu/doxygen/structDominatorSet.html"><tt>DominatorSet</tt></a>
891 needs to be calculated at a time.  This also makes it possible some <a
892 href="#SMP">interesting enhancements</a> in the future.<p>
893
894 </ol><p>
895
896 The effectiveness of the <tt>PassManager</tt> is influenced directly by how much
897 information it has about the behaviors of the passes it is scheduling.  For
898 example, the "preserved" set is intentionally conservative in the face of an
899 unimplemented <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method.
900 Not implementing when it should be implemented will have the effect of not
901 allowing any analysis results to live across the execution of your pass.<p>
902
903 The <tt>PassManager</tt> class exposes a <tt>--debug-pass</tt> command line
904 options that is useful for debugging pass execution, seeing how things work, and
905 diagnosing when you should be preserving more analyses than you currently are
906 (To get information about all of the variants of the <tt>--debug-pass</tt>
907 option, just type '<tt>opt --help-hidden</tt>').<p>
908
909 By using the <tt>--debug-pass=Structure</tt> option, for example, we can see how
910 our <a href="#basiccode">Hello World</a> pass interacts with other passes.  Lets
911 try it out with the <tt>gcse</tt> and <tt>licm</tt> passes:<p>
912
913 <pre>
914 $ opt -load ../../../lib/Debug/libhello.so -gcse -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
915 Module Pass Manager
916   Function Pass Manager
917     Dominator Set Construction
918     Immediate Dominators Construction
919     Global Common Subexpression Elimination
920 --  Immediate Dominators Construction
921 --  Global Common Subexpression Elimination
922     Natural Loop Construction
923     Loop Invariant Code Motion
924 --  Natural Loop Construction
925 --  Loop Invariant Code Motion
926     Module Verifier
927 --  Dominator Set Construction
928 --  Module Verifier
929   Bytecode Writer
930 --Bytecode Writer
931 </pre><p>
932
933 This output shows us when passes are constructed and when the analysis results
934 are known to be dead (prefixed with '<tt>--</tt>').  Here we see that GCSE uses
935 dominator and immediate dominator information to do its job.  The LICM pass uses
936 natural loop information, which uses dominator sets, but not immediate
937 dominators.  Because immediate dominators are no longer useful after the GCSE
938 pass, it is immediately destroyed.  The dominator sets are then reused to
939 compute natural loop information, which is then used by the LICM pass.<p>
940
941 After the LICM pass, the module verifier runs (which is automatically added by
942 the '<tt>opt</tt>' tool), which uses the dominator set to check that the
943 resultant LLVM code is well formed.  After it finishes, the dominator set
944 information is destroyed, after being computed once, and shared by three
945 passes.<p>
946
947 Lets see how this changes when we run the <a href="#basiccode">Hello World</a>
948 pass in between the two passes:<p>
949
950 <pre>
951 $ opt -load ../../../lib/Debug/libhello.so -gcse -hello -licm --debug-pass=Structure &lt; hello.bc &gt; /dev/null
952 Module Pass Manager
953   Function Pass Manager
954     Dominator Set Construction
955     Immediate Dominators Construction
956     Global Common Subexpression Elimination
957 <b>--  Dominator Set Construction</b>
958 --  Immediate Dominators Construction
959 --  Global Common Subexpression Elimination
960 <b>    Hello World Pass
961 --  Hello World Pass
962     Dominator Set Construction</b>
963     Natural Loop Construction
964     Loop Invariant Code Motion
965 --  Natural Loop Construction
966 --  Loop Invariant Code Motion
967     Module Verifier
968 --  Dominator Set Construction
969 --  Module Verifier
970   Bytecode Writer
971 --Bytecode Writer
972 Hello: __main
973 Hello: puts
974 Hello: main
975 </pre><p>
976
977 Here we see that the <a href="#basiccode">Hello World</a> pass has killed the
978 Dominator Set pass, even though it doesn't modify the code at all!  To fix this,
979 we need to add the following <a
980 href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method to our pass:<p>
981
982 <pre>
983     <i>// We don't modify the program, so we preserve all analyses</i>
984     <b>virtual void</b> getAnalysisUsage(AnalysisUsage &amp;AU) <b>const</b> {
985       AU.setPreservesAll();
986     }
987 </pre><p>
988
989 Now when we run our pass, we get this output:<p>
990
991 <pre>
992 $ opt -load ../../../lib/Debug/libhello.so -gcse -hello -licm --debug-pass=Structure < hello.bc > /dev/null
993 Pass Arguments:  -gcse -hello -licm
994 Module Pass Manager
995   Function Pass Manager
996     Dominator Set Construction
997     Immediate Dominators Construction
998     Global Common Subexpression Elimination
999 --  Immediate Dominators Construction
1000 --  Global Common Subexpression Elimination
1001     Hello World Pass
1002 --  Hello World Pass
1003     Natural Loop Construction
1004     Loop Invariant Code Motion
1005 --  Loop Invariant Code Motion
1006 --  Natural Loop Construction
1007     Module Verifier
1008 --  Dominator Set Construction
1009 --  Module Verifier
1010   Bytecode Writer
1011 --Bytecode Writer
1012 Hello: __main
1013 Hello: puts
1014 Hello: main
1015 </pre><p>
1016
1017 Which shows that we don't accidentally invalidate dominator information
1018 anymore, and therefore do not have to compute it twice.<p>
1019
1020
1021 <!-- _______________________________________________________________________ -->
1022 </ul><h4><a name="releaseMemory"><hr size=0>The <tt>releaseMemory</tt> method</h4><ul>
1023
1024 <pre>
1025   <b>virtual void</b> releaseMemory();
1026 </pre><p>
1027
1028 The <tt>PassManager</tt> automatically determines when to compute analysis
1029 results, and how long to keep them around for.  Because the lifetime of the pass
1030 object itself is effectively the entire duration of the compilation process, we
1031 need some way to free analysis results when they are no longer useful.  The
1032 <tt>releaseMemory</tt> virtual method is the way to do this.<p>
1033
1034 If you are writing an analysis or any other pass that retains a significant
1035 amount of state (for use by another pass which "requires" your pass and uses the
1036 <a href="#getAnalysis">getAnalysis</a> method) you should implement
1037 <tt>releaseMEmory</tt> to, well, release the memory allocated to maintain this
1038 internal state.  This method is called after the <tt>run*</tt> method for the
1039 class, before the next call of <tt>run*</tt> in your pass.<p>
1040
1041
1042 <!-- *********************************************************************** -->
1043 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
1044 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
1045 <a name="debughints">Using GDB with dynamically loaded passes
1046 </b></font></td></tr></table><ul>
1047 <!-- *********************************************************************** -->
1048
1049 Unfortunately, using GDB with dynamically loaded passes is not as easy as it
1050 should be.  First of all, you can't set a breakpoint in a shared object that has
1051 not been loaded yet, and second of all there are problems with inlined functions
1052 in shared objects.  Here are some suggestions to debugging your pass with
1053 GDB.<p>
1054
1055 For sake of discussion, I'm going to assume that you are debugging a
1056 transformation invoked by <tt>opt</tt>, although nothing described here depends
1057 on that.<p>
1058
1059 <!-- _______________________________________________________________________ -->
1060 </ul><h4><a name="breakpoint"><hr size=0>Setting a breakpoint in your pass</h4><ul>
1061
1062 First thing you do is start <tt>gdb</tt> on the <tt>opt</tt> process:<p>
1063
1064 <pre>
1065 $ <b>gdb opt</b>
1066 GNU gdb 5.0
1067 Copyright 2000 Free Software Foundation, Inc.
1068 GDB is free software, covered by the GNU General Public License, and you are
1069 welcome to change it and/or distribute copies of it under certain conditions.
1070 Type "show copying" to see the conditions.
1071 There is absolutely no warranty for GDB.  Type "show warranty" for details.
1072 This GDB was configured as "sparc-sun-solaris2.6"...
1073 (gdb)
1074 </pre><p>
1075
1076 Note that <tt>opt</tt> has a lot of debugging information in it, so it takes
1077 time to load.  Be patient.  Since we cannot set a breakpoint in our pass yet
1078 (the shared object isn't loaded until runtime), we must execute the process, and
1079 have it stop before it invokes our pass, but after it has loaded the shared
1080 object.  The most foolproof way of doing this is to set a breakpoint in
1081 <tt>PassManager::run</tt> and then run the process with the arguments you
1082 want:<p>
1083
1084 <pre>
1085 (gdb) <b>break PassManager::run</b>
1086 Breakpoint 1 at 0x2413bc: file Pass.cpp, line 70.
1087 (gdb) <b>run test.bc -load /shared/lattner/cvs/llvm/lib/Debug/[libname].so -[passoption]</b>
1088 Starting program: /shared/lattner/cvs/llvm/tools/Debug/opt test.bc 
1089     -load /shared/lattner/cvs/llvm/lib/Debug/[libname].so -[passoption]
1090 Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
1091 70      bool PassManager::run(Module &amp;M) { return PM-&gt;run(M); }
1092 (gdb)
1093 </pre></p>
1094
1095 Once the <tt>opt</tt> stops in the <tt>PassManager::run</tt> method you are now
1096 free to set breakpoints in your pass so that you can trace through execution or
1097 do other standard debugging stuff.<p>
1098
1099
1100 <!-- _______________________________________________________________________ -->
1101 </ul><h4><a name="debugmisc"><hr size=0>Miscellaneous Problems</h4><ul>
1102
1103 Once you have the basics down, there are a couple of problems that GDB has, some
1104 with solutions, some without.<p>
1105
1106 <ul>
1107 <li>Inline functions have bogus stack information.  In general, GDB does a
1108 pretty good job getting stack traces and stepping through inline functions.
1109 When a pass is dynamically loaded however, it somehow completely loses this
1110 capability.  The only solution I know of is to de-inline a function (move it
1111 from the body of a class to a .cpp file).<p>
1112
1113 <li>Restarting the program breaks breakpoints.  After following the information
1114 above, you have succeeded in getting some breakpoints planted in your pass.  Nex
1115 thing you know, you restart the program (i.e., you type '<tt>run</tt>' again),
1116 and you start getting errors about breakpoints being unsettable.  The only way I
1117 have found to "fix" this problem is to <tt>delete</tt> the breakpoints that are
1118 already set in your pass, run the program, and re-set the breakpoints once
1119 execution stops in <tt>PassManager::run</tt>.<p>
1120
1121 </ul>
1122
1123 Hopefully these tips will help with common case debugging situations.  If you'd
1124 like to contribute some tips of your own, just contact <a
1125 href="mailto:sabre@nondot.org">Chris</a>.<p>
1126
1127
1128 <!-- *********************************************************************** -->
1129 </ul><table width="100%" bgcolor="#330077" border=0 cellpadding=4 cellspacing=0>
1130 <tr><td align=center><font color="#EEEEFF" size=+2 face="Georgia,Palatino"><b>
1131 <a name="future">Future extensions planned
1132 </b></font></td></tr></table><ul>
1133 <!-- *********************************************************************** -->
1134
1135 Although the LLVM Pass Infrastructure is very capable as it stands, and does
1136 some nifty stuff, there are things we'd like to add in the future.  Here is
1137 where we are going:<p>
1138
1139 <!-- _______________________________________________________________________ -->
1140 </ul><h4><a name="SMP"><hr size=0>Multithreaded LLVM</h4><ul>
1141
1142 Multiple CPU machines are becoming more command and compilation can never be
1143 fast enough: obviously we should allow for a multithreaded compiler.  Because of
1144 the semantics defined for passes above (specifically they cannot maintain state
1145 across invocations of their <tt>run*</tt> methods), a nice clean way to
1146 implement a multithreaded compiler would be for the <tt>PassManager</tt> class
1147 to create multiple instances of each pass object, and allow the seperate
1148 instances to be hacking on different parts of the program at the same time.<p>
1149
1150 This implementation would prevent each of the passes from having to implement
1151 multithreaded constructs, requiring only the LLVM core to have locking in a few
1152 places (for global resources).  Although this is a simple extension, we simply
1153 haven't had time (or multiprocessor machines, thus a reason) to implement this.
1154 Despite that, we have kept the LLVM passes SMP ready, and you should too.<p>
1155
1156
1157 <!-- _______________________________________________________________________ -->
1158 </ul><h4><a name="ModuleSource"><hr size=0>A new <tt>ModuleSource</tt> interface</h4><ul>
1159
1160 Currently, the <tt>PassManager</tt>'s <tt>run</tt> method takes a <tt><a
1161 href="http://llvm.cs.uiuc.edu/doxygen/classModule.html">Module</a></tt> as
1162 input, and runs all of the passes on this module.  The problem with this
1163 approach is that none of the <tt>PassManager</tt> features can be used for
1164 timing and debugging the actual <b>loading</b> of the module from disk or
1165 standard input.<p>
1166
1167 To solve this problem, eventually the <tt>PassManger</tt> class will accept a
1168 <tt>ModuleSource</tt> object instead of a Module itself.  When complete, this
1169 will also allow for streaming of functions out of the bytecode representation,
1170 allowing us to avoid holding the entire program in memory at once if we only are
1171 dealing with <a href="#FunctionPass">FunctionPass</a>'s.<p>
1172
1173 As part of a different issue, eventually the bytecode loader will be extended to
1174 allow on-demand loading of functions from the bytecode representation, in order
1175 to better support the runtime reoptimizer.  The bytecode format is already
1176 capable of this, the loader just needs to be reworked a bit.<p>
1177
1178
1179 <!-- _______________________________________________________________________ -->
1180 </ul><h4><a name="PassFunctionPass"><hr size=0><tt>Pass</tt>'s requiring <tt>FunctionPass</tt>'s</h4><ul>
1181
1182 Currently it is illegal for a <a href="#Pass"><tt>Pass</tt></a> to require a <a
1183 href="#FunctionPass"><tt>FunctionPass</tt></a>.  This is because there is only
1184 one instance of the <a href="#FunctionPass"><tt>FunctionPass</tt></a> object
1185 ever created, thus nowhere to store information for all of the functions in the
1186 program at the same time.  Although this has come up a couple of times before,
1187 this has always been worked around by factoring one big complicated pass into a
1188 global and an interprocedural part, both of which are distinct.  In the future,
1189 it would be nice to have this though.<p>
1190
1191 Note that it is no problem for a <a
1192 href="#FunctionPass"><tt>FunctionPass</tt></a> to require the results of a <a
1193 href="#Pass"><tt>Pass</tt></a>, only the other way around.<p>
1194
1195
1196 <!-- *********************************************************************** -->
1197 </ul>
1198 <!-- *********************************************************************** -->
1199
1200 <hr><font size-1>
1201 <address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
1202 <!-- Created: Tue Aug  6 15:00:33 CDT 2002 -->
1203 <!-- hhmts start -->
1204 Last modified: Mon Sep 16 17:37:27 CDT 2002
1205 <!-- hhmts end -->
1206 </font></body></html>