blob: 7d81c81c0afd826ba08c3564e1aa77480e0d713b [file] [log] [blame]
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
2<html><head><title>Writing an LLVM Pass</title></head>
3
Chris Lattnerc6bb8242002-08-08 20:11:18 +00004<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>
Chris Lattnerd0713f92002-09-12 17:06:43 +000028 <li><a href="#doInitialization_mod">The <tt>doInitialization(Module
29 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000030 <li><a href="#runOnFunction">The <tt>runOnFunction</tt> method</a>
Chris Lattnerd0713f92002-09-12 17:06:43 +000031 <li><a href="#doFinalization_mod">The <tt>doFinalization(Module
32 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000033 </ul>
34 <li><a href="#BasicBlockPass">The <tt>BasicBlockPass</tt> class</a>
35 <ul>
Chris Lattnerd0713f92002-09-12 17:06:43 +000036 <li><a href="#doInitialization_fn">The <tt>doInitialization(Function
37 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000038 <li><a href="#runOnBasicBlock">The <tt>runOnBasicBlock</tt> method</a>
Chris Lattnerd0713f92002-09-12 17:06:43 +000039 <li><a href="#doFinalization_fn">The <tt>doFinalization(Function
40 &amp;)</tt> method</a>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000041 </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>
Chris Lattner79910702002-08-22 19:21:04 +000052 <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>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000057 <li><a href="#passmanager">What PassManager does</a>
58 <ul>
59 <li><a href="#releaseMemory">The <tt>releaseMemory</tt> method</a>
60 </ul>
Chris Lattner480e2ef2002-09-06 02:02:58 +000061 <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>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000066 <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>
Chris Lattner38c633d2002-08-08 20:23:41 +000072
73 <p><b>Written by <a href="mailto:sabre@nondot.org">Chris Lattner</a></b><p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +000074</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
85The LLVM Pass Framework is an important part of the LLVM system, because LLVM
86passes are where the interesting parts of the compiler exist. Passes perform
87the transformations and optimizations that make up the compiler, they build
88the analysis results that are used by these transformations, and they are, above
89all, a structuring technique for compiler code.<p>
90
91All LLVM passes are subclasses of the <tt><a
92href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt> class, which
93implement functionality by overriding virtual methods inherited from
94<tt>Pass</tt>. Depending on how your pass works, you may be able to inherit
95from the <tt><a
96href="http://llvm.cs.uiuc.edu/doxygen/structFunctionPass.html">FunctionPass</a></tt>
97or <tt><a
98href="http://llvm.cs.uiuc.edu/doxygen/structBasicBlockPass.html">BasicBlockPass</a></tt>,
99which gives the system more information about what your pass does, and how it
100can be combined with other passes. One of the main features of the LLVM Pass
101Framework is that it schedules passes to run in an efficient way based on the
102constraints that your pass has.<p>
103
104We start by showing you how to construct a pass, everything from setting up the
105code, to compiling, loading, and executing it. After the basics are down, more
106advanced 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
116Here we describe how to write the "hello world" of passes. The "Hello" pass is
117designed to simply print out the name of non-external functions that exist in
118the program being compiled. It does not modify the program at all, just
119inspects it. The source code and files for this pass are available in the LLVM
120source 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
130First thing you need to do is create a new directory somewhere in the LLVM
131source 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
133script (Makefile) that will compile the source code for the new pass. To do
Chris Lattnerfd214762002-09-16 22:37:56 +0000134this, copy this into "<tt>Makefile</tt>":<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000135
136</ul><hr><ul><pre>
137# Makefile for hello pass
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000138
Chris Lattner17a4c3e2002-08-14 20:06:13 +0000139# Path to top level of LLVM heirarchy
Chris Lattner7ce83e52002-08-14 20:07:01 +0000140LEVEL = ../../..
Chris Lattner17a4c3e2002-08-14 20:06:13 +0000141
142# Name of the library to build
Chris Lattner7ce83e52002-08-14 20:07:01 +0000143LIBRARYNAME = hello
Chris Lattner17a4c3e2002-08-14 20:06:13 +0000144
145# Build a dynamically loadable shared object
146SHARED_LIBRARY = 1
147
148# Include the makefile implementation stuff
149include $(LEVEL)/Makefile.common
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000150</pre></ul><hr><ul><p>
151
152This makefile specifies that all of the <tt>.cpp</tt> files in the current
153directory are to be compiled and linked together into a
154<tt>lib/Debug/libhello.so</tt> shared object that can be dynamically loaded by
155the <tt>opt</tt> or <tt>analyze</tt> tools.<p>
156
157Now that we have the build scripts set up, we just need to write the code for
158the 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
168Now that we have a way to compile our new pass, we just have to write it. Start
169out 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
176Which are needed because we are writing a <tt><a
177href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt>, and we are
178operating on <tt><a
179href="http://llvm.cs.uiuc.edu/doxygen/classFunction.html">Function</a></tt>'s.<p>
180
181Next 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++
188what the "<tt>static</tt>" keyword is to C (at global scope). It makes the
189things declared inside of the anonymous namespace only visible to the current
190file. If you're not familiar with them, consult a decent C++ book for more
191information.<p>
192
193Next, 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
199This declares a "<tt>Hello</tt>" class that is a subclass of <tt><a
200href="http://llvm.cs.uiuc.edu/doxygen/structFunctionPass.html">FunctionPass</a></tt>.
Chris Lattnerd6ea9262002-09-09 03:48:46 +0000201The different builtin pass subclasses are described in detail <a
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000202href="#passtype">later</a>, but for now, know that <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s
203operate 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
213We declare a "<a href="#runOnFunction"><tt>runOnFunction</tt></a>" method, which
214overloads an abstract virtual method inherited from <a
215href="#FunctionPass"><tt>FunctionPass</tt></a>. This is where we are supposed
216to do our thing, so we just print out our message with the name of each
217function.<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
224Lastly, 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
226different ways of <a href="#registration">registering your pass</a>, depending
227on what it is to be used for. For "optimizations" we use the
228<tt>RegisterOpt</tt> template.<p>
229
230As 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
248Now that it's all together, compile the file with a simple "<tt>gmake</tt>"
249command 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
251contained in an anonymous namespace: this reflects the fact that passes are self
252contained units that do not need external interfaces (although they can have
253them) 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
263Now 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
265registered your pass with the <tt>RegisterOpt</tt> template, you will be able to
266use the <tt>opt</tt> tool to access it, once loaded.<p>
267
268To test it, follow the example at the end of the <a
269href="GettingStarted.html">Getting Started Guide</a> to compile "Hello World" to
270LLVM. We can now run the bytecode file (<tt>hello.bc</tt>) for the program
271through our transformation like this (or course, any bytecode file will
272work):<p>
273
274<pre>
275$ opt -load ../../../lib/Debug/libhello.so -hello &lt; hello.bc &gt; /dev/null
276Hello: __main
277Hello: puts
278Hello: main
279</pre><p>
280
281The '<tt>-load</tt>' option specifies that '<tt>opt</tt>' should load your pass
282as 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
284pass</a>). Because the hello pass does not modify the program in any
285interesting way, we just throw away the result of <tt>opt</tt> (sending it to
286<tt>/dev/null</tt>).<p>
287
288To 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
293OVERVIEW: llvm .bc -&gt; .bc modular optimizer
294
295USAGE: opt [options] &lt;input bytecode&gt;
296
297OPTIONS:
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
310The pass name get added as the information string for your pass, giving some
311documentation to users of <tt>opt</tt>. Now that you have a working pass, you
312would go ahead and make it do the cool transformations you want. Once you get
313it all working and tested, it may become useful to find out how fast your pass
314is. The <a href="#passManager"><tt>PassManager</tt></a> provides a nice command
315line option (<tt>--time-passes</tt>) that allows you to get information about
316the execution time of your pass along with the other passes you queue up. For
317example:<p>
318
319<pre>
320$ opt -load ../../../lib/Debug/libhello.so -hello -time-passes &lt; hello.bc &gt; /dev/null
321Hello: __main
322Hello: puts
323Hello: 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
337As you can see, our implementation above is pretty fast :). The additional
338passes listed are automatically inserted by the '<tt>opt</tt>' tool to verify
339that the LLVM emitted by your pass is still valid and well formed LLVM, which
340hasn't been broken somehow.
341
342Now that you have seen the basics of the mechanics behind passes, we can talk
343about 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
354One of the first things that you should do when designing a new pass is to
355decide what class you should subclass for your pass. The <a
356href="#basiccode">Hello World</a> example uses the <tt><a
357href="#FunctionPass">FunctionPass</a></tt> class for its implementation, but we
358did not discuss why or when this should occur. Here we talk about the classes
359available, from the most general to the most specific.<p>
360
Chris Lattner79910702002-08-22 19:21:04 +0000361When choosing a superclass for your Pass, you should choose the <b>most
362specific</b> class possible, while still being able to meet the requirements
363listed. This gives the LLVM Pass Infrastructure information neccesary to
364optimize how passes are run, so that the resultant compiler isn't unneccesarily
365slow.<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000366
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
376The "<tt><a href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">Pass</a></tt>"
377class 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,
379refering to function bodies in no predictable order, or adding and removing
380functions. Because nothing is known about the behavior of direct <tt>Pass</tt>
381subclasses, no optimization can be done for their execution.<p>
382
383To write a correct <tt>Pass</tt> subclass, derive from <tt>Pass</tt> and
384overload 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
394The <tt>run</tt> method performs the interesting work of the pass, and should
395return true if the module was modified by the transformation, false
396otherwise.<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
407In contrast to direct <tt>Pass</tt> subclasses, direct <tt><a
408href="http://llvm.cs.uiuc.edu/doxygen/classPass.html">FunctionPass</a></tt>
409subclasses do have a predictable, local behavior that can be expected by the
410system. All <tt>FunctionPass</tt> execute on each function in the program
411independant of all of the other functions in the program.
412<tt>FunctionPass</tt>'s do not require that they are executed in a particular
413order, and <tt>FunctionPass</tt>'s do not modify external functions.<p>
414
415To 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
425Implementing a <tt>FunctionPass</tt> is usually straightforward (See the <a
426href="#basiccode">Hello World</a> pass for example). <tt>FunctionPass</tt>'s
427may overload three virtual methods to do their work. All of these methods
428should return true if they modified the program, or false if they didn't.<p>
429
430<!-- _______________________________________________________________________ -->
Chris Lattnerd0713f92002-09-12 17:06:43 +0000431</ul><h4><a name="doInitialization_mod"><hr size=0>The
432<tt>doInitialization(Module &amp;)</tt> method</h4><ul>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000433
434<pre>
435 <b>virtual bool</b> doInitialization(Module &amp;M);
436</pre><p>
437
438The <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
Chris Lattnerd0713f92002-09-12 17:06:43 +0000440functions, get pointers to functions, etc. The <tt>doInitialization</tt> method
441is designed to do simple initialization type of stuff that does not depend on
442the functions being processed. The <tt>doInitialization</tt> method call is not
443scheduled to overlap with any other pass executions (thus it should be very
444fast).<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000445
446A good example of how this method should be used is the <a
447href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations</a>
448pass. This pass converts <tt>malloc</tt> and <tt>free</tt> instructions into
449platform dependant <tt>malloc()</tt> and <tt>free()</tt> function calls. It
450uses the <tt>doInitialization</tt> method to get a reference to the malloc and
451free 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
460The <tt>runOnFunction</tt> method must be implemented by your subclass to do the
461transformation or analysis work of your pass. As usual, a true value should be
462returned if the function is modified.<p>
463
464<!-- _______________________________________________________________________ -->
Chris Lattnerd0713f92002-09-12 17:06:43 +0000465</ul><h4><a name="doFinalization_mod"><hr size=0>The <tt>doFinalization(Module &amp;)</tt> method</h4><ul>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000466
467<pre>
468 <b>virtual bool</b> doFinalization(Module &amp;M);
469</pre</p>
470
471The <tt>doFinalization</tt> method is an infrequently used method that is called
472when the pass framework has finished calling <a
473href="#runOnFunction"><tt>runOnFunction</tt></a> for every function in the
474program 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
486href="#FunctionPass"><tt>FunctionPass</tt></a>'s, except that they must limit
487their scope of inspection and modification to a single basic block at a time.
488As 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"
500optimizations. They may override the same <a
Chris Lattnerd0713f92002-09-12 17:06:43 +0000501href="#doInitialization_mod"><tt>doInitialization(Module &amp;)</tt></a> and <a
502href="#doFinalization_mod"><tt>doFinalization(Module &amp;)</tt></a> methods that <a
503href="#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
513The <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
516to do simple initialization type of stuff that does not depend on the
517BasicBlocks being processed. The <tt>doInitialization</tt> method call is not
518scheduled to overlap with any other pass executions (thus it should be very
519fast).<p>
520
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000521
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
529Override this function to do the work of the <tt>BasicBlockPass</tt>. This
530function is not allowed to inspect or modify basic blocks other than the
531parameter, and are not allowed to modify the CFG. A true value must be returned
532if the basic block is modified.<p>
533
534
Chris Lattnerd0713f92002-09-12 17:06:43 +0000535<!-- _______________________________________________________________________ -->
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
543The <tt>doFinalization</tt> method is an infrequently used method that is called
544when the pass framework has finished calling <a
545href="#runOnBasicBlock"><tt>runOnBasicBlock</tt></a> for every BasicBlock in the
546program being compiled. This can be used to perform per-function
547finalization.<p>
548
549
550
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000551<!-- *********************************************************************** -->
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
558In the <a href="#basiccode">Hello World</a> example pass we illustrated how pass
559registration works, and discussed some of the reasons that it is used and what
560it does. Here we discuss how and why passes are registered.<p>
561
562Passes can be registered in several different ways. Depending on the general
563classification of the pass, you should use one of the following templates to
564register the pass:<p>
565
566<ul>
567<li><b><tt>RegisterOpt</tt></b> - This template should be used when you are
568registering 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
572registering 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
576registering 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
581multiple or no utilities. This template takes an extra third argument that
582specifies which tools it should be listed in. See the <a
583href="http://llvm.cs.uiuc.edu/doxygen/PassSupport_8h-source.html">PassSupport.h</a>
584file for more information.<p>
585</ul><p>
586
587Regardless of how you register your pass, you must specify at least two
588parameters. The first parameter is the name of the pass that is to be used on
589the command line to specify that the pass should be added to a program (for
590example <tt>opt</tt> or <tt>analyze</tt>). The second argument is the name of
591the pass, which is to be used for the <tt>--help</tt> output of programs, as
592well as for debug output generated by the <tt>--debug-pass</tt> option.<p>
593
594If you pass is constructed by its default constructor, you only ever have to
595pass these two arguments. If, on the other hand, you require other information
596(like target specific information), you must pass an additional argument. This
597argument is a pointer to a function used to create the pass. For an example of
598how this works, look at the <a
599href="http://llvm.cs.uiuc.edu/doxygen/LowerAllocations_8cpp-source.html">LowerAllocations.cpp</a>
600file.<p>
601
602If a pass is registered to be used by the <tt>analyze</tt> utility, you should
603implement 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
612The <tt>print</tt> method must be implemented by "analyses" in order to print a
613human readable version of the analysis results. This is useful for debugging an
614analysis itself, as well as for other people to figure out how an analysis
615works. The <tt>analyze</tt> tool uses this method to generate its output.<p>
616
617The <tt>ostream</tt> parameter specifies the stream to write the results on, and
618the <tt>Module</tt> parameter gives a pointer to the top level module of the
619program that has been analyzed. Note however that this pointer may be null in
620certain circumstances (such as calling the <tt>Pass::dump()</tt> from a
621debugger), so it should only be used to enhance debug output, it should not be
622depended 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
632One of the main responsibilities of the <tt>PassManager</tt> is the make sure
633that passes interact with each other correctly. Because <tt>PassManager</tt>
634tries to <a href="#passmanager">optimize the execution of passes</a> it must
635know how the passes interact with each other and what dependencies exist between
636the various passes. To track this, each pass can declare the set of passes that
637are required to be executed before the current pass, and the passes which are
638invalidated by the current pass.<p>
639
640Typically this functionality is used to require that analysis results are
641computed before your pass is run. Running arbitrary transformation passes can
642invalidate the computed analysis results, which is what the invalidation set
643specifies. If a pass does not implement the <tt><a
644href="#getAnalysisUsage">getAnalysisUsage</a></tt> method, it defaults to not
645having 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
655By implementing the <tt>getAnalysisUsage</tt> method, the required and
656invalidated sets may be specified for your transformation. The implementation
657should fill in the <tt><a
658href="http://llvm.cs.uiuc.edu/doxygen/classAnalysisUsage.html">AnalysisUsage</a></tt>
659object with information about which passes are required and not invalidated. To do this, the following set methods are provided by the <tt><a
660href="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
685Some 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
696and:<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
709The <tt>Pass::getAnalysis&lt;&gt;</tt> method is inherited by your class,
710providing you with access to the passes that you declared that you required with
711the <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method. It takes
712a single template argument that specifies which pass class you want, and returns
713a 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
720This method call returns a reference to the pass desired. You may get a runtime
721assertion failure if you attempt to get an analysis that you did not declare as
722required in your <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a>
723implementation. This method can be called by your <tt>run*</tt> method
724implementation, or by any other local method invoked by your <tt>run*</tt>
725method.<p>
726
Chris Lattner79910702002-08-22 19:21:04 +0000727<!-- *********************************************************************** -->
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
734Now that we understand the basics of how passes are defined, how the are used,
735and how they are required from other passes, it's time to get a little bit
736fancier. All of the pass relationships that we have seen so far are very
737simple: one pass depends on one other specific pass to be run before it can run.
738For many applications, this is great, for others, more flexibility is
739required.<p>
740
741In particular, some analyses are defined such that there is a single simple
742interface to the analysis results, but multiple ways of calculating them.
743Consider alias analysis for example. The most trivial alias analysis returns
744"may alias" for any alias query. The most sophisticated analysis a
745flow-sensitive, context-sensitive interprocedural analysis that can take a
746significant amount of time to execute (and obviously, there is a lot of room
747between these two extremes for other implementations). To cleanly support
748situations like this, the LLVM Pass Infrastructure supports the notion of
749Analysis Groups.<p>
750
751<!-- _______________________________________________________________________ -->
752</ul><h4><a name="agconcepts"><hr size=0>Analysis Group Concepts</h4><ul>
753
754An Analysis Group is a single simple interface that may be implemented by
755multiple different passes. Analysis Groups can be given human readable names
756just like passes, but unlike passes, they need not derive from the <tt>Pass</tt>
757class. An analysis group may have one or more implementations, one of which is
758the "default" implementation.<p>
759
760Analysis groups are used by client passes just like other passes are: the
761<tt>AnalysisUsage::addRequired()</tt> and <tt>Pass::getAnalysis()</tt> methods.
762In order to resolve this requirement, the <a href="#passmanager">PassManager</a>
763scans the available passes to see if any implementations of the analysis group
764are available. If none is available, the default implementation is created for
765the pass to use. All standard rules for <A href="#interaction">interaction
766between passes</a> still apply.<p>
767
768Although <a href="#registration">Pass Registration</a> is optional for normal
769passes, all analysis group implementations must be registered, and must use the
770<A href="#registerag"><tt>RegisterAnalysisGroup</tt></a> template to join the
771implementation pool. Also, a default implementation of the interface
772<b>must</b> be registered with <A
773href="#registerag"><tt>RegisterAnalysisGroup</tt></a>.<p>
774
775As a concrete example of an Analysis Group in action, consider the <a
776href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a>
777analysis group. The default implementation of the alias analysis interface (the
778<tt><a
779href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">basicaa</a></tt>
780pass) just does a few simple checks that don't require significant analysis to
781compute (such as: two different globals can never alias each other, etc).
782Passes that use the <tt><a
783href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a></tt>
784interface (for example the <tt><a
785href="http://llvm.cs.uiuc.edu/doxygen/classGCSE.html">gcse</a></tt> pass), do not care which implementation
786of alias analysis is actually provided, they just use the designated
787interface.<p>
788
789From the user's perspective, commands work just like normal. Issuing the
790command '<tt>opt -gcse ...</tt>' will cause the <tt>basicaa</tt> class to be
791instantiated 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
794hypothetical example) instead.<p>
795
796
797<!-- _______________________________________________________________________ -->
798</ul><h4><a name="registerag"><hr size=0>Using <tt>RegisterAnalysisGroup</tt></h4><ul>
799
800The <tt>RegisterAnalysisGroup</tt> template is used to register the analysis
801group itself as well as add pass implementations to the analysis group. First,
802an analysis should be registered, with a human readable name provided for it.
803Unlike registration of passes, there is no command line argument to be specified
804for 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
810Once the analysis is registered, passes can declare that they are valid
811implementations 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
824This just shows a class <tt>FancyAA</tt> that is registered normally, then uses
825the <tt>RegisterAnalysisGroup</tt> template to "join" the <tt><a
826href="http://llvm.cs.uiuc.edu/doxygen/structAliasAnalysis.html">AliasAnalysis</a></tt>
827analysis group. Every implementation of an analysis group should join using
828this template. A single pass may join multiple different analysis groups with
829no 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
842Here we show how the default implementation is specified (using the extra
843argument to the <tt>RegisterAnalysisGroup</tt> template). There must be exactly
844one default implementation available at all times for an Analysis Group to be
845used. Here we declare that the <tt><a
846href="http://llvm.cs.uiuc.edu/doxygen/structBasicAliasAnalysis.html">BasicAliasAnalysis</a></tt>
847pass is the default implementation for the interface.<p>
Chris Lattnerc6bb8242002-08-08 20:11:18 +0000848
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
857The <a
858href="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
860a list of passes, ensures their <a href="#interaction">prerequisites</a> are set
861up correctly, and then schedules passes to run efficiently. All of the LLVM
862tools that run passes use the <tt>PassManager</tt> for execution of these
863passes.<p>
864
865The <tt>PassManager</tt> does two main things to try to reduce the execution
866time of a series of passes:<p>
867
868<ol>
869<li><b>Share analysis results</b> - The PassManager attempts to avoid
870recomputing analysis results as much as possible. This means keeping track of
871which analyses are available already, which analyses get invalidated, and which
872analyses 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
874it to <a href="#releaseMemory">free memory</a> allocated to holding analysis
875results 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
879of a series of passes by pipelining the passes together. This means that, given
880a series of consequtive <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s, it
881will execute all of the <a href="#FunctionPass"><tt>FunctionPass</tt></a>'s on
882the first function, then all of the <a
883href="#FunctionPass"><tt>FunctionPass</tt></a>'s on the second function,
884etc... until the entire program has been run through the passes.<p>
885
886This improves the cache behavior of the compiler, because it is only touching
887the LLVM program representation for a single function at a time, instead of
888traversing the entire program. It reduces the memory consumption of compiler,
889because, for example, only one <a
890href="http://llvm.cs.uiuc.edu/doxygen/structDominatorSet.html"><tt>DominatorSet</tt></a>
891needs to be calculated at a time. This also makes it possible some <a
892href="#SMP">interesting enhancements</a> in the future.<p>
893
894</ol><p>
895
896The effectiveness of the <tt>PassManager</tt> is influenced directly by how much
897information it has about the behaviors of the passes it is scheduling. For
898example, the "preserved" set is intentionally conservative in the face of an
899unimplemented <a href="#getAnalysisUsage"><tt>getAnalysisUsage</tt></a> method.
900Not implementing when it should be implemented will have the effect of not
901allowing any analysis results to live across the execution of your pass.<p>
902
903The <tt>PassManager</tt> class exposes a <tt>--debug-pass</tt> command line
904options that is useful for debugging pass execution, seeing how things work, and
905diagnosing 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>
907option, just type '<tt>opt --help-hidden</tt>').<p>
908
909By using the <tt>--debug-pass=Structure</tt> option, for example, we can see how
910our <a href="#basiccode">Hello World</a> pass interacts with other passes. Lets
911try 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
915Module 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
933This output shows us when passes are constructed and when the analysis results
934are known to be dead (prefixed with '<tt>--</tt>'). Here we see that GCSE uses
935dominator and immediate dominator information to do its job. The LICM pass uses
936natural loop information, which uses dominator sets, but not immediate
937dominators. Because immediate dominators are no longer useful after the GCSE
938pass, it is immediately destroyed. The dominator sets are then reused to
939compute natural loop information, which is then used by the LICM pass.<p>
940
941After the LICM pass, the module verifier runs (which is automatically added by
942the '<tt>opt</tt>' tool), which uses the dominator set to check that the
943resultant LLVM code is well formed. After it finishes, the dominator set
944information is destroyed, after being computed once, and shared by three
945passes.<p>
946
947Lets see how this changes when we run the <a href="#basiccode">Hello World</a>
948pass 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
952Module 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
972Hello: __main
973Hello: puts
974Hello: main
975</pre><p>
976
977Here we see that the <a href="#basiccode">Hello World</a> pass has killed the
978Dominator Set pass, even though it doesn't modify the code at all! To fix this,
979we need to add the following <a
980href="#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
989Now 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
993Pass Arguments: -gcse -hello -licm
994Module 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
1012Hello: __main
1013Hello: puts
1014Hello: main
1015</pre><p>
1016
1017Which shows that we don't accidentally invalidate dominator information
1018anymore, 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
1028The <tt>PassManager</tt> automatically determines when to compute analysis
1029results, and how long to keep them around for. Because the lifetime of the pass
1030object itself is effectively the entire duration of the compilation process, we
1031need 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
1034If you are writing an analysis or any other pass that retains a significant
1035amount 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
1038internal state. This method is called after the <tt>run*</tt> method for the
1039class, 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>
Chris Lattner480e2ef2002-09-06 02:02:58 +00001045<a name="debughints">Using GDB with dynamically loaded passes
1046</b></font></td></tr></table><ul>
1047<!-- *********************************************************************** -->
1048
1049Unfortunately, using GDB with dynamically loaded passes is not as easy as it
1050should be. First of all, you can't set a breakpoint in a shared object that has
1051not been loaded yet, and second of all there are problems with inlined functions
1052in shared objects. Here are some suggestions to debugging your pass with
1053GDB.<p>
1054
1055For sake of discussion, I'm going to assume that you are debugging a
1056transformation invoked by <tt>opt</tt>, although nothing described here depends
1057on that.<p>
1058
1059<!-- _______________________________________________________________________ -->
1060</ul><h4><a name="breakpoint"><hr size=0>Setting a breakpoint in your pass</h4><ul>
1061
1062First thing you do is start <tt>gdb</tt> on the <tt>opt</tt> process:<p>
1063
1064<pre>
1065$ <b>gdb opt</b>
1066GNU gdb 5.0
1067Copyright 2000 Free Software Foundation, Inc.
1068GDB is free software, covered by the GNU General Public License, and you are
1069welcome to change it and/or distribute copies of it under certain conditions.
1070Type "show copying" to see the conditions.
1071There is absolutely no warranty for GDB. Type "show warranty" for details.
1072This GDB was configured as "sparc-sun-solaris2.6"...
1073(gdb)
1074</pre><p>
1075
1076Note that <tt>opt</tt> has a lot of debugging information in it, so it takes
1077time 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
1079have it stop before it invokes our pass, but after it has loaded the shared
1080object. 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
1082want:<p>
1083
1084<pre>
1085(gdb) <b>break PassManager::run</b>
1086Breakpoint 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>
1088Starting program: /shared/lattner/cvs/llvm/tools/Debug/opt test.bc
1089 -load /shared/lattner/cvs/llvm/lib/Debug/[libname].so -[passoption]
1090Breakpoint 1, PassManager::run (this=0xffbef174, M=@0x70b298) at Pass.cpp:70
109170 bool PassManager::run(Module &amp;M) { return PM-&gt;run(M); }
1092(gdb)
1093</pre></p>
1094
1095Once the <tt>opt</tt> stops in the <tt>PassManager::run</tt> method you are now
1096free to set breakpoints in your pass so that you can trace through execution or
1097do other standard debugging stuff.<p>
1098
1099
1100<!-- _______________________________________________________________________ -->
1101</ul><h4><a name="debugmisc"><hr size=0>Miscellaneous Problems</h4><ul>
1102
1103Once you have the basics down, there are a couple of problems that GDB has, some
1104with solutions, some without.<p>
1105
1106<ul>
1107<li>Inline functions have bogus stack information. In general, GDB does a
1108pretty good job getting stack traces and stepping through inline functions.
1109When a pass is dynamically loaded however, it somehow completely loses this
1110capability. The only solution I know of is to de-inline a function (move it
1111from the body of a class to a .cpp file).<p>
1112
1113<li>Restarting the program breaks breakpoints. After following the information
1114above, you have succeeded in getting some breakpoints planted in your pass. Nex
1115thing you know, you restart the program (i.e., you type '<tt>run</tt>' again),
1116and you start getting errors about breakpoints being unsettable. The only way I
1117have found to "fix" this problem is to <tt>delete</tt> the breakpoints that are
1118already set in your pass, run the program, and re-set the breakpoints once
1119execution stops in <tt>PassManager::run</tt>.<p>
1120
1121</ul>
1122
1123Hopefully these tips will help with common case debugging situations. If you'd
1124like to contribute some tips of your own, just contact <a
1125href="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>
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001131<a name="future">Future extensions planned
1132</b></font></td></tr></table><ul>
1133<!-- *********************************************************************** -->
1134
1135Although the LLVM Pass Infrastructure is very capable as it stands, and does
1136some nifty stuff, there are things we'd like to add in the future. Here is
1137where we are going:<p>
1138
1139<!-- _______________________________________________________________________ -->
1140</ul><h4><a name="SMP"><hr size=0>Multithreaded LLVM</h4><ul>
1141
Chris Lattnered2e7a92002-09-17 16:47:06 +00001142Multiple CPU machines are becoming more common and compilation can never be
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001143fast enough: obviously we should allow for a multithreaded compiler. Because of
1144the semantics defined for passes above (specifically they cannot maintain state
1145across invocations of their <tt>run*</tt> methods), a nice clean way to
1146implement a multithreaded compiler would be for the <tt>PassManager</tt> class
1147to create multiple instances of each pass object, and allow the seperate
1148instances to be hacking on different parts of the program at the same time.<p>
1149
1150This implementation would prevent each of the passes from having to implement
1151multithreaded constructs, requiring only the LLVM core to have locking in a few
1152places (for global resources). Although this is a simple extension, we simply
1153haven't had time (or multiprocessor machines, thus a reason) to implement this.
1154Despite 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
1160Currently, the <tt>PassManager</tt>'s <tt>run</tt> method takes a <tt><a
1161href="http://llvm.cs.uiuc.edu/doxygen/classModule.html">Module</a></tt> as
1162input, and runs all of the passes on this module. The problem with this
1163approach is that none of the <tt>PassManager</tt> features can be used for
1164timing and debugging the actual <b>loading</b> of the module from disk or
1165standard input.<p>
1166
1167To 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
1169will also allow for streaming of functions out of the bytecode representation,
1170allowing us to avoid holding the entire program in memory at once if we only are
1171dealing with <a href="#FunctionPass">FunctionPass</a>'s.<p>
1172
1173As part of a different issue, eventually the bytecode loader will be extended to
1174allow on-demand loading of functions from the bytecode representation, in order
1175to better support the runtime reoptimizer. The bytecode format is already
1176capable 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
1182Currently it is illegal for a <a href="#Pass"><tt>Pass</tt></a> to require a <a
1183href="#FunctionPass"><tt>FunctionPass</tt></a>. This is because there is only
1184one instance of the <a href="#FunctionPass"><tt>FunctionPass</tt></a> object
1185ever created, thus nowhere to store information for all of the functions in the
1186program at the same time. Although this has come up a couple of times before,
1187this has always been worked around by factoring one big complicated pass into a
1188global and an interprocedural part, both of which are distinct. In the future,
1189it would be nice to have this though.<p>
1190
1191Note that it is no problem for a <a
1192href="#FunctionPass"><tt>FunctionPass</tt></a> to require the results of a <a
1193href="#Pass"><tt>Pass</tt></a>, only the other way around.<p>
1194
1195
1196<!-- *********************************************************************** -->
1197</ul>
1198<!-- *********************************************************************** -->
1199
1200<hr><font size-1>
Chris Lattner480e2ef2002-09-06 02:02:58 +00001201<address><a href="mailto:sabre@nondot.org">Chris Lattner</a></address>
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001202<!-- Created: Tue Aug 6 15:00:33 CDT 2002 -->
1203<!-- hhmts start -->
Chris Lattnerfd214762002-09-16 22:37:56 +00001204Last modified: Mon Sep 16 17:37:27 CDT 2002
Chris Lattnerc6bb8242002-08-08 20:11:18 +00001205<!-- hhmts end -->
1206</font></body></html>