Implement capability to fold this:
[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/Constants.h"
11 #include "llvm/DerivedTypes.h"
12 #include "llvm/iMemory.h"
13 #include "llvm/iTerminators.h"
14 #include "llvm/iOther.h"
15 #include "llvm/Module.h"
16 #include "llvm/Pass.h"
17 #include "llvm/Assembly/Writer.h"
18 #include "Support/CommandLine.h"
19 #include "Support/StringExtras.h"
20 #include <algorithm>
21 #include <sstream>
22 using std::vector;
23 using std::string;
24
25 static cl::opt<bool>
26 DisablePtrHashing("tracedisablehashdisable", cl::Hidden,
27                   cl::desc("Disable pointer hashing"));
28
29 static cl::list<string>
30 TraceFuncName("tracefunc", cl::desc("trace only specific functions"),
31               cl::value_desc("function"), cl::Hidden);
32
33 static void TraceValuesAtBBExit(BasicBlock *BB,
34                                 Function *Printf, Function* HashPtrToSeqNum,
35                                 vector<Instruction*> *valuesStoredInFunction);
36
37 // We trace a particular function if no functions to trace were specified
38 // or if the function is in the specified list.
39 // 
40 inline static bool
41 TraceThisFunction(Function &func)
42 {
43   if (TraceFuncName.size() == 0)
44     return true;
45
46   return std::find(TraceFuncName.begin(), TraceFuncName.end(), func.getName())
47                   != TraceFuncName.end();
48 }
49
50
51 namespace {
52   struct ExternalFuncs {
53     Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
54     Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
55     void doInitialization(Module &M); // Add prototypes for external functions
56   };
57   
58   class InsertTraceCode : public FunctionPass {
59   protected:
60     ExternalFuncs externalFuncs;
61   public:
62     
63     // Add a prototype for runtime functions not already in the program.
64     //
65     bool doInitialization(Module &M);
66     
67     //--------------------------------------------------------------------------
68     // Function InsertCodeToTraceValues
69     // 
70     // Inserts tracing code for all live values at basic block and/or function
71     // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
72     //
73     bool doit(Function *M);
74
75     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) = 0;
76
77     // runOnFunction - This method does the work.
78     //
79     bool runOnFunction(Function &F);
80
81     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
82       AU.preservesCFG();
83     }
84   };
85
86   struct FunctionTracer : public InsertTraceCode {
87     // Ignore basic blocks here...
88     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {}
89   };
90
91   struct BasicBlockTracer : public InsertTraceCode {
92     // Trace basic blocks here...
93     virtual void handleBasicBlock(BasicBlock *BB, vector<Instruction*> &VI) {
94       TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
95                           externalFuncs.HashPtrFunc, &VI);
96     }
97   };
98
99   // Register the passes...
100   RegisterOpt<FunctionTracer>  X("tracem","Insert Function trace code only");
101   RegisterOpt<BasicBlockTracer> Y("trace","Insert BB and Function trace code");
102 } // end anonymous namespace
103
104
105 Pass *createTraceValuesPassForFunction() {     // Just trace functions
106   return new FunctionTracer();
107 }
108
109 Pass *createTraceValuesPassForBasicBlocks() {  // Trace BB's and functions
110   return new BasicBlockTracer();
111 }
112
113
114 // Add a prototype for external functions used by the tracing code.
115 //
116 void ExternalFuncs::doInitialization(Module &M) {
117   const Type *SBP = PointerType::get(Type::SByteTy);
118   const FunctionType *MTy =
119     FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
120   PrintfFunc = M.getOrInsertFunction("printf", MTy);
121
122   // uint (sbyte*)
123   const FunctionType *hashFuncTy =
124     FunctionType::get(Type::UIntTy, vector<const Type*>(1, SBP), false);
125   HashPtrFunc = M.getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
126   
127   // void (sbyte*)
128   const FunctionType *voidSBPFuncTy =
129     FunctionType::get(Type::VoidTy, vector<const Type*>(1, SBP), false);
130   
131   ReleasePtrFunc = M.getOrInsertFunction("ReleasePointerSeqNum", voidSBPFuncTy);
132   RecordPtrFunc  = M.getOrInsertFunction("RecordPointer", voidSBPFuncTy);
133   
134   const FunctionType *voidvoidFuncTy =
135     FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
136   
137   PushOnEntryFunc = M.getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
138   ReleaseOnReturnFunc = M.getOrInsertFunction("ReleasePointersPopSet",
139                                                voidvoidFuncTy);
140 }
141
142
143 // Add a prototype for external functions used by the tracing code.
144 //
145 bool InsertTraceCode::doInitialization(Module &M) {
146   externalFuncs.doInitialization(M);
147   return false;
148 }
149
150
151 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
152   // Create a constant internal string reference...
153   Constant *Init = ConstantArray::get(str);
154
155   // Create the global variable and record it in the module
156   // The GV will be renamed to a unique name if needed.
157   GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
158                                           "trstr");
159   M->getGlobalList().push_back(GV);
160   return GV;
161 }
162
163
164 // 
165 // Check if this instruction has any uses outside its basic block,
166 // or if it used by either a Call or Return instruction.
167 // 
168 static inline bool LiveAtBBExit(const Instruction* I) {
169   const BasicBlock *BB = I->getParent();
170   for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
171     if (const Instruction *UI = dyn_cast<Instruction>(*U))
172       if (UI->getParent() != BB || isa<ReturnInst>(UI))
173         return true;
174
175   return false;
176 }
177
178
179 static inline bool TraceThisOpCode(unsigned opCode) {
180   // Explicitly test for opCodes *not* to trace so that any new opcodes will
181   // be traced by default (VoidTy's are already excluded)
182   // 
183   return (opCode  < Instruction::FirstOtherOp &&
184           opCode != Instruction::Alloca &&
185           opCode != Instruction::PHINode &&
186           opCode != Instruction::Cast);
187 }
188
189
190 static bool ShouldTraceValue(const Instruction *I) {
191   return
192     I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
193     TraceThisOpCode(I->getOpcode());
194 }
195
196 static string getPrintfCodeFor(const Value *V) {
197   if (V == 0) return "";
198   if (V->getType()->isFloatingPoint())
199     return "%g";
200   else if (V->getType() == Type::LabelTy)
201     return "0x%p";
202   else if (isa<PointerType>(V->getType()))
203     return DisablePtrHashing ? "0x%p" : "%d";
204   else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
205     return "%d";
206   
207   assert(0 && "Illegal value to print out...");
208   return "";
209 }
210
211
212 static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
213                             string Message,
214                             Function *Printf, Function* HashPtrToSeqNum) {
215   // Escape Message by replacing all % characters with %% chars.
216   unsigned Offset = 0;
217   while ((Offset = Message.find('%', Offset)) != string::npos) {
218     Message.replace(Offset, 1, "%%");
219     Offset += 2;  // Skip over the new %'s
220   }
221
222   Module *Mod = BB->getParent()->getParent();
223
224   // Turn the marker string into a global variable...
225   GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
226
227   // Turn the format string into an sbyte *
228   Instruction *GEP = 
229     new GetElementPtrInst(fmtVal,
230                           vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
231                           "trstr");
232   BBI = ++BB->getInstList().insert(BBI, GEP);
233   
234   // Insert a call to the hash function if this is a pointer value
235   if (V && isa<PointerType>(V->getType()) && !DisablePtrHashing) {
236     const Type *SBP = PointerType::get(Type::SByteTy);
237     if (V->getType() != SBP) {   // Cast pointer to be sbyte*
238       Instruction *I = new CastInst(V, SBP, "Hash_cast");
239       BBI = ++BB->getInstList().insert(BBI, I);
240       V = I;
241     }
242
243     vector<Value*> HashArgs(1, V);
244     V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
245     BBI = ++BB->getInstList().insert(BBI, cast<Instruction>(V));
246   }
247   
248   // Insert the first print instruction to print the string flag:
249   vector<Value*> PrintArgs;
250   PrintArgs.push_back(GEP);
251   if (V) PrintArgs.push_back(V);
252   Instruction *I = new CallInst(Printf, PrintArgs, "trace");
253   BBI = ++BB->getInstList().insert(BBI, I);
254 }
255                             
256
257 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
258                                    BasicBlock::iterator &BBI,
259                                    const string &Message, Function *Printf,
260                                    Function* HashPtrToSeqNum) {
261   std::ostringstream OutStr;
262   if (V) WriteAsOperand(OutStr, V);
263   InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ",
264                   Printf, HashPtrToSeqNum);
265 }
266
267 static void 
268 InsertReleaseInst(Value *V, BasicBlock *BB,
269                   BasicBlock::iterator &BBI,
270                   Function* ReleasePtrFunc) {
271   
272   const Type *SBP = PointerType::get(Type::SByteTy);
273   if (V->getType() != SBP) {   // Cast pointer to be sbyte*
274     Instruction *I = new CastInst(V, SBP, "RPSN_cast");
275     BBI = ++BB->getInstList().insert(BBI, I);
276     V = I;
277   }
278   vector<Value*> releaseArgs(1, V);
279   Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
280   BBI = ++BB->getInstList().insert(BBI, I);
281 }
282
283 static void 
284 InsertRecordInst(Value *V, BasicBlock *BB,
285                  BasicBlock::iterator &BBI,
286                  Function* RecordPtrFunc) {
287     const Type *SBP = PointerType::get(Type::SByteTy);
288   if (V->getType() != SBP) {   // Cast pointer to be sbyte*
289     Instruction *I = new CastInst(V, SBP, "RP_cast");
290     BBI = ++BB->getInstList().insert(BBI, I);
291     V = I;
292   }
293   vector<Value*> releaseArgs(1, V);
294   Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
295   BBI = ++BB->getInstList().insert(BBI, I);
296 }
297
298 static void
299 InsertPushOnEntryFunc(Function *M,
300                       Function* PushOnEntryFunc) {
301   // Get an iterator to point to the insertion location
302   BasicBlock &BB = M->getEntryNode();
303   BB.getInstList().insert(BB.begin(), new CallInst(PushOnEntryFunc,
304                                                    vector<Value*>()));
305 }
306
307 static void 
308 InsertReleaseRecordedInst(BasicBlock *BB,
309                           Function* ReleaseOnReturnFunc) {
310   BasicBlock::iterator BBI = --BB->end();
311   BBI = ++BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
312                                                      vector<Value*>()));
313 }
314
315 // Look for alloca and free instructions. These are the ptrs to release.
316 // Release the free'd pointers immediately.  Record the alloca'd pointers
317 // to be released on return from the current function.
318 // 
319 static void
320 ReleasePtrSeqNumbers(BasicBlock *BB,
321                      ExternalFuncs& externalFuncs) {
322   
323   for (BasicBlock::iterator II=BB->begin(); II != BB->end(); ++II) {
324     if (FreeInst *FI = dyn_cast<FreeInst>(&*II))
325       InsertReleaseInst(FI->getOperand(0), BB,II,externalFuncs.ReleasePtrFunc);
326     else if (AllocaInst *AI = dyn_cast<AllocaInst>(&*II))
327       {
328         BasicBlock::iterator nextI = ++II;
329         InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);     
330         II = --nextI;
331       }
332   }
333 }  
334
335
336 // Insert print instructions at the end of basic block BB for each value
337 // computed in BB that is live at the end of BB,
338 // or that is stored to memory in BB.
339 // If the value is stored to memory, we load it back before printing it
340 // We also return all such loaded values in the vector valuesStoredInFunction
341 // for printing at the exit from the function.  (Note that in each invocation
342 // of the function, this will only get the last value stored for each static
343 // store instruction).
344 // 
345 static void TraceValuesAtBBExit(BasicBlock *BB,
346                                 Function *Printf, Function* HashPtrToSeqNum,
347                                 vector<Instruction*> *valuesStoredInFunction) {
348   // Get an iterator to point to the insertion location, which is
349   // just before the terminator instruction.
350   // 
351   BasicBlock::iterator InsertPos = --BB->end();
352   assert(InsertPos->isTerminator());
353   
354   std::ostringstream OutStr;
355   WriteAsOperand(OutStr, BB, false);
356   InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
357                   Printf, HashPtrToSeqNum);
358
359   // Insert a print instruction for each instruction preceding InsertPos.
360   // The print instructions must go before InsertPos, so we use the
361   // instruction *preceding* InsertPos to check when to terminate the loop.
362   // 
363   if (InsertPos != BB->begin()) { // there's at least one instr before InsertPos
364     BasicBlock::iterator II = BB->begin(), IEincl = InsertPos;
365     --IEincl;
366     do {                          // do from II up to IEincl, inclusive
367       if (StoreInst *SI = dyn_cast<StoreInst>(&*II)) {
368         assert(valuesStoredInFunction &&
369                "Should not be printing a store instruction at function exit");
370         LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
371                                   "reload."+SI->getPointerOperand()->getName());
372         InsertPos = ++BB->getInstList().insert(InsertPos, LI);
373         valuesStoredInFunction->push_back(LI);
374       }
375       if (ShouldTraceValue(II))
376         InsertVerbosePrintInst(II, BB, InsertPos, "  ", Printf,HashPtrToSeqNum);
377     } while (II++ != IEincl);
378   }
379 }
380
381 static inline void InsertCodeToShowFunctionEntry(Function &F, Function *Printf,
382                                                  Function* HashPtrToSeqNum){
383   // Get an iterator to point to the insertion location
384   BasicBlock &BB = F.getEntryNode();
385   BasicBlock::iterator BBI = BB.begin();
386
387   std::ostringstream OutStr;
388   WriteAsOperand(OutStr, &F, true);
389   InsertPrintInst(0, &BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
390                   Printf, HashPtrToSeqNum);
391
392   // Now print all the incoming arguments
393   unsigned ArgNo = 0;
394   for (Function::aiterator I = F.abegin(), E = F.aend(); I != E; ++I, ++ArgNo){
395     InsertVerbosePrintInst(I, &BB, BBI,
396                            "  Arg #" + utostr(ArgNo) + ": ", Printf,
397                            HashPtrToSeqNum);
398   }
399 }
400
401
402 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
403                                                 Function *Printf,
404                                                 Function* HashPtrToSeqNum) {
405   // Get an iterator to point to the insertion location
406   BasicBlock::iterator BBI = --BB->end();
407   ReturnInst &Ret = cast<ReturnInst>(BB->back());
408   
409   std::ostringstream OutStr;
410   WriteAsOperand(OutStr, BB->getParent(), true);
411   InsertPrintInst(0, BB, BBI, "LEAVING  FUNCTION: " + OutStr.str(),
412                   Printf, HashPtrToSeqNum);
413   
414   // print the return value, if any
415   if (BB->getParent()->getReturnType() != Type::VoidTy)
416     InsertPrintInst(Ret.getReturnValue(), BB, BBI, "  Returning: ",
417                     Printf, HashPtrToSeqNum);
418 }
419
420
421 bool InsertTraceCode::runOnFunction(Function &F) {
422   if (!TraceThisFunction(F))
423     return false;
424   
425   vector<Instruction*> valuesStoredInFunction;
426   vector<BasicBlock*>  exitBlocks;
427
428   // Insert code to trace values at function entry
429   InsertCodeToShowFunctionEntry(F, externalFuncs.PrintfFunc,
430                                 externalFuncs.HashPtrFunc);
431   
432   // Push a pointer set for recording alloca'd pointers at entry.
433   if (!DisablePtrHashing)
434     InsertPushOnEntryFunc(&F, externalFuncs.PushOnEntryFunc);
435   
436   for (Function::iterator BB = F.begin(); BB != F.end(); ++BB) {
437     if (isa<ReturnInst>(BB->getTerminator()))
438       exitBlocks.push_back(BB); // record this as an exit block
439
440     // Insert trace code if this basic block is interesting...
441     handleBasicBlock(BB, valuesStoredInFunction);
442
443     if (!DisablePtrHashing)          // release seq. numbers on free/ret
444       ReleasePtrSeqNumbers(BB, externalFuncs);
445   }
446   
447   for (unsigned i=0; i != exitBlocks.size(); ++i)
448     {
449       // Insert code to trace values at function exit
450       InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
451                                    externalFuncs.HashPtrFunc);
452       
453       // Release all recorded pointers before RETURN.  Do this LAST!
454       if (!DisablePtrHashing)
455         InsertReleaseRecordedInst(exitBlocks[i],
456                                   externalFuncs.ReleaseOnReturnFunc);
457     }
458   
459   return true;
460 }