From 3cd5ca6c72787fa4e5fd2b8d880545f8863f35d1 Mon Sep 17 00:00:00 2001 From: Bill Wendling Date: Wed, 11 Oct 2006 06:30:10 +0000 Subject: [PATCH] Put code example inside of "doc_code" divisions. git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@30876 91177308-0d34-0410-b5e6-96231b3b80d8 --- docs/CodeGenerator.html | 27 ++- docs/ProgrammersManual.html | 450 +++++++++++++++++++++++++++++++++++--------- 2 files changed, 377 insertions(+), 100 deletions(-) diff --git a/docs/CodeGenerator.html b/docs/CodeGenerator.html index 405c57b3458..ebee043315f 100644 --- a/docs/CodeGenerator.html +++ b/docs/CodeGenerator.html @@ -1227,7 +1227,16 @@ defining instruction is encountered.

-

To Be Written

+ +

We now have the information available to perform the liver intervals analysis +and build the live intervals themselves. We start off by numbering the basic +blocks and machine instructions. We then handle the "live-in" values. These +are in physical registers, so the physical register is assumed to be killed by +the end of the basic block. Live intervals for virtual registers are computed +for some ordering of the machine instructions [1,N]. A live interval +is an interval [i,j), where 1 <= i <= j < N, for which a +variable is live.

+
@@ -1239,14 +1248,14 @@ defining instruction is encountered.

-

The Register Allocation problem consists in mapping a -program Pv, that can use an unbounded number of -virtual registers, to a program Pp that contains a -finite (possibly small) number of physical registers. Each target -architecture has a different number of physical registers. If the -number of physical registers is not enough to accommodate all the -virtual registers, some of them will have to be mapped into -memory. These virtuals are called spilled virtuals.

+

The Register Allocation problem consists in mapping a program +Pv, that can use an unbounded number of virtual +registers, to a program Pp that contains a finite +(possibly small) number of physical registers. Each target architecture has +a different number of physical registers. If the number of physical +registers is not enough to accommodate all the virtual registers, some of +them will have to be mapped into memory. These virtuals are called +spilled virtuals.

diff --git a/docs/ProgrammersManual.html b/docs/ProgrammersManual.html index d16cff81dc0..b4159bf39e1 100644 --- a/docs/ProgrammersManual.html +++ b/docs/ProgrammersManual.html @@ -282,29 +282,32 @@ file (note that you very rarely have to include this file directly).

isa<>:
-
The isa<> operator works exactly like the Java +

The isa<> operator works exactly like the Java "instanceof" operator. It returns true or false depending on whether a reference or pointer points to an instance of the specified class. This can - be very useful for constraint checking of various sorts (example below).

+ be very useful for constraint checking of various sorts (example below).

+
cast<>:
-
The cast<> operator is a "checked cast" operation. It +

The cast<> operator is a "checked cast" operation. It converts a pointer or reference from a base class to a derived cast, causing an assertion failure if it is not really an instance of the right type. This should be used in cases where you have some information that makes you believe that something is of the right type. An example of the isa<> - and cast<> template is: + and cast<> template is:

-
-  static bool isLoopInvariant(const Value *V, const Loop *L) {
-    if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
-      return true;
+
+
+static bool isLoopInvariant(const Value *V, const Loop *L) {
+  if (isa<Constant>(V) || isa<Argument>(V) || isa<GlobalValue>(V))
+    return true;
 
-    // Otherwise, it must be an instruction...
-    return !L->contains(cast<Instruction>(V)->getParent());
-  }
-  
+ // Otherwise, it must be an instruction... + return !L->contains(cast<Instruction>(V)->getParent()); +} +
+

Note that you should not use an isa<> test followed by a cast<>, for that use the dyn_cast<> @@ -314,20 +317,22 @@ file (note that you very rarely have to include this file directly).

dyn_cast<>:
-
The dyn_cast<> operator is a "checking cast" operation. It - checks to see if the operand is of the specified type, and if so, returns a +

The dyn_cast<> operator is a "checking cast" operation. + It checks to see if the operand is of the specified type, and if so, returns a pointer to it (this operator does not work with references). If the operand is not of the correct type, a null pointer is returned. Thus, this works very much like the dynamic_cast<> operator in C++, and should be used in the same circumstances. Typically, the dyn_cast<> operator is used in an if statement or some other flow control - statement like this: + statement like this:

-
-     if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) {
-       ...
-     }
-  
+
+
+if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) {
+  // ...
+}
+
+

