Reputation: 463
I'm learning LLVM using the C++ API and am trying to figure out how to create structures and use them. The problem I'm running into is that when I try to allocate the structure, it seg faults.
llvm::LLVMContext ctx;
llvm::IRBuilder<> builder(ctx);
std::unique_ptr<llvm::Module> module;
std::vector<llvm::Type *> types;
types.push_back(llvm::Type::getInt16Ty(ctx));
auto structType = llvm::StructType::create(ctx, "Foo");
structType->setBody(types);
auto bb = llvm::BasicBlock::Create(ctx, "entry", nullptr);
builder.SetInsertPoint(bb);
builder.CreateAlloca(structType, nullptr, "alloctmp");
I'm obviously missing something simple. Why does the CreateAlloca call seg fault?
After getting a debug version, it was seg faulting in the CreateAlloca code because BasicBlock was null. So, I added a BasicBlock and now it's seg faulting because GlobalValue is null. How should that get set?
Upvotes: 1
Views: 271
Reputation: 463
A couple important safety tips learned on this one.
std::unique_ptr<llvm::Module> module(new llvm::Module("mod", ctx));
auto ft = llvm::FunctionType::get(structType, types, false);
auto fn = llvm::Function::Create(ft, llvm::Function::ExternalLinkage, "func", module.get());
auto bb = llvm::BasicBlock::Create(ctx, "entry", fn);
Upvotes: 1