#include #include #include #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include #include #include #include #include #include #include #include #include #include #include #include "tokens.h" void llvm_hello_world(); std::string read_file(char* filepath) { std::ifstream input{ filepath }; if (!input) { std::cerr << "Failed to read " << filepath << std::endl; return {}; } std::string out{}; std::string currLine; while (std::getline(input, currLine)) { if (out.length() > 0) { out = out + "\n"; } out = out + currLine; } return out; } int main() { std::string out{ read_file("test.c") }; std::cout << out << std::endl; auto tokens = token::tokenize(out); for (token::Token token : tokens) { std::cout << token << std::endl; } auto stream = token::TokenStream{ tokens }; stream.expect(token::Type::Eof); // LLVM Hello World // llvm_hello_world(); std::cout << "hello" << std::endl; return 0; } void llvm_hello_world() { auto Context = std::make_unique(); auto Module = std::make_unique("my cool module", *Context); auto Builder = std::make_unique>(*Context); llvm::FunctionType* FunType = llvm::FunctionType::get(llvm::Type::getInt32Ty(*Context), false); llvm::Function* Function = llvm::Function::Create( FunType, llvm::GlobalValue::LinkageTypes::ExternalLinkage, "main", *Module); llvm::BasicBlock* BB = llvm::BasicBlock::Create(*Context, "entry", Function, nullptr); Builder->SetInsertPoint(BB); llvm::Value* value = llvm::ConstantInt::get(llvm::Type::getInt32Ty(*Context), 5); Builder->CreateRet(value); llvm::verifyFunction(*Function); llvm::InitializeAllTargetInfos(); llvm::InitializeAllTargets(); llvm::InitializeAllTargetMCs(); llvm::InitializeAllAsmParsers(); llvm::InitializeAllAsmPrinters(); auto TargetTriple = llvm::sys::getDefaultTargetTriple(); std::string Error; auto Target = llvm::TargetRegistry::lookupTarget(TargetTriple, Error); llvm::TargetOptions opt; auto TargetMachine = Target->createTargetMachine(TargetTriple, "generic", "", opt, llvm::Reloc::PIC_); Module->setDataLayout(TargetMachine->createDataLayout()); std::string out; llvm::raw_string_ostream dest{ out }; Module->print(dest, nullptr); dest.flush(); std::cout << out << std::endl; }