This form of the if statement effectively combines together a call to isa<> and a call to cast<> into one @@ -344,17 +349,17 @@ file (note that you very rarely have to include this file directly).

cast_or_null<>:
-
The cast_or_null<> operator works just like the +

The cast_or_null<> operator works just like the cast<> operator, except that it allows for a null pointer as an argument (which it then propagates). This can sometimes be useful, allowing - you to combine several null checks into one.

+ you to combine several null checks into one.

dyn_cast_or_null<>:
-
The dyn_cast_or_null<> operator works just like the +

The dyn_cast_or_null<> operator works just like the dyn_cast<> operator, except that it allows for a null pointer as an argument (which it then propagates). This can sometimes be useful, - allowing you to combine several null checks into one.

+ allowing you to combine several null checks into one.

@@ -375,7 +380,7 @@ are lots of examples in the LLVM source base.

Often when working on your pass you will put a bunch of debugging printouts and other code into your pass. After you get it working, you want to remove -it... but you may need it again in the future (to work out new bugs that you run +it, but you may need it again in the future (to work out new bugs that you run across).

Naturally, because of this, you don't want to delete the debug printouts, @@ -388,11 +393,22 @@ this problem. Basically, you can put arbitrary code into the argument of the DEBUG macro, and it is only executed if 'opt' (or any other tool) is run with the '-debug' command line argument:

-
     ... 
DEBUG(std::cerr << "I am here!\n");
...
+
+
+DEBUG(std::cerr << "I am here!\n");
+
+

Then you can run your pass like this:

-
  $ opt < a.bc > /dev/null -mypass
<no output>
$ opt < a.bc > /dev/null -mypass -debug
I am here!
$
+
+
+$ opt < a.bc > /dev/null -mypass
+<no output>
+$ opt < a.bc > /dev/null -mypass -debug
+I am here!
+
+

Using the DEBUG() macro instead of a home-brewed solution allows you to not have to create "yet another" command line option for the debug output for @@ -422,11 +438,38 @@ generator). If you want to enable debug information with more fine-grained control, you define the DEBUG_TYPE macro and the -debug only option as follows:

-
     ...
DEBUG(std::cerr << "No debug type\n");
#undef DEBUG_TYPE
#define DEBUG_TYPE "foo"
DEBUG(std::cerr << "'foo' debug type\n");
#undef DEBUG_TYPE
#define DEBUG_TYPE "bar"
DEBUG(std::cerr << "'bar' debug type\n");
#undef DEBUG_TYPE
#define DEBUG_TYPE ""
DEBUG(std::cerr << "No debug type (2)\n");
...
+
+
+DEBUG(std::cerr << "No debug type\n");
+#undef  DEBUG_TYPE
+#define DEBUG_TYPE "foo"
+DEBUG(std::cerr << "'foo' debug type\n");
+#undef  DEBUG_TYPE
+#define DEBUG_TYPE "bar"
+DEBUG(std::cerr << "'bar' debug type\n");
+#undef  DEBUG_TYPE
+#define DEBUG_TYPE ""
+DEBUG(std::cerr << "No debug type (2)\n");
+
+

Then you can run your pass like this:

-
  $ opt < a.bc > /dev/null -mypass
