Rich
Rich

Reputation: 463

LLVM C++ API create struct seg faults

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

Answers (1)

Rich
Rich

Reputation: 463

A couple important safety tips learned on this one.

  1. A module must be created.
    std::unique_ptr<llvm::Module> module(new llvm::Module("mod", ctx));
  1. CreateAlloca allocates on the stack. Apparently there isn't one for top level stuff, so it has to be used within a function.
    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

Related Questions