Documentation: add a section to prevent spurious test failures like the one
[oota-llvm.git] / docs / AliasAnalysis.rst
1 .. _alias_analysis:
2
3 ==================================
4 LLVM Alias Analysis Infrastructure
5 ==================================
6
7 .. contents::
8    :local:
9
10 Introduction
11 ============
12
13 Alias Analysis (aka Pointer Analysis) is a class of techniques which attempt to
14 determine whether or not two pointers ever can point to the same object in
15 memory.  There are many different algorithms for alias analysis and many
16 different ways of classifying them: flow-sensitive vs. flow-insensitive,
17 context-sensitive vs. context-insensitive, field-sensitive
18 vs. field-insensitive, unification-based vs. subset-based, etc.  Traditionally,
19 alias analyses respond to a query with a `Must, May, or No`_ alias response,
20 indicating that two pointers always point to the same object, might point to the
21 same object, or are known to never point to the same object.
22
23 The LLVM `AliasAnalysis
24 <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__ class is the
25 primary interface used by clients and implementations of alias analyses in the
26 LLVM system.  This class is the common interface between clients of alias
27 analysis information and the implementations providing it, and is designed to
28 support a wide range of implementations and clients (but currently all clients
29 are assumed to be flow-insensitive).  In addition to simple alias analysis
30 information, this class exposes Mod/Ref information from those implementations
31 which can provide it, allowing for powerful analyses and transformations to work
32 well together.
33
34 This document contains information necessary to successfully implement this
35 interface, use it, and to test both sides.  It also explains some of the finer
36 points about what exactly results mean.  If you feel that something is unclear
37 or should be added, please `let me know <mailto:sabre@nondot.org>`_.
38
39 ``AliasAnalysis`` Class Overview
40 ================================
41
42 The `AliasAnalysis <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__
43 class defines the interface that the various alias analysis implementations
44 should support.  This class exports two important enums: ``AliasResult`` and
45 ``ModRefResult`` which represent the result of an alias query or a mod/ref
46 query, respectively.
47
48 The ``AliasAnalysis`` interface exposes information about memory, represented in
49 several different ways.  In particular, memory objects are represented as a
50 starting address and size, and function calls are represented as the actual
51 ``call`` or ``invoke`` instructions that performs the call.  The
52 ``AliasAnalysis`` interface also exposes some helper methods which allow you to
53 get mod/ref information for arbitrary instructions.
54
55 All ``AliasAnalysis`` interfaces require that in queries involving multiple
56 values, values which are not `constants <LangRef.html#constants>`_ are all
57 defined within the same function.
58
59 Representation of Pointers
60 --------------------------
61
62 Most importantly, the ``AliasAnalysis`` class provides several methods which are
63 used to query whether or not two memory objects alias, whether function calls
64 can modify or read a memory object, etc.  For all of these queries, memory
65 objects are represented as a pair of their starting address (a symbolic LLVM
66 ``Value*``) and a static size.
67
68 Representing memory objects as a starting address and a size is critically
69 important for correct Alias Analyses.  For example, consider this (silly, but
70 possible) C code:
71
72 .. code-block:: c++
73
74   int i;
75   char C[2];
76   char A[10]; 
77   /* ... */
78   for (i = 0; i != 10; ++i) {
79     C[0] = A[i];          /* One byte store */
80     C[1] = A[9-i];        /* One byte store */
81   }
82
83 In this case, the ``basicaa`` pass will disambiguate the stores to ``C[0]`` and
84 ``C[1]`` because they are accesses to two distinct locations one byte apart, and
85 the accesses are each one byte.  In this case, the Loop Invariant Code Motion
86 (LICM) pass can use store motion to remove the stores from the loop.  In
87 constrast, the following code:
88
89 .. code-block:: c++
90
91   int i;
92   char C[2];
93   char A[10]; 
94   /* ... */
95   for (i = 0; i != 10; ++i) {
96     ((short*)C)[0] = A[i];  /* Two byte store! */
97     C[1] = A[9-i];          /* One byte store */
98   }
99
100 In this case, the two stores to C do alias each other, because the access to the
101 ``&C[0]`` element is a two byte access.  If size information wasn't available in
102 the query, even the first case would have to conservatively assume that the
103 accesses alias.
104
105 .. _alias:
106
107 The ``alias`` method
108 --------------------
109   
110 The ``alias`` method is the primary interface used to determine whether or not
111 two memory objects alias each other.  It takes two memory objects as input and
112 returns MustAlias, PartialAlias, MayAlias, or NoAlias as appropriate.
113
114 Like all ``AliasAnalysis`` interfaces, the ``alias`` method requires that either
115 the two pointer values be defined within the same function, or at least one of
116 the values is a `constant <LangRef.html#constants>`_.
117
118 .. _Must, May, or No:
119
120 Must, May, and No Alias Responses
121 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
122
123 The ``NoAlias`` response may be used when there is never an immediate dependence
124 between any memory reference *based* on one pointer and any memory reference
125 *based* the other. The most obvious example is when the two pointers point to
126 non-overlapping memory ranges. Another is when the two pointers are only ever
127 used for reading memory. Another is when the memory is freed and reallocated
128 between accesses through one pointer and accesses through the other --- in this
129 case, there is a dependence, but it's mediated by the free and reallocation.
130
131 As an exception to this is with the `noalias <LangRef.html#noalias>`_ keyword;
132 the "irrelevant" dependencies are ignored.
133
134 The ``MayAlias`` response is used whenever the two pointers might refer to the
135 same object.
136
137 The ``PartialAlias`` response is used when the two memory objects are known to
138 be overlapping in some way, but do not start at the same address.
139
140 The ``MustAlias`` response may only be returned if the two memory objects are
141 guaranteed to always start at exactly the same location. A ``MustAlias``
142 response implies that the pointers compare equal.
143
144 The ``getModRefInfo`` methods
145 -----------------------------
146
147 The ``getModRefInfo`` methods return information about whether the execution of
148 an instruction can read or modify a memory location.  Mod/Ref information is
149 always conservative: if an instruction **might** read or write a location,
150 ``ModRef`` is returned.
151
152 The ``AliasAnalysis`` class also provides a ``getModRefInfo`` method for testing
153 dependencies between function calls.  This method takes two call sites (``CS1``
154 & ``CS2``), returns ``NoModRef`` if neither call writes to memory read or
155 written by the other, ``Ref`` if ``CS1`` reads memory written by ``CS2``,
156 ``Mod`` if ``CS1`` writes to memory read or written by ``CS2``, or ``ModRef`` if
157 ``CS1`` might read or write memory written to by ``CS2``.  Note that this
158 relation is not commutative.
159
160 Other useful ``AliasAnalysis`` methods
161 --------------------------------------
162
163 Several other tidbits of information are often collected by various alias
164 analysis implementations and can be put to good use by various clients.
165
166 The ``pointsToConstantMemory`` method
167 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
168
169 The ``pointsToConstantMemory`` method returns true if and only if the analysis
170 can prove that the pointer only points to unchanging memory locations
171 (functions, constant global variables, and the null pointer).  This information
172 can be used to refine mod/ref information: it is impossible for an unchanging
173 memory location to be modified.
174
175 .. _never access memory or only read memory:
176
177 The ``doesNotAccessMemory`` and  ``onlyReadsMemory`` methods
178 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
179
180 These methods are used to provide very simple mod/ref information for function
181 calls.  The ``doesNotAccessMemory`` method returns true for a function if the
182 analysis can prove that the function never reads or writes to memory, or if the
183 function only reads from constant memory.  Functions with this property are
184 side-effect free and only depend on their input arguments, allowing them to be
185 eliminated if they form common subexpressions or be hoisted out of loops.  Many
186 common functions behave this way (e.g., ``sin`` and ``cos``) but many others do
187 not (e.g., ``acos``, which modifies the ``errno`` variable).
188
189 The ``onlyReadsMemory`` method returns true for a function if analysis can prove
190 that (at most) the function only reads from non-volatile memory.  Functions with
191 this property are side-effect free, only depending on their input arguments and
192 the state of memory when they are called.  This property allows calls to these
193 functions to be eliminated and moved around, as long as there is no store
194 instruction that changes the contents of memory.  Note that all functions that
195 satisfy the ``doesNotAccessMemory`` method also satisfies ``onlyReadsMemory``.
196
197 Writing a new ``AliasAnalysis`` Implementation
198 ==============================================
199
200 Writing a new alias analysis implementation for LLVM is quite straight-forward.
201 There are already several implementations that you can use for examples, and the
202 following information should help fill in any details.  For a examples, take a
203 look at the `various alias analysis implementations`_ included with LLVM.
204
205 Different Pass styles
206 ---------------------
207
208 The first step to determining what type of :doc:`LLVM pass <WritingAnLLVMPass>`
209 you need to use for your Alias Analysis.  As is the case with most other
210 analyses and transformations, the answer should be fairly obvious from what type
211 of problem you are trying to solve:
212
213 #. If you require interprocedural analysis, it should be a ``Pass``.
214 #. If you are a function-local analysis, subclass ``FunctionPass``.
215 #. If you don't need to look at the program at all, subclass ``ImmutablePass``.
216
217 In addition to the pass that you subclass, you should also inherit from the
218 ``AliasAnalysis`` interface, of course, and use the ``RegisterAnalysisGroup``
219 template to register as an implementation of ``AliasAnalysis``.
220
221 Required initialization calls
222 -----------------------------
223
224 Your subclass of ``AliasAnalysis`` is required to invoke two methods on the
225 ``AliasAnalysis`` base class: ``getAnalysisUsage`` and
226 ``InitializeAliasAnalysis``.  In particular, your implementation of
227 ``getAnalysisUsage`` should explicitly call into the
228 ``AliasAnalysis::getAnalysisUsage`` method in addition to doing any declaring
229 any pass dependencies your pass has.  Thus you should have something like this:
230
231 .. code-block:: c++
232
233   void getAnalysisUsage(AnalysisUsage &AU) const {
234     AliasAnalysis::getAnalysisUsage(AU);
235     // declare your dependencies here.
236   }
237
238 Additionally, your must invoke the ``InitializeAliasAnalysis`` method from your
239 analysis run method (``run`` for a ``Pass``, ``runOnFunction`` for a
240 ``FunctionPass``, or ``InitializePass`` for an ``ImmutablePass``).  For example
241 (as part of a ``Pass``):
242
243 .. code-block:: c++
244
245   bool run(Module &M) {
246     InitializeAliasAnalysis(this);
247     // Perform analysis here...
248     return false;
249   }
250
251 Interfaces which may be specified
252 ---------------------------------
253
254 All of the `AliasAnalysis
255 <http://llvm.org/doxygen/classllvm_1_1AliasAnalysis.html>`__ virtual methods
256 default to providing :ref:`chaining <aliasanalysis-chaining>` to another alias
257 analysis implementation, which ends up returning conservatively correct
258 information (returning "May" Alias and "Mod/Ref" for alias and mod/ref queries
259 respectively).  Depending on the capabilities of the analysis you are
260 implementing, you just override the interfaces you can improve.
261
262 .. _aliasanalysis-chaining:
263
264 ``AliasAnalysis`` chaining behavior
265 -----------------------------------
266
267 With only one special exception (the :ref:`-no-aa <aliasanalysis-no-aa>` pass)
268 every alias analysis pass chains to another alias analysis implementation (for
269 example, the user can specify "``-basicaa -ds-aa -licm``" to get the maximum
270 benefit from both alias analyses).  The alias analysis class automatically
271 takes care of most of this for methods that you don't override.  For methods
272 that you do override, in code paths that return a conservative MayAlias or
273 Mod/Ref result, simply return whatever the superclass computes.  For example:
274
275 .. code-block:: c++
276
277   AliasAnalysis::AliasResult alias(const Value *V1, unsigned V1Size,
278                                    const Value *V2, unsigned V2Size) {
279     if (...)
280       return NoAlias;
281     ...
282
283     // Couldn't determine a must or no-alias result.
284     return AliasAnalysis::alias(V1, V1Size, V2, V2Size);
285   }
286
287 In addition to analysis queries, you must make sure to unconditionally pass LLVM
288 `update notification`_ methods to the superclass as well if you override them,
289 which allows all alias analyses in a change to be updated.
290
291 .. _update notification:
292
293 Updating analysis results for transformations
294 ---------------------------------------------
295
296 Alias analysis information is initially computed for a static snapshot of the
297 program, but clients will use this information to make transformations to the
298 code.  All but the most trivial forms of alias analysis will need to have their
299 analysis results updated to reflect the changes made by these transformations.
300
301 The ``AliasAnalysis`` interface exposes four methods which are used to
302 communicate program changes from the clients to the analysis implementations.
303 Various alias analysis implementations should use these methods to ensure that
304 their internal data structures are kept up-to-date as the program changes (for
305 example, when an instruction is deleted), and clients of alias analysis must be
306 sure to call these interfaces appropriately.
307
308 The ``deleteValue`` method
309 ^^^^^^^^^^^^^^^^^^^^^^^^^^
310
311 The ``deleteValue`` method is called by transformations when they remove an
312 instruction or any other value from the program (including values that do not
313 use pointers).  Typically alias analyses keep data structures that have entries
314 for each value in the program.  When this method is called, they should remove
315 any entries for the specified value, if they exist.
316
317 The ``copyValue`` method
318 ^^^^^^^^^^^^^^^^^^^^^^^^
319
320 The ``copyValue`` method is used when a new value is introduced into the
321 program.  There is no way to introduce a value into the program that did not
322 exist before (this doesn't make sense for a safe compiler transformation), so
323 this is the only way to introduce a new value.  This method indicates that the
324 new value has exactly the same properties as the value being copied.
325
326 The ``replaceWithNewValue`` method
327 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
328
329 This method is a simple helper method that is provided to make clients easier to
330 use.  It is implemented by copying the old analysis information to the new
331 value, then deleting the old value.  This method cannot be overridden by alias
332 analysis implementations.
333
334 The ``addEscapingUse`` method
335 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
336
337 The ``addEscapingUse`` method is used when the uses of a pointer value have
338 changed in ways that may invalidate precomputed analysis information.
339 Implementations may either use this callback to provide conservative responses
340 for points whose uses have change since analysis time, or may recompute some or
341 all of their internal state to continue providing accurate responses.
342
343 In general, any new use of a pointer value is considered an escaping use, and
344 must be reported through this callback, *except* for the uses below:
345
346 * A ``bitcast`` or ``getelementptr`` of the pointer
347 * A ``store`` through the pointer (but not a ``store`` *of* the pointer)
348 * A ``load`` through the pointer
349
350 Efficiency Issues
351 -----------------
352
353 From the LLVM perspective, the only thing you need to do to provide an efficient
354 alias analysis is to make sure that alias analysis **queries** are serviced
355 quickly.  The actual calculation of the alias analysis results (the "run"
356 method) is only performed once, but many (perhaps duplicate) queries may be
357 performed.  Because of this, try to move as much computation to the run method
358 as possible (within reason).
359
360 Limitations
361 -----------
362
363 The AliasAnalysis infrastructure has several limitations which make writing a
364 new ``AliasAnalysis`` implementation difficult.
365
366 There is no way to override the default alias analysis. It would be very useful
367 to be able to do something like "``opt -my-aa -O2``" and have it use ``-my-aa``
368 for all passes which need AliasAnalysis, but there is currently no support for
369 that, short of changing the source code and recompiling. Similarly, there is
370 also no way of setting a chain of analyses as the default.
371
372 There is no way for transform passes to declare that they preserve
373 ``AliasAnalysis`` implementations. The ``AliasAnalysis`` interface includes
374 ``deleteValue`` and ``copyValue`` methods which are intended to allow a pass to
375 keep an AliasAnalysis consistent, however there's no way for a pass to declare
376 in its ``getAnalysisUsage`` that it does so. Some passes attempt to use
377 ``AU.addPreserved<AliasAnalysis>``, however this doesn't actually have any
378 effect.
379
380 ``AliasAnalysisCounter`` (``-count-aa``) and ``AliasDebugger`` (``-debug-aa``)
381 are implemented as ``ModulePass`` classes, so if your alias analysis uses
382 ``FunctionPass``, it won't be able to use these utilities. If you try to use
383 them, the pass manager will silently route alias analysis queries directly to
384 ``BasicAliasAnalysis`` instead.
385
386 Similarly, the ``opt -p`` option introduces ``ModulePass`` passes between each
387 pass, which prevents the use of ``FunctionPass`` alias analysis passes.
388
389 The ``AliasAnalysis`` API does have functions for notifying implementations when
390 values are deleted or copied, however these aren't sufficient. There are many
391 other ways that LLVM IR can be modified which could be relevant to
392 ``AliasAnalysis`` implementations which can not be expressed.
393
394 The ``AliasAnalysisDebugger`` utility seems to suggest that ``AliasAnalysis``
395 implementations can expect that they will be informed of any relevant ``Value``
396 before it appears in an alias query. However, popular clients such as ``GVN``
397 don't support this, and are known to trigger errors when run with the
398 ``AliasAnalysisDebugger``.
399
400 Due to several of the above limitations, the most obvious use for the
401 ``AliasAnalysisCounter`` utility, collecting stats on all alias queries in a
402 compilation, doesn't work, even if the ``AliasAnalysis`` implementations don't
403 use ``FunctionPass``.  There's no way to set a default, much less a default
404 sequence, and there's no way to preserve it.
405
406 The ``AliasSetTracker`` class (which is used by ``LICM``) makes a
407 non-deterministic number of alias queries. This can cause stats collected by
408 ``AliasAnalysisCounter`` to have fluctuations among identical runs, for
409 example. Another consequence is that debugging techniques involving pausing
410 execution after a predetermined number of queries can be unreliable.
411
412 Many alias queries can be reformulated in terms of other alias queries. When
413 multiple ``AliasAnalysis`` queries are chained together, it would make sense to
414 start those queries from the beginning of the chain, with care taken to avoid
415 infinite looping, however currently an implementation which wants to do this can
416 only start such queries from itself.
417
418 Using alias analysis results
419 ============================
420
421 There are several different ways to use alias analysis results.  In order of
422 preference, these are:
423
424 Using the ``MemoryDependenceAnalysis`` Pass
425 -------------------------------------------
426
427 The ``memdep`` pass uses alias analysis to provide high-level dependence
428 information about memory-using instructions.  This will tell you which store
429 feeds into a load, for example.  It uses caching and other techniques to be
430 efficient, and is used by Dead Store Elimination, GVN, and memcpy optimizations.
431
432 .. _AliasSetTracker:
433
434 Using the ``AliasSetTracker`` class
435 -----------------------------------
436
437 Many transformations need information about alias **sets** that are active in
438 some scope, rather than information about pairwise aliasing.  The
439 `AliasSetTracker <http://llvm.org/doxygen/classllvm_1_1AliasSetTracker.html>`__
440 class is used to efficiently build these Alias Sets from the pairwise alias
441 analysis information provided by the ``AliasAnalysis`` interface.
442
443 First you initialize the AliasSetTracker by using the "``add``" methods to add
444 information about various potentially aliasing instructions in the scope you are
445 interested in.  Once all of the alias sets are completed, your pass should
446 simply iterate through the constructed alias sets, using the ``AliasSetTracker``
447 ``begin()``/``end()`` methods.
448
449 The ``AliasSet``\s formed by the ``AliasSetTracker`` are guaranteed to be
450 disjoint, calculate mod/ref information and volatility for the set, and keep
451 track of whether or not all of the pointers in the set are Must aliases.  The
452 AliasSetTracker also makes sure that sets are properly folded due to call
453 instructions, and can provide a list of pointers in each set.
454
455 As an example user of this, the `Loop Invariant Code Motion
456 <doxygen/structLICM.html>`_ pass uses ``AliasSetTracker``\s to calculate alias
457 sets for each loop nest.  If an ``AliasSet`` in a loop is not modified, then all
458 load instructions from that set may be hoisted out of the loop.  If any alias
459 sets are stored to **and** are must alias sets, then the stores may be sunk
460 to outside of the loop, promoting the memory location to a register for the
461 duration of the loop nest.  Both of these transformations only apply if the
462 pointer argument is loop-invariant.
463
464 The AliasSetTracker implementation
465 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
466
467 The AliasSetTracker class is implemented to be as efficient as possible.  It
468 uses the union-find algorithm to efficiently merge AliasSets when a pointer is
469 inserted into the AliasSetTracker that aliases multiple sets.  The primary data
470 structure is a hash table mapping pointers to the AliasSet they are in.
471
472 The AliasSetTracker class must maintain a list of all of the LLVM ``Value*``\s
473 that are in each AliasSet.  Since the hash table already has entries for each
474 LLVM ``Value*`` of interest, the AliasesSets thread the linked list through
475 these hash-table nodes to avoid having to allocate memory unnecessarily, and to
476 make merging alias sets extremely efficient (the linked list merge is constant
477 time).
478
479 You shouldn't need to understand these details if you are just a client of the
480 AliasSetTracker, but if you look at the code, hopefully this brief description
481 will help make sense of why things are designed the way they are.
482
483 Using the ``AliasAnalysis`` interface directly
484 ----------------------------------------------
485
486 If neither of these utility class are what your pass needs, you should use the
487 interfaces exposed by the ``AliasAnalysis`` class directly.  Try to use the
488 higher-level methods when possible (e.g., use mod/ref information instead of the
489 `alias`_ method directly if possible) to get the best precision and efficiency.
490
491 Existing alias analysis implementations and clients
492 ===================================================
493
494 If you're going to be working with the LLVM alias analysis infrastructure, you
495 should know what clients and implementations of alias analysis are available.
496 In particular, if you are implementing an alias analysis, you should be aware of
497 the `the clients`_ that are useful for monitoring and evaluating different
498 implementations.
499
500 .. _various alias analysis implementations:
501
502 Available ``AliasAnalysis`` implementations
503 -------------------------------------------
504
505 This section lists the various implementations of the ``AliasAnalysis``
506 interface.  With the exception of the :ref:`-no-aa <aliasanalysis-no-aa>`
507 implementation, all of these :ref:`chain <aliasanalysis-chaining>` to other
508 alias analysis implementations.
509
510 .. _aliasanalysis-no-aa:
511
512 The ``-no-aa`` pass
513 ^^^^^^^^^^^^^^^^^^^
514
515 The ``-no-aa`` pass is just like what it sounds: an alias analysis that never
516 returns any useful information.  This pass can be useful if you think that alias
517 analysis is doing something wrong and are trying to narrow down a problem.
518
519 The ``-basicaa`` pass
520 ^^^^^^^^^^^^^^^^^^^^^
521
522 The ``-basicaa`` pass is an aggressive local analysis that *knows* many
523 important facts:
524
525 * Distinct globals, stack allocations, and heap allocations can never alias.
526 * Globals, stack allocations, and heap allocations never alias the null pointer.
527 * Different fields of a structure do not alias.
528 * Indexes into arrays with statically differing subscripts cannot alias.
529 * Many common standard C library functions `never access memory or only read
530   memory`_.
531 * Pointers that obviously point to constant globals "``pointToConstantMemory``".
532 * Function calls can not modify or references stack allocations if they never
533   escape from the function that allocates them (a common case for automatic
534   arrays).
535
536 The ``-globalsmodref-aa`` pass
537 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
538
539 This pass implements a simple context-sensitive mod/ref and alias analysis for
540 internal global variables that don't "have their address taken".  If a global
541 does not have its address taken, the pass knows that no pointers alias the
542 global.  This pass also keeps track of functions that it knows never access
543 memory or never read memory.  This allows certain optimizations (e.g. GVN) to
544 eliminate call instructions entirely.
545
546 The real power of this pass is that it provides context-sensitive mod/ref
547 information for call instructions.  This allows the optimizer to know that calls
548 to a function do not clobber or read the value of the global, allowing loads and
549 stores to be eliminated.
550
551 .. note::
552
553   This pass is somewhat limited in its scope (only support non-address taken
554   globals), but is very quick analysis.
555
556 The ``-steens-aa`` pass
557 ^^^^^^^^^^^^^^^^^^^^^^^
558
559 The ``-steens-aa`` pass implements a variation on the well-known "Steensgaard's
560 algorithm" for interprocedural alias analysis.  Steensgaard's algorithm is a
561 unification-based, flow-insensitive, context-insensitive, and field-insensitive
562 alias analysis that is also very scalable (effectively linear time).
563
564 The LLVM ``-steens-aa`` pass implements a "speculatively field-**sensitive**"
565 version of Steensgaard's algorithm using the Data Structure Analysis framework.
566 This gives it substantially more precision than the standard algorithm while
567 maintaining excellent analysis scalability.
568
569 .. note::
570
571   ``-steens-aa`` is available in the optional "poolalloc" module. It is not part
572   of the LLVM core.
573
574 The ``-ds-aa`` pass
575 ^^^^^^^^^^^^^^^^^^^
576
577 The ``-ds-aa`` pass implements the full Data Structure Analysis algorithm.  Data
578 Structure Analysis is a modular unification-based, flow-insensitive,
579 context-**sensitive**, and speculatively field-**sensitive** alias
580 analysis that is also quite scalable, usually at ``O(n * log(n))``.
581
582 This algorithm is capable of responding to a full variety of alias analysis
583 queries, and can provide context-sensitive mod/ref information as well.  The
584 only major facility not implemented so far is support for must-alias
585 information.
586
587 .. note::
588
589   ``-ds-aa`` is available in the optional "poolalloc" module. It is not part of
590   the LLVM core.
591
592 The ``-scev-aa`` pass
593 ^^^^^^^^^^^^^^^^^^^^^
594
595 The ``-scev-aa`` pass implements AliasAnalysis queries by translating them into
596 ScalarEvolution queries. This gives it a more complete understanding of
597 ``getelementptr`` instructions and loop induction variables than other alias
598 analyses have.
599
600 Alias analysis driven transformations
601 -------------------------------------
602
603 LLVM includes several alias-analysis driven transformations which can be used
604 with any of the implementations above.
605
606 The ``-adce`` pass
607 ^^^^^^^^^^^^^^^^^^
608
609 The ``-adce`` pass, which implements Aggressive Dead Code Elimination uses the
610 ``AliasAnalysis`` interface to delete calls to functions that do not have
611 side-effects and are not used.
612
613 The ``-licm`` pass
614 ^^^^^^^^^^^^^^^^^^
615
616 The ``-licm`` pass implements various Loop Invariant Code Motion related
617 transformations.  It uses the ``AliasAnalysis`` interface for several different
618 transformations:
619
620 * It uses mod/ref information to hoist or sink load instructions out of loops if
621   there are no instructions in the loop that modifies the memory loaded.
622
623 * It uses mod/ref information to hoist function calls out of loops that do not
624   write to memory and are loop-invariant.
625
626 * If uses alias information to promote memory objects that are loaded and stored
627   to in loops to live in a register instead.  It can do this if there are no may
628   aliases to the loaded/stored memory location.
629
630 The ``-argpromotion`` pass
631 ^^^^^^^^^^^^^^^^^^^^^^^^^^
632
633 The ``-argpromotion`` pass promotes by-reference arguments to be passed in
634 by-value instead.  In particular, if pointer arguments are only loaded from it
635 passes in the value loaded instead of the address to the function.  This pass
636 uses alias information to make sure that the value loaded from the argument
637 pointer is not modified between the entry of the function and any load of the
638 pointer.
639
640 The ``-gvn``, ``-memcpyopt``, and ``-dse`` passes
641 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
642
643 These passes use AliasAnalysis information to reason about loads and stores.
644
645 .. _the clients:
646
647 Clients for debugging and evaluation of implementations
648 -------------------------------------------------------
649
650 These passes are useful for evaluating the various alias analysis
651 implementations.  You can use them with commands like:
652
653 .. code-block:: bash
654
655   % opt -ds-aa -aa-eval foo.bc -disable-output -stats
656
657 The ``-print-alias-sets`` pass
658 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
659
660 The ``-print-alias-sets`` pass is exposed as part of the ``opt`` tool to print
661 out the Alias Sets formed by the `AliasSetTracker`_ class.  This is useful if
662 you're using the ``AliasSetTracker`` class.  To use it, use something like:
663
664 .. code-block:: bash
665
666   % opt -ds-aa -print-alias-sets -disable-output
667
668 The ``-count-aa`` pass
669 ^^^^^^^^^^^^^^^^^^^^^^
670
671 The ``-count-aa`` pass is useful to see how many queries a particular pass is
672 making and what responses are returned by the alias analysis.  As an example:
673
674 .. code-block:: bash
675
676   % opt -basicaa -count-aa -ds-aa -count-aa -licm
677
678 will print out how many queries (and what responses are returned) by the
679 ``-licm`` pass (of the ``-ds-aa`` pass) and how many queries are made of the
680 ``-basicaa`` pass by the ``-ds-aa`` pass.  This can be useful when debugging a
681 transformation or an alias analysis implementation.
682
683 The ``-aa-eval`` pass
684 ^^^^^^^^^^^^^^^^^^^^^
685
686 The ``-aa-eval`` pass simply iterates through all pairs of pointers in a
687 function and asks an alias analysis whether or not the pointers alias.  This
688 gives an indication of the precision of the alias analysis.  Statistics are
689 printed indicating the percent of no/may/must aliases found (a more precise
690 algorithm will have a lower number of may aliases).
691
692 Memory Dependence Analysis
693 ==========================
694
695 If you're just looking to be a client of alias analysis information, consider
696 using the Memory Dependence Analysis interface instead.  MemDep is a lazy,
697 caching layer on top of alias analysis that is able to answer the question of
698 what preceding memory operations a given instruction depends on, either at an
699 intra- or inter-block level.  Because of its laziness and caching policy, using
700 MemDep can be a significant performance win over accessing alias analysis
701 directly.