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