Unable to conversion in Expected<unique_ptr<Module>> to Module - c++

I am new to llvm , writing the program "main.cpp" of https://github.com/davidar/lljvm/blob/master/backend/main.cpp.
I stuck at the error while executing the command : "pm.run(m)"
error: no matching function for call to ‘llvm::legacy::PassManager::run(llvm::Expected<std::unique_ptr<llvm::Module> >&)
Here is my source code:
#include "backened.h"
#include <iostream>
#include "llvm/Bitcode/BitcodeReader.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ErrorOr.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/IR/PassManager.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/IR/DataLayout.h"
#include <llvm/Transforms/Scalar.h>
#include "llvm/IR/LegacyPassManager.h"
using namespace llvm;
using namespace std;
static cl::opt<string> input(cl::Positional, cl::desc("Bitcode File.."),cl::Required);
static cl::opt<string> classname("classname",cl::desc("Binary name of the generated class..."));
int main(int argc, char** argv)
{
cl::ParseCommandLineOptions(argc, argv, "Hi..");
LLVMContext context;
ErrorOr<unique_ptr<MemoryBuffer>> mb = MemoryBuffer::getFile(input);
if(error_code ec = mb.getError()) {
errs() << ec.message();
return 1;
}
Expected<unique_ptr<Module>> m = parseBitcodeFile(mb->get()->getMemBufferRef(),context);
if(error_code ec= errorToErrorCode(m.takeError()) )
{
errs() <<"Unable to read bitcode file.." <<ec.message() ;
}
PassManager<Module> pm;
pm.add(createVerifierPass());
pm.add(createGCLoweringPass());
pm.add(createLowerSwitchPass());
pm.add(createCFGSimplificationPass());
pm.add(new JVMWriter(fouts(), classname, debugLevel));
pm.add(createGCInfoDeleter());
pm.run(*m);
return 0;
}
Please help me.

Related

C++ regex cstring error

I wrote this code:
#include <iostream>
#include <fstream>
#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <regex>
using namespace std;
int compile()
{
string linecode;
linecode = "_hello:";
if (std::regex_match (linecode, std::regex("(_)(.*)(:)") ))
{
cout<<"...";
}
else if (std::regex_match (linecode, std::regex("(#)(.*)(:)") ))
{
cout<<"###";
}
return 1;
}
int main(int argc, char** argv)
{
compile();
return 0;
}
And i get this error:
enter image description here
cstring error, probably in regex library.
How i can fix this ?
Thanks in advance.

prepare for calling ParseAST. Fatal error

