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/Assembly/Writer.h"
19 #include "Support/StringExtras.h"
24 // Add a prototype for printf if it is not already in the program.
26 bool InsertTraceCode::doInitialization(Module *M) {
27 SymbolTable *ST = M->getSymbolTable();
28 const Type *SBP = PointerType::get(Type::SByteTy);
29 const MethodType *MTy =
30 MethodType::get(Type::IntTy, vector<const Type*>(1, SBP), true);
32 if (Value *Meth = ST->lookup(PointerType::get(MTy), "printf")) {
33 PrintfMeth = cast<Method>(Meth);
37 // Create a new method and add it to the module
38 PrintfMeth = new Method(MTy, false, "printf");
39 M->getMethodList().push_back(PrintfMeth);
44 static inline GlobalVariable *getStringRef(Module *M, const string &str) {
45 // Create a constant internal string reference...
46 Constant *Init = ConstantArray::get(str);
47 GlobalVariable *GV = new GlobalVariable(Init->getType(), true, true, Init,
49 M->getGlobalList().push_back(GV);
55 // Check if this instruction has any uses outside its basic block,
56 // or if it used by either a Call or Return instruction.
58 static inline bool LiveAtBBExit(const Instruction* I) {
59 const BasicBlock *BB = I->getParent();
60 for (Value::use_const_iterator U = I->use_begin(); U != I->use_end(); ++U)
61 if (const Instruction *UI = dyn_cast<Instruction>(*U))
62 if (UI->getParent() != BB || isa<ReturnInst>(UI))
69 static inline bool TraceThisOpCode(unsigned opCode) {
70 // Explicitly test for opCodes *not* to trace so that any new opcodes will
71 // be traced by default (VoidTy's are already excluded)
73 return (opCode < Instruction::FirstOtherOp &&
74 opCode != Instruction::Alloca &&
75 opCode != Instruction::PHINode &&
76 opCode != Instruction::Cast);
80 static bool ShouldTraceValue(const Instruction *I) {
82 I->getType() != Type::VoidTy && LiveAtBBExit(I) &&
83 TraceThisOpCode(I->getOpcode());
86 static string getPrintfCodeFor(const Value *V) {
87 if (V == 0) return "";
88 switch (V->getType()->getPrimitiveID()) {
90 case Type::UByteTyID: case Type::UShortTyID:
91 case Type::UIntTyID: case Type::ULongTyID:
92 case Type::SByteTyID: case Type::ShortTyID:
93 case Type::IntTyID: case Type::LongTyID:
96 case Type::FloatTyID: case Type::DoubleTyID:
99 case Type::LabelTyID: case Type::PointerTyID:
103 assert(0 && "Illegal value to print out...");
109 static void InsertPrintInst(Value *V, BasicBlock *BB, BasicBlock::iterator &BBI,
110 string Message, Method *Printf) {
111 // Escape Message by replacing all % characters with %% chars.
113 while ((Offset = Message.find('%', Offset)) != string::npos) {
114 Message.replace(Offset, 2, "%%");
115 Offset += 2; // Skip over the new %'s
118 Module *Mod = BB->getParent()->getParent();
120 // Turn the marker string into a global variable...
121 GlobalVariable *fmtVal = getStringRef(Mod, Message+getPrintfCodeFor(V)+"\n");
123 // Turn the format string into an sbyte *
125 new GetElementPtrInst(fmtVal,
126 vector<Value*>(2,ConstantUInt::get(Type::UIntTy, 0)),
128 BBI = BB->getInstList().insert(BBI, GEP)+1;
130 // Insert the first print instruction to print the string flag:
131 vector<Value*> PrintArgs;
132 PrintArgs.push_back(GEP);
133 if (V) PrintArgs.push_back(V);
134 Instruction *I = new CallInst(Printf, PrintArgs, "trace");
135 BBI = BB->getInstList().insert(BBI, I)+1;
139 static void InsertVerbosePrintInst(Value *V, BasicBlock *BB,
140 BasicBlock::iterator &BBI,
141 const string &Message, Method *Printf) {
142 std::ostringstream OutStr;
143 if (V) WriteAsOperand(OutStr, V);
144 InsertPrintInst(V, BB, BBI, Message+OutStr.str()+" = ", Printf);
148 // Insert print instructions at the end of the basic block *bb
149 // for each value in valueVec[] that is live at the end of that basic block,
150 // or that is stored to memory in this basic block.
151 // If the value is stored to memory, we load it back before printing
152 // We also return all such loaded values in the vector valuesStoredInMethod
153 // for printing at the exit from the method. (Note that in each invocation
154 // of the method, this will only get the last value stored for each static
155 // store instruction).
156 // *bb must be the block in which the value is computed;
157 // this is not checked here.
159 static void TraceValuesAtBBExit(BasicBlock *BB, Method *Printf,
160 vector<Instruction*> *valuesStoredInMethod) {
161 // Get an iterator to point to the insertion location, which is
162 // just before the terminator instruction.
164 BasicBlock::iterator InsertPos = BB->end()-1;
165 assert((*InsertPos)->isTerminator());
167 // If the terminator is a conditional branch, insert the trace code just
168 // before the instruction that computes the branch condition (just to
169 // avoid putting a call between the CC-setting instruction and the branch).
170 // Use laterInstrSet to mark instructions that come after the setCC instr
171 // because those cannot be traced at the location we choose.
173 Instruction *SetCC = 0;
174 if (BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator()))
175 if (!Branch->isUnconditional())
176 if (Instruction *I = dyn_cast<Instruction>(Branch->getCondition()))
177 if (I->getParent() == BB) {
179 while (*InsertPos != SetCC)
180 --InsertPos; // Back up until we can insert before the setcc
183 // Copy all of the instructions into a vector to avoid problems with Setcc
184 const vector<Instruction*> Insts(BB->begin(), InsertPos);
186 std::ostringstream OutStr;
187 WriteAsOperand(OutStr, BB, false);
188 InsertPrintInst(0, BB, InsertPos, "LEAVING BB:" + OutStr.str(), Printf);
190 // Insert a print instruction for each value.
192 for (vector<Instruction*>::const_iterator II = Insts.begin(),
193 IE = Insts.end(); II != IE; ++II) {
194 Instruction *I = *II;
195 if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
196 assert(valuesStoredInMethod &&
197 "Should not be printing a store instruction at method exit");
198 LoadInst *LI = new LoadInst(SI->getPointerOperand(), SI->copyIndices(),
200 InsertPos = BB->getInstList().insert(InsertPos, LI) + 1;
201 valuesStoredInMethod->push_back(LI);
203 if (ShouldTraceValue(I))
204 InsertVerbosePrintInst(I, BB, InsertPos, " ", Printf);
208 static inline void InsertCodeToShowMethodEntry(Method *M, Method *Printf) {
209 // Get an iterator to point to the insertion location
210 BasicBlock *BB = M->getEntryNode();
211 BasicBlock::iterator BBI = BB->begin();
213 std::ostringstream OutStr;
214 WriteAsOperand(OutStr, M, true);
215 InsertPrintInst(0, BB, BBI, "ENTERING METHOD: " + OutStr.str(), Printf);
217 // Now print all the incoming arguments
218 const Method::ArgumentListType &argList = M->getArgumentList();
220 for (Method::ArgumentListType::const_iterator
221 I = argList.begin(), E = argList.end(); I != E; ++I, ++ArgNo) {
222 InsertVerbosePrintInst(*I, BB, BBI,
223 " Arg #" + utostr(ArgNo), Printf);
228 static inline void InsertCodeToShowMethodExit(BasicBlock *BB, Method *Printf) {
229 // Get an iterator to point to the insertion location
230 BasicBlock::iterator BBI = BB->end()-1;
231 ReturnInst *Ret = cast<ReturnInst>(*BBI);
233 std::ostringstream OutStr;
234 WriteAsOperand(OutStr, BB->getParent(), true);
235 InsertPrintInst(0, BB, BBI, "LEAVING METHOD: " + OutStr.str(), Printf);
237 // print the return value, if any
238 if (BB->getParent()->getReturnType() != Type::VoidTy)
239 InsertPrintInst(Ret->getReturnValue(), BB, BBI, " Returning: ", Printf);
243 bool InsertTraceCode::doit(Method *M, bool traceBasicBlockExits,
244 bool traceMethodEvents, Method *Printf) {
245 if (!traceBasicBlockExits && !traceMethodEvents)
248 vector<Instruction*> valuesStoredInMethod;
249 vector<BasicBlock*> exitBlocks;
251 if (traceMethodEvents)
252 InsertCodeToShowMethodEntry(M, Printf);
254 for (Method::iterator BI = M->begin(); BI != M->end(); ++BI) {
255 BasicBlock *BB = *BI;
256 if (isa<ReturnInst>(BB->getTerminator()))
257 exitBlocks.push_back(BB); // record this as an exit block
259 if (traceBasicBlockExits)
260 TraceValuesAtBBExit(BB, Printf, &valuesStoredInMethod);
263 if (traceMethodEvents)
264 for (unsigned i=0; i < exitBlocks.size(); ++i) {
266 TraceValuesAtBBExit(valuesStoredInMethod, exitBlocks[i], module,
267 /*indent*/ 0, /*isMethodExit*/ true,
268 /*valuesStoredInMethod*/ NULL);
270 InsertCodeToShowMethodExit(exitBlocks[i], Printf);