<no output>
$ opt < a.bc > /dev/null -mypass -debug
No debug type
'foo' debug type
'bar' debug type
No debug type (2)
$ opt < a.bc > /dev/null -mypass -debug-only=foo
'foo' debug type
$ opt < a.bc > /dev/null -mypass -debug-only=bar
'bar' debug type
$
+
+
+$ opt < a.bc > /dev/null -mypass
+<no output>
+$ opt < a.bc > /dev/null -mypass -debug
+No debug type
+'foo' debug type
+'bar' debug type
+No debug type (2)
+$ opt < a.bc > /dev/null -mypass -debug-only=foo
+'foo' debug type
+$ opt < a.bc > /dev/null -mypass -debug-only=bar
+'bar' debug type
+
+

Of course, in practice, you should only set DEBUG_TYPE at the top of a file, to specify the debug type for the entire module (if you do this before @@ -466,27 +509,71 @@ uniform manner with the rest of the passes being executed.

it are as follows:

    -
  1. Define your statistic like this: -
    static Statistic<> NumXForms("mypassname", "The # of times I did stuff");
    +
  2. Define your statistic like this:

    + +
    +
    +static Statistic<> NumXForms("mypassname", "The # of times I did stuff");
    +
    +

    The Statistic template can emulate just about any data-type, but if you do not specify a template argument, it defaults to acting like an unsigned int counter (this is usually what you want).

  3. -
  4. Whenever you make a transformation, bump the counter: -
       ++NumXForms;   // I did stuff
    +
  5. Whenever you make a transformation, bump the counter:

    + +
    +
    +++NumXForms;   // I did stuff!
    +
    +
    +

That's all you have to do. To get 'opt' to print out the statistics gathered, use the '-stats' option:

-
   $ opt -stats -mypassname < program.bc > /dev/null
... statistic output ...
+
+
+$ opt -stats -mypassname < program.bc > /dev/null
+... statistic output ...
+
+

When running gccas on a C file from the SPEC benchmark suite, it gives a report that looks like this:

-
   7646 bytecodewriter  - Number of normal instructions
725 bytecodewriter - Number of oversized instructions
129996 bytecodewriter - Number of bytecode bytes written
2817 raise - Number of insts DCEd or constprop'd
3213 raise - Number of cast-of-self removed
5046 raise - Number of expression trees converted
75 raise - Number of other getelementptr's formed
138 raise - Number of load/store peepholes
42 deadtypeelim - Number of unused typenames removed from symtab
392 funcresolve - Number of varargs functions resolved
27 globaldce - Number of global variables removed
2 adce - Number of basic blocks removed
134 cee - Number of branches revectored
49 cee - Number of setcc instruction eliminated
532 gcse - Number of loads removed
2919 gcse - Number of instructions removed
86 indvars - Number of canonical indvars added
87 indvars - Number of aux indvars removed
25 instcombine - Number of dead inst eliminate
434 instcombine - Number of insts combined
248 licm - Number of load insts hoisted
1298 licm - Number of insts hoisted to a loop pre-header
3 licm - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
75 mem2reg - Number of alloca's promoted
1444 cfgsimplify - Number of blocks simplified
+
+
+   7646 bytecodewriter  - Number of normal instructions
+    725 bytecodewriter  - Number of oversized instructions
+ 129996 bytecodewriter  - Number of bytecode bytes written
+   2817 raise           - Number of insts DCEd or constprop'd
+   3213 raise           - Number of cast-of-self removed
+   5046 raise           - Number of expression trees converted
+     75 raise           - Number of other getelementptr's formed
+    138 raise           - Number of load/store peepholes
+     42 deadtypeelim    - Number of unused typenames removed from symtab
+    392 funcresolve     - Number of varargs functions resolved
+     27 globaldce       - Number of global variables removed
+      2 adce            - Number of basic blocks removed
+    134 cee             - Number of branches revectored
+     49 cee             - Number of setcc instruction eliminated
+    532 gcse            - Number of loads removed
+   2919 gcse            - Number of instructions removed
+     86 indvars         - Number of canonical indvars added
+     87 indvars         - Number of aux indvars removed
+     25 instcombine     - Number of dead inst eliminate
+    434 instcombine     - Number of insts combined
+    248 licm            - Number of load insts hoisted
+   1298 licm            - Number of insts hoisted to a loop pre-header
+      3 licm            - Number of insts hoisted to multiple loop preds (bad, no loop pre-header)
+     75 mem2reg         - Number of alloca's promoted
+   1444 cfgsimplify     - Number of blocks simplified
+
+

Obviously, with so many optimizations, having a unified framework for this stuff is very nice. Making your pass fit well into the framework makes it more @@ -602,7 +689,17 @@ the BasicBlocks that constitute the Function. The following is an example that prints the name of a BasicBlock and the number of Instructions it contains:

-
  // func is a pointer to a Function instance
for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i) {

// print out the name of the basic block if it has one, and then the
// number of instructions that it contains

std::cerr << "Basic block (name=" << i->getName() << ") has "
<< i->size() << " instructions.\n";
}
+
+
+// func is a pointer to a Function instance
+for (Function::iterator i = func->begin(), e = func->end(); i != e; ++i) {
+  // print out the name of the basic block if it has one, and then the
+  // number of instructions that it contains
+  std::cerr << "Basic block (name=" << i->getName() << ") has "
+            << i->size() << " instructions.\n";
+}
+
+

