Move processGraph down lower in the file so all of the forward declarations
[oota-llvm.git] / lib / Transforms / Instrumentation / TraceValues.cpp
1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
2 //
3 // Support for inserting LLVM code to print values at basic block and method
4 // exits.
5 //
6 //===----------------------------------------------------------------------===//
7
8 #include "llvm/Transforms/Instrumentation/TraceValues.h"
9 #include "llvm/GlobalVariable.h"
10 #include "llvm/ConstantVals.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Method.h"
16 #include "llvm/Module.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Assembly/Writer.h"
19 #include "Support/StringExtras.h"
20 #include <sstream>
21 using std::vector;
22 using std::string;
23
24 // Add a prototype for printf if it is not already in the program.
25 //
26 bool InsertTraceCode::doInitialization(Module *M) {
27   SymbolTable *ST = M->getSymbolTable();
28   const Type *SBP = PointerType::get(Type::SByteTy);
29   const MethodType *MTy =
30     MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
31
32   if (Value *Meth = ST->lookup(PointerType::get(MTy), "printf")) {
33     PrintfMeth = cast<Method>(Meth);
34     return false;
35   }
36
37   // Create a new method and add it to the module
38   PrintfMeth = new Method(MTy, false, "printf");
39   M->getMethodList().push_back(PrintfMeth);
40   return true;
41 }
42
43
44 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
45   // Create a constant internal string reference...
46   Constant *Init = ConstantArray::get(str);
47   GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
48                                           "trstr");
49   M->getGlobalList().push_back(GV);
50   return GV;
51 }
52
53
54 // 
55 // Check if this instruction has any uses outside its basic block,
56 // or if it used by either a Call or Return instruction.
57 // 
58 static inline bool LiveAtBBExit(const Instruction* I) {
59   const BasicBlock *BB = I->getParent();
60   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
61     if (const Instruction *UI = dyn_cast<Instruction>(*U))
62       if (UI->getParent() != BB || isa<ReturnInst>(UI))
63         return true;
64
65   return false;
66 }
67
68
69 static inline bool TraceThisOpCode(unsigned opCode) {
70   // Explicitly test for opCodes *not* to trace so that any new opcodes will
71   // be traced by default (VoidTy's are already excluded)
72   // 
73   return (opCode  < Instruction::FirstOtherOp &&
74           opCode != Instruction::Alloca &&
75           opCode != Instruction::PHINode &&
76           opCode != Instruction::Cast);
77 }
78
79
80 static bool ShouldTraceValue(const Instruction *I) {
81   return
82     I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
83     TraceThisOpCode(I->getOpcode());
84 }
85
86 static string getPrintfCodeFor(const Value *V) {
87   if (V == 0) return "";
88   switch (V->getType()->getPrimitiveID()) {
89   case Type::BoolTyID:
90   case Type::UByteTyID: case Type::UShortTyID:
91   case Type::UIntTyID:  case Type::ULongTyID:
92   case Type::SByteTyID: case Type::ShortTyID:
93   case Type::IntTyID:   case Type::LongTyID:
94     return "%d";
95     
96   case Type::FloatTyID: case Type::DoubleTyID:
97     return "%g";
98
99   case Type::LabelTyID: case Type::PointerTyID:
100     return "%p";
101     
102   default:
103     assert(0 && "Illegal value to print out...");
104     return "";
105   }
106 }
107
108
109 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
110                             string Message, Method *Printf) {
111   // Escape Message by replacing all % characters with %% chars.
112   unsigned Offset = 0;
113   while ((Offset = Message.find('%', Offset)) != string::npos) {
114     Message.replace(Offset, 2, "%%");
115     Offset += 2;  // Skip over the new %'s
116   }
117
118   Module *Mod = BB->getParent()->getParent();
119
120   // Turn the marker string into a global variable...
121   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
122
123   // Turn the format string into an sbyte *
124   Instruction *GEP = 
125     new GetElementPtrInst(fmtVal,
126                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
127                           "trstr");
128   BBI = BB->getInstList().insert(BBI, GEP)+1;
129   
130   // Insert the first print instruction to print the string flag:
131   vector<Value*> PrintArgs;
132   PrintArgs.push_back(GEP);
133   if (V) PrintArgs.push_back(V);
134   Instruction *I = new CallInst(Printf, PrintArgs, "trace");
135   BBI = BB->getInstList().insert(BBI, I)+1;
136 }
137                             
138
139 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
140                                    BasicBlock::iterator &BBI,
141                                    const string &Message, Method *Printf) {
142   std::ostringstream OutStr;
143   if (V) WriteAsOperand(OutStr, V);
144   InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
145 }
146
147
148 // Insert print instructions at the end of the basic block *bb
149 // for each value in valueVec[] that is live at the end of that basic block,
150 // or that is stored to memory in this basic block.
151 // If the value is stored to memory, we load it back before printing
152 // We also return all such loaded values in the vector valuesStoredInMethod
153 // for printing at the exit from the method.  (Note that in each invocation
154 // of the method, this will only get the last value stored for each static
155 // store instruction).
156 // *bb must be the block in which the value is computed;
157 // this is not checked here.
158 // 
159 static void TraceValuesAtBBExit(BasicBlock *BB, Method *Printf,
160                                 vector<Instruction*> *valuesStoredInMethod) {
161   // Get an iterator to point to the insertion location, which is
162   // just before the terminator instruction.
163   // 
164   BasicBlock::iterator InsertPos = BB->end()-1;
165   assert((*InsertPos)->isTerminator());
166   
167   // If the terminator is a conditional branch, insert the trace code just
168   // before the instruction that computes the branch condition (just to
169   // avoid putting a call between the CC-setting instruction and the branch).
170   // Use laterInstrSet to mark instructions that come after the setCC instr
171   // because those cannot be traced at the location we choose.
172   // 
173   Instruction *SetCC = 0;
174   if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
175     if (!Branch->isUnconditional())
176       if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
177         if (I->getParent() == BB) {
178           SetCC = I;
179           while (*InsertPos != SetCC)
180             --InsertPos;        // Back up until we can insert before the setcc
181         }
182
183   // Copy all of the instructions into a vector to avoid problems with Setcc
184   const vector<Instruction*> Insts(BB->begin(), InsertPos);
185
186   std::ostringstream OutStr;
187   WriteAsOperand(OutStr, BB, false);
188   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
189
190   // Insert a print instruction for each value.
191   // 
192   for (vector<Instruction*>::const_iterator II = Insts.begin(),
193          IE = Insts.end(); II != IE; ++II) {
194     Instruction *I = *II;
195     if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
196       assert(valuesStoredInMethod &&
197              "Should not be printing a store instruction at method exit");
198       LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
199                                   "reload");
200       InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
201       valuesStoredInMethod->push_back(LI);
202     }
203     if (ShouldTraceValue(I))
204       InsertVerbosePrintInst(I, BB, InsertPos, "  ", Printf);
205   }
206 }
207
208 static inline void InsertCodeToShowMethodEntry(Method *M, Method *Printf) {
209   // Get an iterator to point to the insertion location
210   BasicBlock *BB = M->getEntryNode();
211   BasicBlock::iterator BBI = BB->begin();
212
213   std::ostringstream OutStr;
214   WriteAsOperand(OutStr, M, true);
215   InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
216
217   // Now print all the incoming arguments
218   const Method::ArgumentListType &argList = M->getArgumentList();
219   unsigned ArgNo = 0;
220   for (Method::ArgumentListType::const_iterator
221          I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
222     InsertVerbosePrintInst(*I, BB, BBI,
223                            "  Arg #" + utostr(ArgNo), Printf);
224   }
225 }
226
227
228 static inline void InsertCodeToShowMethodExit(BasicBlock *BB, Method *Printf) {
229   // Get an iterator to point to the insertion location
230   BasicBlock::iterator BBI = BB->end()-1;
231   ReturnInst *Ret = cast<ReturnInst>(*BBI);
232   
233   std::ostringstream OutStr;
234   WriteAsOperand(OutStr, BB->getParent(), true);
235   InsertPrintInst(0, BB, BBI, "LEAVING  METHOD: " + OutStr.str(), Printf);
236   
237   // print the return value, if any
238   if (BB->getParent()->getReturnType() != Type::VoidTy)
239     InsertPrintInst(Ret->getReturnValue(), BB, BBI, "  Returning: ", Printf);
240 }
241
242
243 bool InsertTraceCode::doit(Method *M, bool traceBasicBlockExits,
244                            bool traceMethodEvents, Method *Printf) {
245   if (!traceBasicBlockExits && !traceMethodEvents)
246     return false;
247
248   vector<Instruction*> valuesStoredInMethod;
249   vector<BasicBlock*>  exitBlocks;
250
251   if (traceMethodEvents)
252     InsertCodeToShowMethodEntry(M, Printf);
253   
254   for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {
255     BasicBlock *BB = *BI;
256     if (isa<ReturnInst>(BB->getTerminator()))
257       exitBlocks.push_back(BB); // record this as an exit block
258     
259     if (traceBasicBlockExits)
260       TraceValuesAtBBExit(BB, Printf, &valuesStoredInMethod);
261   }
262
263   if (traceMethodEvents)
264     for (unsigned i=0; i < exitBlocks.size(); ++i) {
265 #if 0
266       TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
267                           /*indent*/ 0, /*isMethodExit*/ true,
268                           /*valuesStoredInMethod*/ NULL);
269 #endif
270       InsertCodeToShowMethodExit(exitBlocks[i], Printf);
271     }
272
273   return true;
274 }