1 //===- TraceValues.cpp - Value Tracing for debugging -------------*- C++ -*--=//
3 // Support for inserting LLVM code to print values at basic block and method
6 //===----------------------------------------------------------------------===//
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/Method.h"
16 #include "llvm/Module.h"
17 #include "llvm/SymbolTable.h"
18 #include "llvm/Pass.h"
19 #include "llvm/Assembly/Writer.h"
20 #include "Support/StringExtras.h"
26 class InsertTraceCode : public MethodPass {
27 bool TraceBasicBlockExits, TraceMethodExits;
30 InsertTraceCode(bool traceBasicBlockExits, bool traceMethodExits)
31 : TraceBasicBlockExits(traceBasicBlockExits),
32 TraceMethodExits(traceMethodExits) {}
34 // Add a prototype for printf if it is not already in the program.
36 bool doInitialization(Module *M);
38 //--------------------------------------------------------------------------
39 // Function InsertCodeToTraceValues
41 // Inserts tracing code for all live values at basic block and/or method
42 // exits as specified by `traceBasicBlockExits' and `traceMethodExits'.
44 static bool doit(Method *M, bool traceBasicBlockExits,
45 bool traceMethodExits, Method *Printf);
47 // runOnMethod - This method does the work. Always successful.
49 bool runOnMethod(Method *M) {
50 return doit(M, TraceBasicBlockExits, TraceMethodExits, PrintfMeth);
53 } // end anonymous namespace
56 Pass *createTraceValuesPassForMethod() { // Just trace methods
57 return new InsertTraceCode(false, true);
60 Pass *createTraceValuesPassForBasicBlocks() { // Trace BB's and methods
61 return new InsertTraceCode(true, true);
67 // Add a prototype for printf if it is not already in the program.
69 bool InsertTraceCode::doInitialization(Module *M) {
70 SymbolTable *ST = M->getSymbolTable();
71 const Type *SBP = PointerType::get(Type::SByteTy);
72 const MethodType *MTy =
73 MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
75 if (Value *Meth = ST->lookup(PointerType::get(MTy), "printf")) {
76 PrintfMeth = cast<Method>(Meth);
80 // Create a new method and add it to the module
81 PrintfMeth = new Method(MTy, false, "printf");
82 M->getMethodList().push_back(PrintfMeth);
87 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
88 // Create a constant internal string reference...
89 Constant *Init = ConstantArray::get(str);
90 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
92 M->getGlobalList().push_back(GV);
98 // Check if this instruction has any uses outside its basic block,
99 // or if it used by either a Call or Return instruction.
101 static inline bool LiveAtBBExit(const Instruction* I) {
102 const BasicBlock *BB = I->getParent();
103 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
104 if (const Instruction *UI = dyn_cast<Instruction>(*U))
105 if (UI->getParent() != BB || isa<ReturnInst>(UI))
112 static inline bool TraceThisOpCode(unsigned opCode) {
113 // Explicitly test for opCodes *not* to trace so that any new opcodes will
114 // be traced by default (VoidTy's are already excluded)
116 return (opCode < Instruction::FirstOtherOp &&
117 opCode != Instruction::Alloca &&
118 opCode != Instruction::PHINode &&
119 opCode != Instruction::Cast);
123 static bool ShouldTraceValue(const Instruction *I) {
125 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
126 TraceThisOpCode(I->getOpcode());
129 static string getPrintfCodeFor(const Value *V) {
130 if (V == 0) return "";
131 switch (V->getType()->getPrimitiveID()) {
133 case Type::UByteTyID: case Type::UShortTyID:
134 case Type::UIntTyID: case Type::ULongTyID:
135 case Type::SByteTyID: case Type::ShortTyID:
136 case Type::IntTyID: case Type::LongTyID:
139 case Type::FloatTyID: case Type::DoubleTyID:
142 case Type::LabelTyID: case Type::PointerTyID:
146 assert(0 && "Illegal value to print out...");
152 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
153 string Message, Method *Printf) {
154 // Escape Message by replacing all % characters with %% chars.
156 while ((Offset = Message.find('%', Offset)) != string::npos) {
157 Message.replace(Offset, 2, "%%");
158 Offset += 2; // Skip over the new %'s
161 Module *Mod = BB->getParent()->getParent();
163 // Turn the marker string into a global variable...
164 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
166 // Turn the format string into an sbyte *
168 new GetElementPtrInst(fmtVal,
169 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
171 BBI = BB->getInstList().insert(BBI, GEP)+1;
173 // Insert the first print instruction to print the string flag:
174 vector<Value*> PrintArgs;
175 PrintArgs.push_back(GEP);
176 if (V) PrintArgs.push_back(V);
177 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
178 BBI = BB->getInstList().insert(BBI, I)+1;
182 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
183 BasicBlock::iterator &BBI,
184 const string &Message, Method *Printf) {
185 std::ostringstream OutStr;
186 if (V) WriteAsOperand(OutStr, V);
187 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
191 // Insert print instructions at the end of the basic block *bb
192 // for each value in valueVec[] that is live at the end of that basic block,
193 // or that is stored to memory in this basic block.
194 // If the value is stored to memory, we load it back before printing
195 // We also return all such loaded values in the vector valuesStoredInMethod
196 // for printing at the exit from the method. (Note that in each invocation
197 // of the method, this will only get the last value stored for each static
198 // store instruction).
199 // *bb must be the block in which the value is computed;
200 // this is not checked here.
202 static void TraceValuesAtBBExit(BasicBlock *BB, Method *Printf,
203 vector<Instruction*> *valuesStoredInMethod) {
204 // Get an iterator to point to the insertion location, which is
205 // just before the terminator instruction.
207 BasicBlock::iterator InsertPos = BB->end()-1;
208 assert((*InsertPos)->isTerminator());
210 // If the terminator is a conditional branch, insert the trace code just
211 // before the instruction that computes the branch condition (just to
212 // avoid putting a call between the CC-setting instruction and the branch).
213 // Use laterInstrSet to mark instructions that come after the setCC instr
214 // because those cannot be traced at the location we choose.
216 Instruction *SetCC = 0;
217 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
218 if (!Branch->isUnconditional())
219 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
220 if (I->getParent() == BB) {
222 while (*InsertPos != SetCC)
223 --InsertPos; // Back up until we can insert before the setcc
226 // Copy all of the instructions into a vector to avoid problems with Setcc
227 const vector<Instruction*> Insts(BB->begin(), InsertPos);
229 std::ostringstream OutStr;
230 WriteAsOperand(OutStr, BB, false);
231 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
233 // Insert a print instruction for each value.
235 for (vector<Instruction*>::const_iterator II = Insts.begin(),
236 IE = Insts.end(); II != IE; ++II) {
237 Instruction *I = *II;
238 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
239 assert(valuesStoredInMethod &&
240 "Should not be printing a store instruction at method exit");
241 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
243 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
244 valuesStoredInMethod->push_back(LI);
246 if (ShouldTraceValue(I))
247 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
251 static inline void InsertCodeToShowMethodEntry(Method *M, Method *Printf) {
252 // Get an iterator to point to the insertion location
253 BasicBlock *BB = M->getEntryNode();
254 BasicBlock::iterator BBI = BB->begin();
256 std::ostringstream OutStr;
257 WriteAsOperand(OutStr, M, true);
258 InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
260 // Now print all the incoming arguments
261 const Method::ArgumentListType &argList = M->getArgumentList();
263 for (Method::ArgumentListType::const_iterator
264 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
265 InsertVerbosePrintInst(*I, BB, BBI,
266 " Arg #" + utostr(ArgNo), Printf);
271 static inline void InsertCodeToShowMethodExit(BasicBlock *BB, Method *Printf) {
272 // Get an iterator to point to the insertion location
273 BasicBlock::iterator BBI = BB->end()-1;
274 ReturnInst *Ret = cast<ReturnInst>(*BBI);
276 std::ostringstream OutStr;
277 WriteAsOperand(OutStr, BB->getParent(), true);
278 InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
280 // print the return value, if any
281 if (BB->getParent()->getReturnType() != Type::VoidTy)
282 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
286 bool InsertTraceCode::doit(Method *M, bool traceBasicBlockExits,
287 bool traceMethodEvents, Method *Printf) {
288 if (!traceBasicBlockExits && !traceMethodEvents)
291 vector<Instruction*> valuesStoredInMethod;
292 vector<BasicBlock*> exitBlocks;
294 if (traceMethodEvents)
295 InsertCodeToShowMethodEntry(M, Printf);
297 for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {
298 BasicBlock *BB = *BI;
299 if (isa<ReturnInst>(BB->getTerminator()))
300 exitBlocks.push_back(BB); // record this as an exit block
302 if (traceBasicBlockExits)
303 TraceValuesAtBBExit(BB, Printf, &valuesStoredInMethod);
306 if (traceMethodEvents)
307 for (unsigned i=0; i < exitBlocks.size(); ++i) {
309 TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
310 /*indent*/ 0, /*isMethodExit*/ true,
311 /*valuesStoredInMethod*/ NULL);
313 InsertCodeToShowMethodExit(exitBlocks[i], Printf);