X-Git-Url: http://demsky.eecs.uci.edu/git/?a=blobdiff_plain;f=docs%2FProgrammersManual.html;h=950c937824ae2cc2ed802badd7567a36ffcdcd1d;hb=8e28b5c4265ea636e5b737d9352096498be28d3b;hp=a3b54f802b638b171f8e50e8576fcf9ec0096b3b;hpb=c915108e1daba81aa2a4f16d9681a942cbe4f8b5;p=oota-llvm.git diff --git a/docs/ProgrammersManual.html b/docs/ProgrammersManual.html index a3b54f802b6..950c937824a 100644 --- a/docs/ProgrammersManual.html +++ b/docs/ProgrammersManual.html @@ -28,7 +28,7 @@
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).
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<> @@ -312,48 +317,51 @@ file (note that you very rarely have to include this file directly).
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: - -
- if (AllocationInst *AI = dyn_cast<AllocationInst>(Val)) { - ... - } -+ 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: + +
+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 - statement, which is very convenient.
+This form of the if statement effectively combines together a call + to isa<> and a call to cast<> into one + statement, which is very convenient.
-Note that the dyn_cast<> operator, like C++'s - dynamic_cast or Java's instanceof operator, can be abused. - In particular you should not use big chained if/then/else blocks to - check for lots of different variants of classes. If you find yourself - wanting to do this, it is much cleaner and more efficient to use the - InstVisitor class to dispatch over the instruction type directly.
+Note that the dyn_cast<> operator, like C++'s + dynamic_cast<> or Java's instanceof operator, can be + abused. In particular, you should not use big chained if/then/else + blocks to check for lots of different variants of classes. If you find + yourself wanting to do this, it is much cleaner and more efficient to use the + InstVisitor class to dispatch over the instruction type directly.
-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.
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.
These five templates can be used with any classes, whether they have a v-table or not. To add support for these templates, you simply need to add @@ -365,14 +373,14 @@ 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, @@ -385,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 @@ -419,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 @@ -463,27 +509,71 @@ uniform manner with the rest of the passes being executed.
it are as follows:static Statistic<> NumXForms("mypassname", "The # of times I did stuff");+
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).
++NumXForms; // I did stuff+
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 +... statistics 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 @@ -491,6 +581,56 @@ maintainable and useful.
Several of the important data structures in LLVM are graphs: for example +CFGs made out of LLVM BasicBlocks, CFGs made out of +LLVM MachineBasicBlocks, and +Instruction Selection +DAGs. In many cases, while debugging various parts of the compiler, it is +nice to instantly visualize these graphs.
+ +LLVM provides several callbacks that are available in a debug build to do +exactly that. If you call the Function::viewCFG() method, for example, +the current LLVM tool will pop up a window containing the CFG for the function +where each basic block is a node in the graph, and each node contains the +instructions in the block. Similarly, there also exists +Function::viewCFGOnly() (does not include the instructions), the +MachineFunction::viewCFG() and MachineFunction::viewCFGOnly(), +and the SelectionDAG::viewGraph() methods. Within GDB, for example, +you can usually use something like call DAG.viewGraph() to pop +up a window. Alternatively, you can sprinkle calls to these functions in your +code in places you want to debug.
+ +Getting this to work requires a small amount of configuration. On Unix +systems with X11, install the graphviz +toolkit, and make sure 'dot' and 'gv' are in your path. If you are running on +Mac OS/X, download and install the Mac OS/X Graphviz program, and add +/Applications/Graphviz.app/Contents/MacOS/ (or whereever you install +it) to your path. Once in your system and path are set up, rerun the LLVM +configure script and rebuild LLVM to enable this functionality.
+ +SelectionDAG has been extended to make it easier to locate +interesting nodes in large complex graphs. From gdb, if you +call DAG.setGraphColor(node, "color"), then the +next call DAG.viewGraph() would hilight the node in the +specified color (choices of colors can be found at Colors.) More +complex node attributes can be provided with call +DAG.setGraphAttrs(node, "attributes") (choices can be +found at Graph +Attributes.) If you want to restart and clear all the current graph +attributes, then you can call DAG.clearGraphAttrs().
+ +// 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
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 @@ -573,13 +722,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 @@ -604,12 +755,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"-Easy, isn't it? You can also use InstIterators to fill a +
...
// Suppose F is a ptr to a function
for (inst_iterator i = inst_begin(F), e = inst_end(F); i != e; ++i)
cerr << *i << "\n";
+#include "llvm/Support/InstIterator.h" + +// F is a ptr to a Function instance +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;+F, all you would need to do is something like: + +
worklist.insert(inst_begin(F), inst_end(F));
+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.
@@ -630,7 +796,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 @@ -640,11 +812,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 @@ -652,7 +832,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()) 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"; +} ++
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; +}; ++
Function* F = ...;+
for (Value::use_iterator i = F->use_begin(), e = F->use_end(); i != e; ++i) {
if (Instruction *Inst = dyn_cast<Instruction>(*i)) {
cerr << "F is used in instruction:\n";
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 @@ -737,7 +970,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; + // ... +} ++
Constant represents a base class for different types of constants. It -is subclassed by ConstantBool, ConstantInt, ConstantSInt, ConstantUInt, -ConstantArray etc for representing the various types of Constants.
+is subclassed by ConstantBool, ConstantInt, ConstantArray etc for representing +the various types of Constants.