Note that i can be used as if it were a pointer for the purposes of invoking member functions of the Instruction class. This is @@ -626,13 +723,15 @@ easy to iterate over the individual instructions that make up BasicBlocks. Here's a code snippet that prints out each instruction in a BasicBlock:

+
-  // blk is a pointer to a BasicBlock instance
-  for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i)
-     // the next statement works since operator<<(ostream&,...)
-     // is overloaded for Instruction&
-     std::cerr << *i << "\n";
+// blk is a pointer to a BasicBlock instance
+for (BasicBlock::iterator i = blk->begin(), e = blk->end(); i != e; ++i)
+   // the next statement works since operator<<(ostream&,...)
+   // is overloaded for Instruction&
+   std::cerr << *i << "\n";
 
+

However, this isn't really the best way to print out the contents of a BasicBlock! Since the ostream operators are overloaded for virtually @@ -657,12 +756,27 @@ href="/doxygen/InstIterator_8h-source.html">llvm/Support/InstIterator.h and then instantiate InstIterators explicitly in your code. Here's a small example that shows how to dump all instructions in a function to the standard error stream:

-

#include "llvm/Support/InstIterator.h"
...
// Suppose F is a ptr to a function
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
std::cerr << *i << "\n";
-Easy, isn't it? You can also use InstIterators to fill a +
+
+#include "llvm/Support/InstIterator.h"
+
+// Suppose F is a ptr to a function
+for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
+  std::cerr << *i << "\n";
+
+
+ +

Easy, isn't it? You can also use InstIterators to fill a worklist with its initial contents. For example, if you wanted to initialize a worklist to contain all instructions in a Function -F, all you would need to do is something like: -

std::set<Instruction*> worklist;
worklist.insert(inst_begin(F), inst_end(F));
+F, all you would need to do is something like:

+ +
+
+std::set<Instruction*> worklist;
+worklist.insert(inst_begin(F), inst_end(F));
+
+

The STL set worklist would now contain all instructions in the Function pointed to by F.

@@ -683,7 +797,13 @@ a reference or a pointer from an iterator is very straight-forward. Assuming that i is a BasicBlock::iterator and j is a BasicBlock::const_iterator:

-
    Instruction& inst = *i;   // grab reference to instruction reference
Instruction* pinst = &*i; // grab pointer to instruction reference
const Instruction& inst = *j;
+
+
+Instruction& inst = *i;   // grab reference to instruction reference
+Instruction* pinst = &*i; // grab pointer to instruction reference
+const Instruction& inst = *j;
+
+

However, the iterators you'll be working with in the LLVM framework are special: they will automatically convert to a ptr-to-instance type whenever they @@ -693,11 +813,19 @@ you get the dereference and address-of operation as a result of the assignment (behind the scenes, this is a result of overloading casting mechanisms). Thus the last line of the last example,

-
Instruction* pinst = &*i;
+
+
+Instruction* pinst = &*i;
+
+

