1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and function
6 //===----------------------------------------------------------------------===//
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"
27 enum TraceHashPtrOpt {
31 static cl::Enum<enum TraceHashPtrOpt> TraceHashPtrs("tracehash", cl::NoFlags,
32 "Hash pointer values when tracing",
33 clEnumValN(HashToSeqNum, "on", "Hash pointers to sequence number"),
34 clEnumValN(NoHash , "off","Disable hashing of pointers"), 0);
37 static cl::StringList TraceFuncName ("tracefunc", "trace these functions", cl::NoFlags);
40 // We trace a particular function if no functions to trace were specified
41 // or if the function is in the specified list.
44 TraceThisFunction(Function* func)
46 if (TraceFuncName.getNumOccurances() == 0)
49 for (std::vector<std::string>::const_iterator SI=TraceFuncName.begin(),
50 SE=TraceFuncName.end(); SI != SE; ++SI)
51 if (func->getName() == *SI)
61 Function *PrintfFunc, *HashPtrFunc, *ReleasePtrFunc;
62 Function *RecordPtrFunc, *PushOnEntryFunc, *ReleaseOnReturnFunc;
63 void doInitialization(Module *M); // Add prototypes for external functions
66 class InsertTraceCode : public FunctionPass {
67 bool TraceBasicBlockExits, TraceFunctionExits;
68 ExternalFuncs externalFuncs;
70 InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
71 : TraceBasicBlockExits(traceBasicBlockExits),
72 TraceFunctionExits(traceFunctionExits) {}
74 const char *getPassName() const { return "Trace Code Insertion"; }
76 // Add a prototype for runtime functions not already in the program.
78 bool doInitialization(Module *M);
80 //--------------------------------------------------------------------------
81 // Function InsertCodeToTraceValues
83 // Inserts tracing code for all live values at basic block and/or function
84 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
86 static bool doit(Function *M, bool traceBasicBlockExits,
87 bool traceFunctionExits, ExternalFuncs& externalFuncs);
89 // runOnFunction - This method does the work.
91 bool runOnFunction(Function *F) {
92 return doit(F, TraceBasicBlockExits, TraceFunctionExits, externalFuncs);
95 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 } // end anonymous namespace
102 Pass *createTraceValuesPassForFunction() { // Just trace functions
103 return new InsertTraceCode(false, true);
106 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
107 return new InsertTraceCode(true, true);
110 // Add a prototype for external functions used by the tracing code.
112 void ExternalFuncs::doInitialization(Module *M) {
113 const Type *SBP = PointerType::get(Type::SByteTy);
114 const FunctionType *MTy =
115 FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
116 PrintfFunc = M->getOrInsertFunction("printf", MTy);
118 // Use varargs functions with no args instead of func(sbyte*) so that
119 // we don't have to generate cast instructions below :-)
121 const FunctionType *hashFuncTy =
122 FunctionType::get(Type::UIntTy, vector<const Type*>(), true);
123 HashPtrFunc = M->getOrInsertFunction("HashPointerToSeqNum", hashFuncTy);
125 // varargs again, same reason.
126 const FunctionType *voidVAFuncTy =
127 FunctionType::get(Type::VoidTy, vector<const Type*>(), true);
129 ReleasePtrFunc =M->getOrInsertFunction("ReleasePointerSeqNum", voidVAFuncTy);
130 RecordPtrFunc = M->getOrInsertFunction("RecordPointer", voidVAFuncTy);
132 const FunctionType *voidvoidFuncTy =
133 FunctionType::get(Type::VoidTy, vector<const Type*>(), false);
135 PushOnEntryFunc = M->getOrInsertFunction("PushPointerSet", voidvoidFuncTy);
136 ReleaseOnReturnFunc = M->getOrInsertFunction("ReleasePointersPopSet",
141 // Add a prototype for external functions used by the tracing code.
143 bool InsertTraceCode::doInitialization(Module *M) {
144 externalFuncs.doInitialization(M);
149 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
150 // Create a constant internal string reference...
151 Constant *Init = ConstantArray::get(str);
153 // Create the global variable and record it in the module
154 // The GV will be renamed to a unique name if needed.
155 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
157 M->getGlobalList().push_back(GV);
163 // Check if this instruction has any uses outside its basic block,
164 // or if it used by either a Call or Return instruction.
166 static inline bool LiveAtBBExit(const Instruction* I) {
167 const BasicBlock *BB = I->getParent();
168 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
169 if (const Instruction *UI = dyn_cast<Instruction>(*U))
170 if (UI->getParent() != BB || isa<ReturnInst>(UI))
177 static inline bool TraceThisOpCode(unsigned opCode) {
178 // Explicitly test for opCodes *not* to trace so that any new opcodes will
179 // be traced by default (VoidTy's are already excluded)
181 return (opCode < Instruction::FirstOtherOp &&
182 opCode != Instruction::Alloca &&
183 opCode != Instruction::PHINode &&
184 opCode != Instruction::Cast);
188 static bool ShouldTraceValue(const Instruction *I) {
190 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
191 TraceThisOpCode(I->getOpcode());
194 static string getPrintfCodeFor(const Value *V) {
195 if (V == 0) return "";
196 if (V->getType()->isFloatingPoint())
198 else if (V->getType() == Type::LabelTy)
200 else if (isa<PointerType>(V->getType()))
201 return (TraceHashPtrs == NoHash)? "0x%p" : "%d";
202 else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
205 assert(0 && "Illegal value to print out...");
210 static void InsertPrintInst(Value *V,BasicBlock *BB, BasicBlock::iterator &BBI,
212 Function *Printf, Function* HashPtrToSeqNum) {
213 // Escape Message by replacing all % characters with %% chars.
215 while ((Offset = Message.find('%', Offset)) != string::npos) {
216 Message.replace(Offset, 1, "%%");
217 Offset += 2; // Skip over the new %'s
220 Module *Mod = BB->getParent()->getParent();
222 // Turn the marker string into a global variable...
223 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
225 // Turn the format string into an sbyte *
227 new GetElementPtrInst(fmtVal,
228 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
230 BBI = BB->getInstList().insert(BBI, GEP)+1;
232 // Insert a call to the hash function if this is a pointer value
233 if (V && isa<PointerType>(V->getType()) && TraceHashPtrs == HashToSeqNum) {
234 vector<Value*> HashArgs;
235 HashArgs.push_back(V);
236 V = new CallInst(HashPtrToSeqNum, HashArgs, "ptrSeqNum");
237 BBI = BB->getInstList().insert(BBI, cast<Instruction>(V))+1;
240 // Insert the first print instruction to print the string flag:
241 vector<Value*> PrintArgs;
242 PrintArgs.push_back(GEP);
243 if (V) PrintArgs.push_back(V);
244 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
245 BBI = BB->getInstList().insert(BBI, I)+1;
249 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
250 BasicBlock::iterator &BBI,
251 const string &Message, Function *Printf,
252 Function* HashPtrToSeqNum) {
253 std::ostringstream OutStr;
254 if (V) WriteAsOperand(OutStr, V);
255 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ",
256 Printf, HashPtrToSeqNum);
260 InsertReleaseInst(Value *V, BasicBlock *BB,
261 BasicBlock::iterator &BBI,
262 Function* ReleasePtrFunc) {
263 vector<Value*> releaseArgs;
264 releaseArgs.push_back(V);
265 Instruction *I = new CallInst(ReleasePtrFunc, releaseArgs);
266 BBI = BB->getInstList().insert(BBI, I)+1;
270 InsertRecordInst(Value *V, BasicBlock *BB,
271 BasicBlock::iterator &BBI,
272 Function* RecordPtrFunc) {
273 vector<Value*> releaseArgs;
274 releaseArgs.push_back(V);
275 Instruction *I = new CallInst(RecordPtrFunc, releaseArgs);
276 BBI = BB->getInstList().insert(BBI, I)+1;
280 InsertPushOnEntryFunc(Function *M,
281 Function* PushOnEntryFunc) {
282 // Get an iterator to point to the insertion location
283 BasicBlock *BB = M->getEntryNode();
284 BB->getInstList().insert(BB->begin(), new CallInst(PushOnEntryFunc,
289 InsertReleaseRecordedInst(BasicBlock *BB,
290 Function* ReleaseOnReturnFunc) {
291 BasicBlock::iterator BBI = BB->end()-1;
292 BBI = 1 + BB->getInstList().insert(BBI, new CallInst(ReleaseOnReturnFunc,
296 // Look for alloca and free instructions. These are the ptrs to release.
297 // Release the free'd pointers immediately. Record the alloca'd pointers
298 // to be released on return from the current function.
301 ReleasePtrSeqNumbers(BasicBlock *BB,
302 ExternalFuncs& externalFuncs) {
304 for (BasicBlock::iterator II=BB->begin(); II != BB->end(); ++II) {
305 if (FreeInst *FI = dyn_cast<FreeInst>(*II))
306 InsertReleaseInst(FI->getOperand(0), BB,II,externalFuncs.ReleasePtrFunc);
307 else if (AllocaInst *AI = dyn_cast<AllocaInst>(*II))
309 BasicBlock::iterator nextI = II+1;
310 InsertRecordInst(AI, BB, nextI, externalFuncs.RecordPtrFunc);
317 // Insert print instructions at the end of the basic block *bb
318 // for each value in valueVec[] that is live at the end of that basic block,
319 // or that is stored to memory in this basic block.
320 // If the value is stored to memory, we load it back before printing
321 // We also return all such loaded values in the vector valuesStoredInFunction
322 // for printing at the exit from the function. (Note that in each invocation
323 // of the function, this will only get the last value stored for each static
324 // store instruction).
325 // *bb must be the block in which the value is computed;
326 // this is not checked here.
328 static void TraceValuesAtBBExit(BasicBlock *BB,
329 Function *Printf, Function* HashPtrToSeqNum,
330 vector<Instruction*> *valuesStoredInFunction) {
331 // Get an iterator to point to the insertion location, which is
332 // just before the terminator instruction.
334 BasicBlock::iterator InsertPos = BB->end()-1;
335 assert((*InsertPos)->isTerminator());
337 // If the terminator is a conditional branch, insert the trace code just
338 // before the instruction that computes the branch condition (just to
339 // avoid putting a call between the CC-setting instruction and the branch).
340 // Use laterInstrSet to mark instructions that come after the setCC instr
341 // because those cannot be traced at the location we choose.
343 Instruction *SetCC = 0;
344 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
345 if (!Branch->isUnconditional())
346 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
347 if (I->getParent() == BB) {
349 while (*InsertPos != SetCC)
350 --InsertPos; // Back up until we can insert before the setcc
353 // Copy all of the instructions into a vector to avoid problems with Setcc
354 const vector<Instruction*> Insts(BB->begin(), InsertPos);
356 std::ostringstream OutStr;
357 WriteAsOperand(OutStr, BB, false);
358 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(),
359 Printf, HashPtrToSeqNum);
361 // Insert a print instruction for each value.
363 for (vector<Instruction*>::const_iterator II = Insts.begin(),
364 IE = Insts.end(); II != IE; ++II) {
365 Instruction *I = *II;
366 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
367 assert(valuesStoredInFunction &&
368 "Should not be printing a store instruction at function exit");
369 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
371 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
372 valuesStoredInFunction->push_back(LI);
374 if (ShouldTraceValue(I))
375 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf, HashPtrToSeqNum);
379 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf,
380 Function* HashPtrToSeqNum){
381 // Get an iterator to point to the insertion location
382 BasicBlock *BB = M->getEntryNode();
383 BasicBlock::iterator BBI = BB->begin();
385 std::ostringstream OutStr;
386 WriteAsOperand(OutStr, M, true);
387 InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(),
388 Printf, HashPtrToSeqNum);
390 // Now print all the incoming arguments
391 const Function::ArgumentListType &argList = M->getArgumentList();
393 for (Function::ArgumentListType::const_iterator
394 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
395 InsertVerbosePrintInst((Value*)*I, BB, BBI,
396 " Arg #" + utostr(ArgNo), Printf, HashPtrToSeqNum);
401 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
403 Function* HashPtrToSeqNum) {
404 // Get an iterator to point to the insertion location
405 BasicBlock::iterator BBI = BB->end()-1;
406 ReturnInst *Ret = cast<ReturnInst>(*BBI);
408 std::ostringstream OutStr;
409 WriteAsOperand(OutStr, BB->getParent(), true);
410 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(),
411 Printf, HashPtrToSeqNum);
413 // print the return value, if any
414 if (BB->getParent()->getReturnType() != Type::VoidTy)
415 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ",
416 Printf, HashPtrToSeqNum);
420 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
421 bool traceFunctionEvents,
422 ExternalFuncs& externalFuncs) {
423 if (!traceBasicBlockExits && !traceFunctionEvents)
426 if (!TraceThisFunction(M))
429 vector<Instruction*> valuesStoredInFunction;
430 vector<BasicBlock*> exitBlocks;
432 // Insert code to trace values at function entry
433 if (traceFunctionEvents)
434 InsertCodeToShowFunctionEntry(M, externalFuncs.PrintfFunc,
435 externalFuncs.HashPtrFunc);
437 // Push a pointer set for recording alloca'd pointers at entry.
438 if (TraceHashPtrs == HashToSeqNum)
439 InsertPushOnEntryFunc(M, externalFuncs.PushOnEntryFunc);
441 for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
442 BasicBlock *BB = *BI;
443 if (isa<ReturnInst>(BB->getTerminator()))
444 exitBlocks.push_back(BB); // record this as an exit block
446 if (traceBasicBlockExits)
447 TraceValuesAtBBExit(BB, externalFuncs.PrintfFunc,
448 externalFuncs.HashPtrFunc, &valuesStoredInFunction);
450 if (TraceHashPtrs == HashToSeqNum) // release seq. numbers on free/ret
451 ReleasePtrSeqNumbers(BB, externalFuncs);
454 for (unsigned i=0; i < exitBlocks.size(); ++i)
456 // Insert code to trace values at function exit
457 if (traceFunctionEvents)
458 InsertCodeToShowFunctionExit(exitBlocks[i], externalFuncs.PrintfFunc,
459 externalFuncs.HashPtrFunc);
461 // Release all recorded pointers before RETURN. Do this LAST!
462 if (TraceHashPtrs == HashToSeqNum)
463 InsertReleaseRecordedInst(exitBlocks[i],
464 externalFuncs.ReleaseOnReturnFunc);