How to get the filename and directory from a LLVM

2020-07-18 02:11发布

问题:

I need to extract the directory and filename during a llvm pass. The current version of llvm moved getFilename and getDirectory from DebugLoc to DebugInfoMetadata. I can't find a class member getFilename directly in the DebugLoc header. Thus, how to do I go from an instruction to source code filename and directory?

http://llvm.org/docs/doxygen/html/classllvm_1_1DebugLoc.html

Additionally, there is a print function that might help but it only takes a llvm::raw_ostream and can't be redirected to a std::string.

void print (raw_ostream &OS) const
// prints source location /path/to/file.exe:line:col @[inlined at]

The code below is what gives the error

const DebugLoc &location = an_instruction_iter->getDebugLoc()
StringRef File = location->getFilename() // Gives an error

---solution I figured out a few minutes ago----

const DebugLoc &location = i_iter->getDebugLoc();
const DILocation *test =location.get();
test->getFilename();`

回答1:

1)

std::string dbgInfo;
llvm::raw_string_ostream rso(dbgInfo);
location->print(rso);
std::sting dbgStr = rso.str()

2)

auto *Scope = cast<DIScope>(location->getScope());
std::string fileName = Scope->getFilename();


回答2:

F.getParent()->getSourceFileName();

Where F is the function for which you want to get the source filename.