blob: 17175c4e4cf1beafc5de4076d365dcb7992695d8 [file] [log] [blame]
Chris Lattner2eacf262004-01-05 05:25:10 +00001//===-- ProgramInfo.cpp - Compute and cache info about a program ----------===//
2//
3// The LLVM Compiler Infrastructure
4//
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.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the ProgramInfo and related classes, by sorting through
11// the loaded Module.
12//
13//===----------------------------------------------------------------------===//
14
15#include "llvm/Debugger/ProgramInfo.h"
16#include "llvm/Constants.h"
17#include "llvm/DerivedTypes.h"
18#include "llvm/Intrinsics.h"
Chris Lattner4ab78e02004-07-29 17:15:38 +000019#include "llvm/Instructions.h"
Chris Lattner2eacf262004-01-05 05:25:10 +000020#include "llvm/Module.h"
21#include "llvm/Debugger/SourceFile.h"
22#include "llvm/Debugger/SourceLanguage.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000023#include "llvm/Support/SlowOperationInformer.h"
24#include "llvm/ADT/STLExtras.h"
Reid Spencer954da372004-07-04 12:19:56 +000025#include <iostream>
26
Chris Lattner2eacf262004-01-05 05:25:10 +000027using namespace llvm;
28
29/// getGlobalVariablesUsing - Return all of the global variables which have the
30/// specified value in their initializer somewhere.
31static 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))
35 Found.push_back(GV);
36 else if (Constant *C = dyn_cast<Constant>(*I))
37 getGlobalVariablesUsing(C, Found);
38 }
39}
40
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.
43///
44static 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());
Chris Lattnere3f84f52004-01-14 17:07:46 +000048 if (Init->isString()) {
Chris Lattner2eacf262004-01-05 05:25:10 +000049 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);
53
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());
58 return Result;
59 }
60 }
61 }
62 } else if (Constant *C = dyn_cast<Constant>(V)) {
Reid Spencer518310c2004-07-18 00:44:37 +000063 if (GlobalValue *GV = dyn_cast<GlobalValue>(C))
64 return getStringValue(GV, Offset);
Chris Lattner2eacf262004-01-05 05:25:10 +000065 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());
73 }
74 }
75 }
76 }
77 return "";
78}
79
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
83/// null.
84static const GlobalVariable *getNextStopPoint(const Value *V, unsigned &LineNo,
85 unsigned &ColNo) {
86 // The use-def chains can fork. As such, we pick the lowest numbered one we
87 // find.
88 const GlobalVariable *LastDesc = 0;
89 unsigned LastLineNo = ~0;
90 unsigned LastColNo = ~0;
91
92 for (Value::use_const_iterator UI = V->use_begin(), E = V->use_end();
93 UI != E; ++UI) {
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);
Chris Lattner2eacf262004-01-05 05:25:10 +0000110
111 if ((CurDesc = dyn_cast<GlobalVariable>(Op)) &&
112 (LineNo < LastLineNo ||
113 (LineNo == LastLineNo && ColNo < LastColNo))) {
114 LastDesc = CurDesc;
115 LastLineNo = CurLineNo;
116 LastColNo = CurColNo;
117 }
118 ShouldRecurse = false;
119 }
120
121 }
122
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.
125 if (ShouldRecurse) {
126 unsigned CurLineNo, CurColNo;
127 if (const GlobalVariable *GV = getNextStopPoint(*UI, CurLineNo,CurColNo)){
128 if (LineNo < LastLineNo || (LineNo == LastLineNo && ColNo < LastColNo)){
129 LastDesc = GV;
130 LastLineNo = CurLineNo;
131 LastColNo = CurColNo;
132 }
133 }
134 }
135 }
136
137 if (LastDesc) {
138 LineNo = LastLineNo != ~0U ? LastLineNo : 0;
139 ColNo = LastColNo != ~0U ? LastColNo : 0;
140 }
141 return LastDesc;
142}
143
144
145//===----------------------------------------------------------------------===//
146// SourceFileInfo implementation
147//
148
149SourceFileInfo::SourceFileInfo(const GlobalVariable *Desc,
150 const SourceLanguage &Lang)
151 : Language(&Lang), Descriptor(Desc) {
152 Version = 0;
153 SourceText = 0;
154
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();
160
161 BaseName = getStringValue(CS->getOperand(3));
162 Directory = getStringValue(CS->getOperand(4));
163 }
164}
165
166SourceFileInfo::~SourceFileInfo() {
167 delete SourceText;
168}
169
170SourceFile &SourceFileInfo::getSourceText() const {
171 // FIXME: this should take into account the source search directories!
Reid Spencer663601c2004-12-13 02:59:15 +0000172 if (SourceText == 0) { // Read the file in if we haven't already.
173 sys::Path tmpPath;
174 if (!Directory.empty())
175 tmpPath.setDirectory(Directory);
176 tmpPath.appendFile(BaseName);
177 if (tmpPath.readable())
178 SourceText = new SourceFile(tmpPath.toString(), Descriptor);
Chris Lattner2eacf262004-01-05 05:25:10 +0000179 else
180 SourceText = new SourceFile(BaseName, Descriptor);
Reid Spencer663601c2004-12-13 02:59:15 +0000181 }
Chris Lattner2eacf262004-01-05 05:25:10 +0000182 return *SourceText;
183}
184
185
186//===----------------------------------------------------------------------===//
187// SourceFunctionInfo implementation
188//
189SourceFunctionInfo::SourceFunctionInfo(ProgramInfo &PI,
190 const GlobalVariable *Desc)
191 : Descriptor(Desc) {
192 LineNo = ColNo = 0;
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.
Reid Spencer518310c2004-07-18 00:44:37 +0000197 if (const GlobalVariable *GV =
198 dyn_cast<GlobalVariable>(CS->getOperand(1)))
199 SourceFile = &PI.getSourceFile(GV);
Chris Lattner2eacf262004-01-05 05:25:10 +0000200
201 // Entry #2 is the function name.
202 Name = getStringValue(CS->getOperand(2));
203 }
204}
205
206/// getSourceLocation - This method returns the location of the first stopping
207/// point in the function.
208void SourceFunctionInfo::getSourceLocation(unsigned &RetLineNo,
209 unsigned &RetColNo) const {
210 // If we haven't computed this yet...
211 if (!LineNo) {
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";
227 break;
228 }
229 }
230 }
231 RetLineNo = LineNo; RetColNo = ColNo;
232}
233
234//===----------------------------------------------------------------------===//
235// ProgramInfo implementation
236//
237
Reid Spencer9d88d1a2004-12-13 17:01:53 +0000238ProgramInfo::ProgramInfo(Module *m) : M(m), ProgramTimeStamp(0,0) {
Chris Lattner2eacf262004-01-05 05:25:10 +0000239 assert(M && "Cannot create program information with a null module!");
Reid Spencer9d88d1a2004-12-13 17:01:53 +0000240 sys::Path modulePath(M->getModuleIdentifier());
241 ProgramTimeStamp = modulePath.getTimestamp();
Chris Lattner2eacf262004-01-05 05:25:10 +0000242
243 SourceFilesIsComplete = false;
244 SourceFunctionsIsComplete = false;
245}
246
247ProgramInfo::~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)
251 delete I->second;
252 for (std::map<const GlobalVariable*, SourceFunctionInfo*>::iterator
253 I = SourceFunctions.begin(), E = SourceFunctions.end(); I != E; ++I)
254 delete I->second;
255
256 // Delete the source language caches.
257 for (unsigned i = 0, e = LanguageCaches.size(); i != e; ++i)
258 delete LanguageCaches[i].second;
259}
260
261
262//===----------------------------------------------------------------------===//
263// SourceFileInfo tracking...
264//
265
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.
269///
270const SourceFileInfo &
271ProgramInfo::getSourceFile(const GlobalVariable *Desc) {
272 SourceFileInfo *&Result = SourceFiles[Desc];
273 if (Result) return *Result;
274
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();
282
283 const SourceLanguage &Lang = SourceLanguage::get(LangID);
284 SourceFileInfo *New = Lang.createSourceFileInfo(Desc, *this);
285
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!
288 //
289 SourceFileIndex.insert(std::make_pair(New->getBaseName(), New));
290 return *(Result = New);
291}
292
293
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.
299const std::map<const GlobalVariable*, SourceFileInfo*> &
300ProgramInfo::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)
304 return SourceFiles;
305
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.
308 //
309 GlobalVariable *Units =
310 M->getGlobalVariable("llvm.dbg.translation_units",
311 StructType::get(std::vector<const Type*>()));
312 if (Units == 0)
313 throw "Program contains no debugging information!";
314
315 std::vector<GlobalVariable*> TranslationUnits;
316 getGlobalVariablesUsing(Units, TranslationUnits);
317
318 SlowOperationInformer SOI("building source files index");
319
320 // Loop over all of the translation units found, building the SourceFiles
321 // mapping.
322 for (unsigned i = 0, e = TranslationUnits.size(); i != e; ++i) {
323 getSourceFile(TranslationUnits[i]);
324 SOI.progress(i+1, e);
325 }
326
327 // Ok, if we got this far, then we indexed the whole program.
328 SourceFilesIsComplete = true;
329 return SourceFiles;
330}
331
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.
337const SourceFileInfo &ProgramInfo::getSourceFile(const std::string &Filename) {
338 std::multimap<std::string, SourceFileInfo*>::const_iterator Start, End;
339 getSourceFiles();
340 tie(Start, End) = SourceFileIndex.equal_range(Filename);
341
342 if (Start == End) throw "Could not find source file '" + Filename + "'!";
343 const SourceFileInfo &SFI = *Start->second;
344 ++Start;
345 if (Start == End) return SFI;
346
347 throw "FIXME: Multiple source files with the same name not implemented!";
348}
349
350
351//===----------------------------------------------------------------------===//
352// SourceFunctionInfo tracking...
353//
354
355
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.
359///
360const SourceFunctionInfo &
361ProgramInfo::getFunction(const GlobalVariable *Desc) {
362 SourceFunctionInfo *&Result = SourceFunctions[Desc];
363 if (Result) return *Result;
364
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)
Reid Spencer518310c2004-07-18 00:44:37 +0000370 if (const GlobalVariable *GV =
371 dyn_cast<GlobalVariable>(CS->getOperand(1)))
372 SourceFileDesc = GV;
Chris Lattner2eacf262004-01-05 05:25:10 +0000373
374 const SourceLanguage &Lang = getSourceFile(SourceFileDesc).getLanguage();
375 return *(Result = Lang.createSourceFunctionInfo(Desc, *this));
376}
377
378
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.
383const std::map<const GlobalVariable*, SourceFunctionInfo*> &
384ProgramInfo::getSourceFunctions(bool RequiresCompleteMap) {
385 if (SourceFunctionsIsComplete || !RequiresCompleteMap)
386 return SourceFunctions;
387
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.
390 //
391 GlobalVariable *Units =
392 M->getGlobalVariable("llvm.dbg.globals",
393 StructType::get(std::vector<const Type*>()));
394 if (Units == 0)
395 throw "Program contains no debugging information!";
396
397 std::vector<GlobalVariable*> Functions;
398 getGlobalVariablesUsing(Units, Functions);
399
400 SlowOperationInformer SOI("building functions index");
401
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);
406 }
407
408 // Ok, if we got this far, then we indexed the whole program.
409 SourceFunctionsIsComplete = true;
410 return SourceFunctions;
411}