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