I'm reading the book Getting Started with LLVM Core Libraries and trying to implement an example from page 100 Chapter 4: Frontend. But got an error on the last line of code clang::ParseAST(CI.getSema());:
[bash#bash book]$ ./book_clang test.c
fatal error: error opening file '<invalid loc>':
What should I add to prepare for ParseAST?
code:
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/Support/CommandLine.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "llvm/Support/Host.h"
#include <memory>
#include <string>
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/ASTConsumers.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Parse/ParseAST.h"
#include "clang/AST/ASTContext.h"
static llvm::cl::opt<std::string> fileName(llvm::cl::Positional, llvm::cl::desc("Input file"), llvm::cl::Required);
int main(int argc, char **argv)
{
llvm::cl::ParseCommandLineOptions(argc, argv, "My simple front end\n");
clang::CompilerInstance CI;
clang::DiagnosticOptions diagnosticOptions;
CI.createDiagnostics();
std::shared_ptr<clang::TargetOptions> PTO = std::make_shared<clang::TargetOptions>();
PTO->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo *PTI = clang::TargetInfo::CreateTargetInfo(CI.getDiagnostics(), PTO);
CI.setTarget(PTI);
CI.createFileManager();//References getFileSystemOpts(), clang::vfs::getRealFileSystem(), hasVirtualFileSystem(), and setVirtualFileSystem().
CI.createSourceManager( CI.getFileManager());//References getDiagnostics().
CI.createPreprocessor(clang::TU_Complete);
CI.getPreprocessorOpts().UsePredefines = false;
std::unique_ptr< clang::ASTConsumer > astConsumer = clang::CreateASTPrinter(NULL, "");
CI.setASTConsumer(std::move(astConsumer));
CI.createASTContext();
CI.createSema(clang::TU_Complete, NULL);//after getASTConsumer(), getASTContext(), and getPreprocessor().
const clang::FileEntry *file = CI.getFileManager().getFile(fileName);
if (!file) {
llvm::errs() << "File not found: " << fileName;
return 1;
}
CI.getSourceManager().createFileID(file, clang::SourceLocation(), clang::SrcMgr::C_User);
CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
clang::ParseAST(CI.getSema());
// Print AST statistics
// CI.getASTContext().PrintStats();
// CI.getASTContext().Idents.PrintStats();
return 0;
}
for executable need to pass c-file, for example:
test.c
int main() {
char *msg = "Hello, world!\n";
write(1, msg, 14);
return 0;
}
the problem is solved. Need to set MainFileID for CompilerInstence's SourceManager
clang::FileID mainFileID = CI.getSourceManager().createFileID(file, clang::SourceLocation(), clang::SrcMgr::C_User);
CI.getSourceManager().setMainFileID(mainFileID);
The problem was that clang::ParseAST calls (S is Sema) S.getPreprocessor().EnterMainSourceFile(); that calls SourceMgr.getMainFileID();
void Preprocessor::EnterMainSourceFile() {
assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
FileID MainFileID = SourceMgr.getMainFileID();
But MainFileID was'n set
corrected full code is:
#include "llvm/Support/CommandLine.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/TargetOptions.h"
#include "llvm/Support/Host.h"
#include <memory>
#include <string>
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/PreprocessorOptions.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Frontend/ASTConsumers.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Parse/ParseAST.h"
#include "clang/AST/ASTContext.h"
static llvm::cl::opt<std::string> fileName(llvm::cl::Positional, llvm::cl::desc("Input file"), llvm::cl::Required);
int main(int argc, char **argv)
{
llvm::cl::ParseCommandLineOptions(argc, argv, "My simple front end\n");
clang::CompilerInstance CI;
clang::DiagnosticOptions diagnosticOptions;
CI.createDiagnostics();
std::shared_ptr<clang::TargetOptions> PTO = std::make_shared<clang::TargetOptions>();
PTO->Triple = llvm::sys::getDefaultTargetTriple();
clang::TargetInfo *PTI = clang::TargetInfo::CreateTargetInfo(CI.getDiagnostics(), PTO);
CI.setTarget(PTI);
CI.createFileManager();//References getFileSystemOpts(), clang::vfs::getRealFileSystem(), hasVirtualFileSystem(), and setVirtualFileSystem().
CI.createSourceManager( CI.getFileManager());//References getDiagnostics().
CI.createPreprocessor(clang::TU_Complete);
CI.getPreprocessorOpts().UsePredefines = false;
std::unique_ptr< clang::ASTConsumer > astConsumer = clang::CreateASTPrinter(NULL, "");
CI.setASTConsumer(std::move(astConsumer));
CI.createASTContext();
CI.createSema(clang::TU_Complete, NULL);//after getASTConsumer(), getASTContext(), and getPreprocessor().
const clang::FileEntry *file = CI.getFileManager().getFile(fileName);
if (!file) {
llvm::errs() << "File not found: " << fileName;
return 1;
}
clang::FileID mainFileID = CI.getSourceManager().createFileID(file, clang::SourceLocation(), clang::SrcMgr::C_User);
CI.getSourceManager().setMainFileID(mainFileID);
CI.getDiagnosticClient().BeginSourceFile(CI.getLangOpts(), 0);
clang::ParseAST(CI.getSema());
// Print AST statistics
CI.getASTContext().PrintStats();
CI.getASTContext().Idents.PrintStats();
return 0;
}

Loading an image from a folder using OpenCV 3.0 in Windows

I am using Visual Studio 2010, with OpenCV 3.0. I'm trying to load some images from a folder but I am having problems.
Firstly I did not have the file dirent.h, so I downloaded it in order to get the DIR* and "dirent*" structures to access to the files. All seems to be well, but now when I get to the line
string fileName = in_file->d_name;
I have found that I don't access to the name of the file.
Anyone have any thoughts on this?
This is the code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <opencv2/core/dirent.h>
#ifdef _WIN32
#include <io.h>
#else
#include <unistd.h>
#endif
#include <conio.h>
#include <windows.h>
#include <tchar.h>
#include <stdio.h>
#include <strsafe.h>
#pragma comment(lib, "User32.lib")
#include <errno.h>
#include <iostream>
#include <time.h>
#include <limits.h>
#include <fstream>
#include <sys/stat.h>
#include <opencv2/core.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/ml.hpp>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace cv::ml;
using namespace std;
int patchWidth = 15;
int patchHeight = 15;
int main(int, char**)
{
string imagesPath = "Images";
string resultsPath = "Patches";
DIR* FD;
struct dirent* in_file;
if (NULL == (FD = opendir (imagesPath.c_str())))
{
fprintf(stderr, "Error : Failed to open input directory\n");
return 0;
}
while ((in_file = readdir(FD)))
{
/* On linux/Unix we don't want current and parent directories
* If you're on Windows machine remove this two lines
*/
// if (!strcmp (in_file->d_name, "."))
// continue;
// if (!strcmp (in_file->d_name, ".."))
// continue;
/* Open directory entry file for common operation */
/* TODO : change permissions to meet your need! */
string fileName = in_file->d_name;
string pathFile = imagesPath;
pathFile.append("/");
pathFile.append(fileName);
//pathFile.append(".jpg");
Mat img = imread(pathFile.c_str());
Thanks in advance.
for a much simpler solution, just use cv::glob :
String imagesPath = "Images/*.png"; // it has filters, too !
vector<String> fn;
glob(path, fn, true); // recursive, if you want
for (size_t i=0; i<fn.size(); i++)
{
Mat img = imread(fn[i]);
...
}

failing to parse C++ using llvm and clang

I'm writing a little tool with llvm to parse C and C++ code, but I can't seem to get it to successfully parse C++ at all. I'm probably missing something obvious.
This is what I have so far:
#include <iostream>
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/CompilerInvocation.h"
#include "clang/Frontend/FrontendOptions.h"
#include "clang/Frontend/LangStandard.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Lex/HeaderSearch.h"
#include "clang/Lex/DirectoryLookup.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/Parse/ParseAST.h"
class MyASTConsumer : public clang::ASTConsumer {
public:
bool HandleTopLevelDecl(clang::DeclGroupRef d);
virtual ~MyASTConsumer() { }
};
bool MyASTConsumer::HandleTopLevelDecl(clang::DeclGroupRef d)
{
for(auto ii = d.begin(); ii != d.end(); ii++)
{
printf("decl type: %s\n", (*ii)->getDeclKindName());
auto namedDecl = llvm::dyn_cast<clang::NamedDecl>(*ii);
if(namedDecl)
{
printf("name: %s\n", namedDecl->getName().data());
}
}
return true;
}
int main(int, char **argv)
{
using clang::CompilerInstance;
using clang::TargetOptions;
using clang::TargetInfo;
using clang::FileEntry;
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
using clang::SrcMgr::CharacteristicKind;
using clang::StringRef;
using clang::DirectoryLookup;
using llvm::MemoryBuffer;
using clang::LangOptions;
using clang::FrontendOptions;
using clang::LangStandard;
using clang::CompilerInvocation;
using clang::InitializePreprocessor;
using clang::Preprocessor;
using clang::PreprocessorOptions;
using clang::HeaderSearch;
using clang::HeaderSearchOptions;
CompilerInstance ci;
DiagnosticOptions diagnosticOptions;
ci.createDiagnostics();
CompilerInvocation *invocation = new CompilerInvocation;
LangOptions &langOpts = ci.getLangOpts();
langOpts.RTTI = 1;
langOpts.Bool = 1;
langOpts.CPlusPlus11 = 1;
langOpts.GNUKeywords = 1;
langOpts.CXXExceptions = 1;
langOpts.POSIXThreads = 1;
langOpts.SpellChecking = 1;
invocation->setLangDefaults(langOpts, clang::IK_CXX, LangStandard::lang_gnucxx11);
ci.setInvocation(invocation);
llvm::IntrusiveRefCntPtr<TargetOptions> pto( new TargetOptions() );
pto->Triple = llvm::sys::getDefaultTargetTriple();
llvm::IntrusiveRefCntPtr<TargetInfo> pti(TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto.getPtr()));
ci.setTarget(pti.getPtr());
ci.createFileManager();
auto &fileManager = ci.getFileManager();
ci.createSourceManager(fileManager);
llvm::IntrusiveRefCntPtr<HeaderSearchOptions> headerSearchOpts( new HeaderSearchOptions() );
ci.createPreprocessor();
auto &pp = ci.getPreprocessor();
pp.setPredefines(builtinMacros);
HeaderSearch &headerSearch = pp.getHeaderSearchInfo();
for(auto &inc: builtinIncludePaths)
{
auto dirEntry = fileManager.getDirectory(StringRef(inc), true);
DirectoryLookup dirLookup(dirEntry, CharacteristicKind::C_System, false);
headerSearch.AddSearchPath (dirLookup, true);
}
MyASTConsumer *astConsumer = new MyASTConsumer();
ci.setASTConsumer(astConsumer);
ci.createASTContext();
const FileEntry *pFile = fileManager.getFile(argv[1]);
auto &sourceManager = ci.getSourceManager();
sourceManager.createMainFileID(pFile);
ci.getDiagnosticClient().BeginSourceFile(
ci.getLangOpts(),
&pp
);
clang::ParseAST(pp, astConsumer, ci.getASTContext());
ci.getDiagnosticClient().EndSourceFile();
return 0;
}
It does parse C just fine, but it errors out on the namespace keyword and extern "C" { blocks. So far I'm stumped. If anyone has a clue, something I'm missing, please share.
I believe I figured out the problem. You should always call setInvocation on the compiler instance before calling a lot of the methods on the compiler instance, as it actually just proxies to the invocation.
I moved the setInvocation call to right after the CompilerInvocation object is created, and things now work.

segfault at the end of the main()

I am compiling a program agains LLVM-CLANG. This is the main
#include <iostream>
#include "CompilerFactory.h"
#include "clang/Basic/FileManager.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Basic/Diagnostic.h"
int main(int argc, char const *argv[])
{
using clang::CompilerInstance;
using clang::TargetOptions;
using clang::TargetInfo;
using clang::FileEntry;
using clang::Token;
using clang::DiagnosticOptions;
using clang::TextDiagnosticPrinter;
CompilerInstance ci;
CSFV::CompilerFactory::GetCompilerInstance(ci);
const FileEntry *pFile = ci.getFileManager().getFile("test.c");
ci.getSourceManager().createMainFileID(pFile);
ci.getPreprocessor().EnterMainSourceFile();
ci.getDiagnosticClient().BeginSourceFile(ci.getLangOpts(),
&ci.getPreprocessor());
Token tok;
do
{
ci.getPreprocessor().Lex(tok);
if (ci.getDiagnostics().hasErrorOccurred())
break;
ci.getPreprocessor().DumpToken(tok);
std::cerr << std::endl;
} while (tok.isNot(clang::tok::eof));
ci.getDiagnosticClient().EndSourceFile();
return 0;
}
and this is the included class
//If they are not defined we have an error at compile time
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#include "llvm/Support/Host.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Frontend/TextDiagnosticPrinter.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/TargetOptions.h"
#include "clang/Basic/TargetInfo.h"
using namespace clang;
namespace CSFV{
class CompilerFactory
{
public:
CompilerFactory();
~CompilerFactory();
/// \brief Generate and returns a compiler instance object
static void GetCompilerInstance(CompilerInstance &ci){
DiagnosticOptions diagOpts;
TextDiagnosticPrinter* diagPrinter =
new TextDiagnosticPrinter(llvm::outs(), &diagOpts, true);
ci.createDiagnostics(diagPrinter);
llvm::IntrusiveRefCntPtr<TargetOptions> pto (new TargetOptions());
pto->Triple = llvm::sys::getDefaultTargetTriple();
TargetInfo *pti =
TargetInfo::CreateTargetInfo(ci.getDiagnostics(), pto.getPtr());
ci.setTarget(pti);
ci.createFileManager();
ci.createSourceManager(ci.getFileManager());
ci.createPreprocessor();
return;
}
};
} //end of namespace CSFV
For some reason I get a segfault at the end of the execution of the main. What am I missing?
I don't know if this is the same problem I had, but what I did was declare the targetoptions as a new pointer.
eg:
clang::TargetOptions *targetOpts=new clang::TargetOptions;
I have a feeling targetinfo cleans it up when itself is destroyed.