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/StringExtras.h"
26 class InsertTraceCode : public FunctionPass {
27 bool TraceBasicBlockExits, TraceFunctionExits;
30 InsertTraceCode(bool traceBasicBlockExits, bool traceFunctionExits)
31 : TraceBasicBlockExits(traceBasicBlockExits),
32 TraceFunctionExits(traceFunctionExits) {}
34 const char *getPassName() const { return "Trace Code Insertion"; }
36 // Add a prototype for printf if it is not already in the program.
38 bool doInitialization(Module *M);
40 //--------------------------------------------------------------------------
41 // Function InsertCodeToTraceValues
43 // Inserts tracing code for all live values at basic block and/or function
44 // exits as specified by `traceBasicBlockExits' and `traceFunctionExits'.
46 static bool doit(Function *M, bool traceBasicBlockExits,
47 bool traceFunctionExits, Function *Printf);
49 // runOnFunction - This method does the work.
51 bool runOnFunction(Function *F) {
52 return doit(F, TraceBasicBlockExits, TraceFunctionExits, PrintfFunc);
55 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
59 } // end anonymous namespace
62 Pass *createTraceValuesPassForFunction() { // Just trace functions
63 return new InsertTraceCode(false, true);
66 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and functions
67 return new InsertTraceCode(true, true);
73 // Add a prototype for printf if it is not already in the program.
75 bool InsertTraceCode::doInitialization(Module *M) {
76 const Type *SBP = PointerType::get(Type::SByteTy);
77 const FunctionType *MTy =
78 FunctionType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
80 PrintfFunc = M->getOrInsertFunction("printf", MTy);
85 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
86 // Create a constant internal string reference...
87 Constant *Init = ConstantArray::get(str);
89 // Create the global variable and record it in the module
90 // The GV will be renamed to a unique name if needed.
91 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
93 M->getGlobalList().push_back(GV);
99 // Check if this instruction has any uses outside its basic block,
100 // or if it used by either a Call or Return instruction.
102 static inline bool LiveAtBBExit(const Instruction* I) {
103 const BasicBlock *BB = I->getParent();
104 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
105 if (const Instruction *UI = dyn_cast<Instruction>(*U))
106 if (UI->getParent() != BB || isa<ReturnInst>(UI))
113 static inline bool TraceThisOpCode(unsigned opCode) {
114 // Explicitly test for opCodes *not* to trace so that any new opcodes will
115 // be traced by default (VoidTy's are already excluded)
117 return (opCode < Instruction::FirstOtherOp &&
118 opCode != Instruction::Alloca &&
119 opCode != Instruction::PHINode &&
120 opCode != Instruction::Cast);
124 static bool ShouldTraceValue(const Instruction *I) {
126 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
127 TraceThisOpCode(I->getOpcode());
130 static string getPrintfCodeFor(const Value *V) {
131 if (V == 0) return "";
132 if (V->getType()->isFloatingPoint())
134 else if (V->getType() == Type::LabelTy || isa<PointerType>(V->getType()))
136 else if (V->getType()->isIntegral() || V->getType() == Type::BoolTy)
139 assert(0 && "Illegal value to print out...");
144 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
145 string Message, Function *Printf) {
146 // Escape Message by replacing all % characters with %% chars.
148 while ((Offset = Message.find('%', Offset)) != string::npos) {
149 Message.replace(Offset, 1, "%%");
150 Offset += 2; // Skip over the new %'s
153 Module *Mod = BB->getParent()->getParent();
155 // Turn the marker string into a global variable...
156 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
158 // Turn the format string into an sbyte *
160 new GetElementPtrInst(fmtVal,
161 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
163 BBI = BB->getInstList().insert(BBI, GEP)+1;
165 // Insert the first print instruction to print the string flag:
166 vector<Value*> PrintArgs;
167 PrintArgs.push_back(GEP);
168 if (V) PrintArgs.push_back(V);
169 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
170 BBI = BB->getInstList().insert(BBI, I)+1;
174 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
175 BasicBlock::iterator &BBI,
176 const string &Message, Function *Printf) {
177 std::ostringstream OutStr;
178 if (V) WriteAsOperand(OutStr, V);
179 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
183 // Insert print instructions at the end of the basic block *bb
184 // for each value in valueVec[] that is live at the end of that basic block,
185 // or that is stored to memory in this basic block.
186 // If the value is stored to memory, we load it back before printing
187 // We also return all such loaded values in the vector valuesStoredInFunction
188 // for printing at the exit from the function. (Note that in each invocation
189 // of the function, this will only get the last value stored for each static
190 // store instruction).
191 // *bb must be the block in which the value is computed;
192 // this is not checked here.
194 static void TraceValuesAtBBExit(BasicBlock *BB, Function *Printf,
195 vector<Instruction*> *valuesStoredInFunction) {
196 // Get an iterator to point to the insertion location, which is
197 // just before the terminator instruction.
199 BasicBlock::iterator InsertPos = BB->end()-1;
200 assert((*InsertPos)->isTerminator());
202 // If the terminator is a conditional branch, insert the trace code just
203 // before the instruction that computes the branch condition (just to
204 // avoid putting a call between the CC-setting instruction and the branch).
205 // Use laterInstrSet to mark instructions that come after the setCC instr
206 // because those cannot be traced at the location we choose.
208 Instruction *SetCC = 0;
209 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
210 if (!Branch->isUnconditional())
211 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
212 if (I->getParent() == BB) {
214 while (*InsertPos != SetCC)
215 --InsertPos; // Back up until we can insert before the setcc
218 // Copy all of the instructions into a vector to avoid problems with Setcc
219 const vector<Instruction*> Insts(BB->begin(), InsertPos);
221 std::ostringstream OutStr;
222 WriteAsOperand(OutStr, BB, false);
223 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
225 // Insert a print instruction for each value.
227 for (vector<Instruction*>::const_iterator II = Insts.begin(),
228 IE = Insts.end(); II != IE; ++II) {
229 Instruction *I = *II;
230 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
231 assert(valuesStoredInFunction &&
232 "Should not be printing a store instruction at function exit");
233 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
235 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
236 valuesStoredInFunction->push_back(LI);
238 if (ShouldTraceValue(I))
239 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
243 static inline void InsertCodeToShowFunctionEntry(Function *M, Function *Printf){
244 // Get an iterator to point to the insertion location
245 BasicBlock *BB = M->getEntryNode();
246 BasicBlock::iterator BBI = BB->begin();
248 std::ostringstream OutStr;
249 WriteAsOperand(OutStr, M, true);
250 InsertPrintInst(0, BB, BBI, "ENTERING FUNCTION: " + OutStr.str(), Printf);
252 // Now print all the incoming arguments
253 const Function::ArgumentListType &argList = M->getArgumentList();
255 for (Function::ArgumentListType::const_iterator
256 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
257 InsertVerbosePrintInst((Value*)*I, BB, BBI,
258 " Arg #" + utostr(ArgNo), Printf);
263 static inline void InsertCodeToShowFunctionExit(BasicBlock *BB,
265 // Get an iterator to point to the insertion location
266 BasicBlock::iterator BBI = BB->end()-1;
267 ReturnInst *Ret = cast<ReturnInst>(*BBI);
269 std::ostringstream OutStr;
270 WriteAsOperand(OutStr, BB->getParent(), true);
271 InsertPrintInst(0, BB, BBI, "LEAVING FUNCTION: " + OutStr.str(), Printf);
273 // print the return value, if any
274 if (BB->getParent()->getReturnType() != Type::VoidTy)
275 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
279 bool InsertTraceCode::doit(Function *M, bool traceBasicBlockExits,
280 bool traceFunctionEvents, Function *Printf) {
281 if (!traceBasicBlockExits && !traceFunctionEvents)
284 vector<Instruction*> valuesStoredInFunction;
285 vector<BasicBlock*> exitBlocks;
287 if (traceFunctionEvents)
288 InsertCodeToShowFunctionEntry(M, Printf);
290 for (Function::iterator BI = M->begin(); BI != M->end(); ++BI) {
291 BasicBlock *BB = *BI;
292 if (isa<ReturnInst>(BB->getTerminator()))
293 exitBlocks.push_back(BB); // record this as an exit block
295 if (traceBasicBlockExits)
296 TraceValuesAtBBExit(BB, Printf, &valuesStoredInFunction);
299 if (traceFunctionEvents)
300 for (unsigned i=0; i < exitBlocks.size(); ++i) {
302 TraceValuesAtBBExit(valuesStoredInFunction, exitBlocks[i], module,
303 /*indent*/ 0, /*isFunctionExit*/ true,
304 /*valuesStoredInFunction*/ NULL);
306 InsertCodeToShowFunctionExit(exitBlocks[i], Printf);