如何从 LLVM 指令中获取文件名和目录?

How to get the filename and directory from a LLVM Instruction?

我需要在 llvm 传递过程中提取目录和文件名。 当前版本的 llvm 将 getFilenamegetDirectoryDebugLoc 移动到 DebugInfoMetadata。我无法直接在 DebugLoc header 中找到 class 成员 getFilename。因此,如何从指令转到源代码文件名和目录?

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

此外,还有一个可能有用的打印功能,但它只需要一个 llvm::raw_ostream 并且不能重定向到一个 std::string

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

下面的代码给出了错误

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

---我几分钟前想到的解决方案----

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

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();
F.getParent()->getSourceFileName();

其中 F 是您要为其获取源文件名的函数。