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