is semantically equivalent to

-
Instruction* pinst = i;
+
+
+Instruction* pinst = i;
+
+

It's also possible to turn a class pointer into the corresponding iterator, and this is a constant time operation (very efficient). The following code @@ -705,7 +833,15 @@ snippet illustrates use of the conversion constructors provided by LLVM iterators. By using these, you can explicitly grab the iterator of something without actually obtaining it via iteration over some structure:

-
void printNextInstruction(Instruction* inst) {
BasicBlock::iterator it(inst);
++it; // after this line, it refers to the instruction after *inst.
if (it != inst->getParent()->end()) std::cerr << *it << "\n";
}
+
+
+void printNextInstruction(Instruction* inst) {
+  BasicBlock::iterator it(inst);
+  ++it; // after this line, it refers to the instruction after *inst.
+  if (it != inst->getParent()->end()) std::cerr << *it << "\n";
+}
+
+
@@ -725,15 +861,50 @@ much more straight-forward manner, but this example will allow us to explore how you'd do it if you didn't have InstVisitor around. In pseudocode, this is what we want to do:

-
initialize callCounter to zero
for each Function f in the Module
for each BasicBlock b in f
for each Instruction i in b
if (i is a CallInst and calls the given function)
increment callCounter
+
+
+initialize callCounter to zero
+for each Function f in the Module
+  for each BasicBlock b in f
+    for each Instruction i in b
+      if (i is a CallInst and calls the given function)
+        increment callCounter
+
+
-

And the actual code is (remember, since we're writing a +

And the actual code is (remember, because we're writing a FunctionPass, our FunctionPass-derived class simply has to -override the runOnFunction method...):

+override the runOnFunction method):

-
Function* targetFunc = ...;

class OurFunctionPass : public FunctionPass {
public:
OurFunctionPass(): callCounter(0) { }

virtual runOnFunction(Function& F) {
for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) {
if (CallInst* callInst = dyn_cast<CallInst>(&*i)) {
// we know we've encountered a call instruction, so we
// need to determine if it's a call to the
// function pointed to by m_func or not.

if (callInst->getCalledFunction() == targetFunc)
++callCounter;
}
}
}

private:
unsigned callCounter;
};
+
+
+Function* targetFunc = ...;
+
+class OurFunctionPass : public FunctionPass {
+  public:
+    OurFunctionPass(): callCounter(0) { }
+
+    virtual runOnFunction(Function& F) {
+      for (Function::iterator b = F.begin(), be = F.end(); b != be; ++b) {
+        for (BasicBlock::iterator i = b->begin(); ie = b->end(); i != ie; ++i) {
+          if (CallInst* callInst = dyn_cast<CallInst>(&*i)) {
+            // we know we've encountered a call instruction, so we
+            // need to determine if it's a call to the
+            // function pointed to by m_func or not.
+
+            if (callInst->getCalledFunction() == targetFunc)
+              ++callCounter;
+          }
+        }
+      }
+
+
+  private:
+    unsigned  callCounter;
+};
+
+
@@ -780,7 +951,18 @@ particular function foo. Finding all of the instructions that use foo is as simple as iterating over the def-use chain of F:

-
Function* F = ...;

for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {
if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
std::cerr << "F is used in instruction:\n";
std::cerr << *Inst << "\n";
}
}
+
+
+Function* F = ...;
+
+for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {
+  if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
+    std::cerr << "F is used in instruction:\n";
+    std::cerr << *Inst << "\n";
+  }
+}
+
+

Alternately, it's common to have an instance of the User Class and need to know what @@ -790,7 +972,16 @@ href="/doxygen/classllvm_1_1User.html">User Class and need to know what all of the values that a particular instruction uses (that is, the operands of the particular Instruction):

-
Instruction* pi = ...;

for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) {
Value* v = *i;
...
}
+
+
+Instruction* pi = ...;
+
+for (User::op_iterator i = pi->op_begin(), e = pi->op_end(); i != e; ++i) {
+  Value* v = *i;
+  ...
+}
+
+