Executing a FrontendAction on a MemoryBuffer


I’m currently using the following code(excerpted) to execute a FrontendAction(an EmitObjAction specifically) on source code contained in a MemoryBuffer:

llvm::MemoryBuffer* Buffer = llvm::MemoryBuffer::getMemBuffer(Source);
SourceManager& SM = Clang.getSourceManager();
FileID MainFileID = SM.createMainFileIDForMemBuffer(Buffer);

EmitObjAction E;

The code fails at “E.Execute()” with:

Assertion failed: (!CurrentFile.empty() && “No current file!”), function isCurrentFileAST, file /Volumes/Data/Users/mike/llvm/tools/clang/lib/Frontend/…/…/include/clang/Frontend/FrontendAction.h, line 95.

I looked up the FrontendAction::setCurrentFile method, but it takes in a StringRef to a path. Since I don’t have a path to a file, as I’m only operating on source code in memory, I’m not able to set the current file.

How can I set the current file to point to a MemoryBuffer?


Some folks on #llvm helped me with this - the solution is to create a virtual file using FileManager::getVirtualFile, and populate it with the buffer’s contents using SourceManager::overrideFileContents, then pass the virtual file to the FrontendAction.

Hope that helps,