1 //===-- ProgramInfo.cpp - Compute and cache info about a program ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ProgramInfo and related classes, by sorting through
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Debugger/ProgramInfo.h"
16 #include "llvm/Constants.h"
17 #include "llvm/DerivedTypes.h"
18 #include "llvm/Intrinsics.h"
19 #include "llvm/Instructions.h"
20 #include "llvm/Module.h"
21 #include "llvm/Debugger/SourceFile.h"
22 #include "llvm/Debugger/SourceLanguage.h"
23 #include "llvm/Support/SlowOperationInformer.h"
24 #include "llvm/ADT/STLExtras.h"
29 /// getGlobalVariablesUsing - Return all of the global variables which have the
30 /// specified value in their initializer somewhere.
31 static void getGlobalVariablesUsing(Value *V,
32 std::vector<GlobalVariable*> &Found) {
33 for (Value::use_iterator I = V->use_begin(), E = V->use_end(); I != E; ++I) {
34 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(*I))
36 else if (Constant *C = dyn_cast<Constant>(*I))
37 getGlobalVariablesUsing(C, Found);
41 /// getStringValue - Turn an LLVM constant pointer that eventually points to a
42 /// global into a string value. Return an empty string if we can't do it.
44 static std::string getStringValue(Value *V, unsigned Offset = 0) {
45 if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
46 if (GV->hasInitializer() && isa<ConstantArray>(GV->getInitializer())) {
47 ConstantArray *Init = cast<ConstantArray>(GV->getInitializer());
48 if (Init->isString()) {
49 std::string Result = Init->getAsString();
50 if (Offset < Result.size()) {
51 // If we are pointing INTO The string, erase the beginning...
52 Result.erase(Result.begin(), Result.begin()+Offset);
54 // Take off the null terminator, and any string fragments after it.
55 std::string::size_type NullPos = Result.find_first_of((char)0);
56 if (NullPos != std::string::npos)
57 Result.erase(Result.begin()+NullPos, Result.end());
62 } else if (Constant *C = dyn_cast<Constant>(V)) {
63 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
64 return getStringValue(GV, Offset);
65 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
66 if (CE->getOpcode() == Instruction::GetElementPtr) {
67 // Turn a gep into the specified offset.
68 if (CE->getNumOperands() == 3 &&
69 cast<Constant>(CE->getOperand(1))->isNullValue() &&
70 isa<ConstantInt>(CE->getOperand(2))) {
71 return getStringValue(CE->getOperand(0),
72 Offset+cast<ConstantInt>(CE->getOperand(2))->getRawValue());
80 /// getNextStopPoint - Follow the def-use chains of the specified LLVM value,
81 /// traversing the use chains until we get to a stoppoint. When we do, return
82 /// the source location of the stoppoint. If we don't find a stoppoint, return
84 static const GlobalVariable *getNextStopPoint(const Value *V, unsigned &LineNo,
86 // The use-def chains can fork. As such, we pick the lowest numbered one we
88 const GlobalVariable *LastDesc = 0;
89 unsigned LastLineNo = ~0;
90 unsigned LastColNo = ~0;
92 for (Value::use_const_iterator UI = V->use_begin(), E = V->use_end();
94 bool ShouldRecurse = true;
95 if (cast<Instruction>(*UI)->getOpcode() == Instruction::PHI) {
96 // Infinite loops == bad, ignore PHI nodes.
97 ShouldRecurse = false;
98 } else if (const CallInst *CI = dyn_cast<CallInst>(*UI)) {
99 // If we found a stop point, check to see if it is earlier than what we
100 // already have. If so, remember it.
101 if (const Function *F = CI->getCalledFunction())
102 if (F->getIntrinsicID() == Intrinsic::dbg_stoppoint) {
103 unsigned CurLineNo = ~0, CurColNo = ~0;
104 const GlobalVariable *CurDesc = 0;
105 if (const ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(2)))
106 CurLineNo = C->getRawValue();
107 if (const ConstantInt *C = dyn_cast<ConstantInt>(CI->getOperand(3)))
108 CurColNo = C->getRawValue();
109 const Value *Op = CI->getOperand(4);
111 if ((CurDesc = dyn_cast<GlobalVariable>(Op)) &&
112 (LineNo < LastLineNo ||
113 (LineNo == LastLineNo && ColNo < LastColNo))) {
115 LastLineNo = CurLineNo;
116 LastColNo = CurColNo;
118 ShouldRecurse = false;
123 // If this is not a phi node or a stopping point, recursively scan the users
124 // of this instruction to skip over region.begin's and the like.
126 unsigned CurLineNo, CurColNo;
127 if (const GlobalVariable *GV = getNextStopPoint(*UI, CurLineNo,CurColNo)){
128 if (LineNo < LastLineNo || (LineNo == LastLineNo && ColNo < LastColNo)){
130 LastLineNo = CurLineNo;
131 LastColNo = CurColNo;
138 LineNo = LastLineNo != ~0U ? LastLineNo : 0;
139 ColNo = LastColNo != ~0U ? LastColNo : 0;
145 //===----------------------------------------------------------------------===//
146 // SourceFileInfo implementation
149 SourceFileInfo::SourceFileInfo(const GlobalVariable *Desc,
150 const SourceLanguage &Lang)
151 : Language(&Lang), Descriptor(Desc) {
155 if (Desc && Desc->hasInitializer())
156 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
157 if (CS->getNumOperands() > 4) {
158 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CS->getOperand(1)))
159 Version = CUI->getValue();
161 BaseName = getStringValue(CS->getOperand(3));
162 Directory = getStringValue(CS->getOperand(4));
166 SourceFileInfo::~SourceFileInfo() {
170 SourceFile &SourceFileInfo::getSourceText() const {
171 // FIXME: this should take into account the source search directories!
172 if (SourceText == 0) { // Read the file in if we haven't already.
174 if (!Directory.empty())
175 tmpPath.set(Directory);
176 tmpPath.appendComponent(BaseName);
177 if (tmpPath.canRead())
178 SourceText = new SourceFile(tmpPath.toString(), Descriptor);
180 SourceText = new SourceFile(BaseName, Descriptor);
186 //===----------------------------------------------------------------------===//
187 // SourceFunctionInfo implementation
189 SourceFunctionInfo::SourceFunctionInfo(ProgramInfo &PI,
190 const GlobalVariable *Desc)
193 if (Desc && Desc->hasInitializer())
194 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
195 if (CS->getNumOperands() > 2) {
196 // Entry #1 is the file descriptor.
197 if (const GlobalVariable *GV =
198 dyn_cast<GlobalVariable>(CS->getOperand(1)))
199 SourceFile = &PI.getSourceFile(GV);
201 // Entry #2 is the function name.
202 Name = getStringValue(CS->getOperand(2));
206 /// getSourceLocation - This method returns the location of the first stopping
207 /// point in the function.
208 void SourceFunctionInfo::getSourceLocation(unsigned &RetLineNo,
209 unsigned &RetColNo) const {
210 // If we haven't computed this yet...
212 // Look at all of the users of the function descriptor, looking for calls to
213 // %llvm.dbg.func.start.
214 for (Value::use_const_iterator UI = Descriptor->use_begin(),
215 E = Descriptor->use_end(); UI != E; ++UI)
216 if (const CallInst *CI = dyn_cast<CallInst>(*UI))
217 if (const Function *F = CI->getCalledFunction())
218 if (F->getIntrinsicID() == Intrinsic::dbg_func_start) {
219 // We found the start of the function. Check to see if there are
220 // any stop points on the use-list of the function start.
221 const GlobalVariable *SD = getNextStopPoint(CI, LineNo, ColNo);
222 if (SD) { // We found the first stop point!
223 // This is just a sanity check.
224 if (getSourceFile().getDescriptor() != SD)
225 std::cout << "WARNING: first line of function is not in the"
226 " file that the function descriptor claims it is in.\n";
231 RetLineNo = LineNo; RetColNo = ColNo;
234 //===----------------------------------------------------------------------===//
235 // ProgramInfo implementation
238 ProgramInfo::ProgramInfo(Module *m) : M(m), ProgramTimeStamp(0,0) {
239 assert(M && "Cannot create program information with a null module!");
240 sys::Path modulePath(M->getModuleIdentifier());
241 ProgramTimeStamp = modulePath.getTimestamp();
243 SourceFilesIsComplete = false;
244 SourceFunctionsIsComplete = false;
247 ProgramInfo::~ProgramInfo() {
248 // Delete cached information about source program objects...
249 for (std::map<const GlobalVariable*, SourceFileInfo*>::iterator
250 I = SourceFiles.begin(), E = SourceFiles.end(); I != E; ++I)
252 for (std::map<const GlobalVariable*, SourceFunctionInfo*>::iterator
253 I = SourceFunctions.begin(), E = SourceFunctions.end(); I != E; ++I)
256 // Delete the source language caches.
257 for (unsigned i = 0, e = LanguageCaches.size(); i != e; ++i)
258 delete LanguageCaches[i].second;
262 //===----------------------------------------------------------------------===//
263 // SourceFileInfo tracking...
266 /// getSourceFile - Return source file information for the specified source file
267 /// descriptor object, adding it to the collection as needed. This method
268 /// always succeeds (is unambiguous), and is always efficient.
270 const SourceFileInfo &
271 ProgramInfo::getSourceFile(const GlobalVariable *Desc) {
272 SourceFileInfo *&Result = SourceFiles[Desc];
273 if (Result) return *Result;
275 // Figure out what language this source file comes from...
276 unsigned LangID = 0; // Zero is unknown language
277 if (Desc && Desc->hasInitializer())
278 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
279 if (CS->getNumOperands() > 2)
280 if (ConstantUInt *CUI = dyn_cast<ConstantUInt>(CS->getOperand(2)))
281 LangID = CUI->getValue();
283 const SourceLanguage &Lang = SourceLanguage::get(LangID);
284 SourceFileInfo *New = Lang.createSourceFileInfo(Desc, *this);
286 // FIXME: this should check to see if there is already a Filename/WorkingDir
287 // pair that matches this one. If so, we shouldn't create the duplicate!
289 SourceFileIndex.insert(std::make_pair(New->getBaseName(), New));
290 return *(Result = New);
294 /// getSourceFiles - Index all of the source files in the program and return
295 /// a mapping of it. This information is lazily computed the first time
296 /// that it is requested. Since this information can take a long time to
297 /// compute, the user is given a chance to cancel it. If this occurs, an
298 /// exception is thrown.
299 const std::map<const GlobalVariable*, SourceFileInfo*> &
300 ProgramInfo::getSourceFiles(bool RequiresCompleteMap) {
301 // If we have a fully populated map, or if the client doesn't need one, just
302 // return what we have.
303 if (SourceFilesIsComplete || !RequiresCompleteMap)
306 // Ok, all of the source file descriptors (compile_unit in dwarf terms),
307 // should be on the use list of the llvm.dbg.translation_units global.
309 GlobalVariable *Units =
310 M->getGlobalVariable("llvm.dbg.translation_units",
311 StructType::get(std::vector<const Type*>()));
313 throw "Program contains no debugging information!";
315 std::vector<GlobalVariable*> TranslationUnits;
316 getGlobalVariablesUsing(Units, TranslationUnits);
318 SlowOperationInformer SOI("building source files index");
320 // Loop over all of the translation units found, building the SourceFiles
322 for (unsigned i = 0, e = TranslationUnits.size(); i != e; ++i) {
323 getSourceFile(TranslationUnits[i]);
324 SOI.progress(i+1, e);
327 // Ok, if we got this far, then we indexed the whole program.
328 SourceFilesIsComplete = true;
332 /// getSourceFile - Look up the file with the specified name. If there is
333 /// more than one match for the specified filename, prompt the user to pick
334 /// one. If there is no source file that matches the specified name, throw
335 /// an exception indicating that we can't find the file. Otherwise, return
336 /// the file information for that file.
337 const SourceFileInfo &ProgramInfo::getSourceFile(const std::string &Filename) {
338 std::multimap<std::string, SourceFileInfo*>::const_iterator Start, End;
340 tie(Start, End) = SourceFileIndex.equal_range(Filename);
342 if (Start == End) throw "Could not find source file '" + Filename + "'!";
343 const SourceFileInfo &SFI = *Start->second;
345 if (Start == End) return SFI;
347 throw "FIXME: Multiple source files with the same name not implemented!";
351 //===----------------------------------------------------------------------===//
352 // SourceFunctionInfo tracking...
356 /// getFunction - Return function information for the specified function
357 /// descriptor object, adding it to the collection as needed. This method
358 /// always succeeds (is unambiguous), and is always efficient.
360 const SourceFunctionInfo &
361 ProgramInfo::getFunction(const GlobalVariable *Desc) {
362 SourceFunctionInfo *&Result = SourceFunctions[Desc];
363 if (Result) return *Result;
365 // Figure out what language this function comes from...
366 const GlobalVariable *SourceFileDesc = 0;
367 if (Desc && Desc->hasInitializer())
368 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Desc->getInitializer()))
369 if (CS->getNumOperands() > 0)
370 if (const GlobalVariable *GV =
371 dyn_cast<GlobalVariable>(CS->getOperand(1)))
374 const SourceLanguage &Lang = getSourceFile(SourceFileDesc).getLanguage();
375 return *(Result = Lang.createSourceFunctionInfo(Desc, *this));
379 // getSourceFunctions - Index all of the functions in the program and return
380 // them. This information is lazily computed the first time that it is
381 // requested. Since this information can take a long time to compute, the user
382 // is given a chance to cancel it. If this occurs, an exception is thrown.
383 const std::map<const GlobalVariable*, SourceFunctionInfo*> &
384 ProgramInfo::getSourceFunctions(bool RequiresCompleteMap) {
385 if (SourceFunctionsIsComplete || !RequiresCompleteMap)
386 return SourceFunctions;
388 // Ok, all of the source function descriptors (subprogram in dwarf terms),
389 // should be on the use list of the llvm.dbg.translation_units global.
391 GlobalVariable *Units =
392 M->getGlobalVariable("llvm.dbg.globals",
393 StructType::get(std::vector<const Type*>()));
395 throw "Program contains no debugging information!";
397 std::vector<GlobalVariable*> Functions;
398 getGlobalVariablesUsing(Units, Functions);
400 SlowOperationInformer SOI("building functions index");
402 // Loop over all of the functions found, building the SourceFunctions mapping.
403 for (unsigned i = 0, e = Functions.size(); i != e; ++i) {
404 getFunction(Functions[i]);
405 SOI.progress(i+1, e);
408 // Ok, if we got this far, then we indexed the whole program.
409 SourceFunctionsIsComplete = true;
410 return SourceFunctions;