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