我正在尝试用 LLVM 和 C++ 编写一个玩具编译器。但是,每当我尝试创建具有多个索引的 GetElementPtrInst 时,都会出现 Segfault。有关此指令的文档对我没有帮助(API-Documentation Language-Documentation)
我的 llvm 版本是 3.1,这是在 Arch Linux 上。刚刚在另一台 Arch 机器上测试它并得到了同样的错误。
难道我做错了什么?
这是一个小的工作程序来说明我的问题。它可以编译为:
g++ -o segfault_example segfault_example.cpp -Wall -Wextra -pedantic \
`llvm-config --libs core jit native --cxxflags --ldflags`
#include <llvm/Module.h>
#include <llvm/Constants.h>
#include <llvm/DerivedTypes.h>
#include <llvm/LLVMContext.h>
#include <llvm/Instructions.h>
#include <llvm/Analysis/Verifier.h>
#include <llvm/ADT/ArrayRef.h>
#include <string>
#include <iostream>
static llvm::LLVMContext& global = llvm::getGlobalContext();
static llvm::Type* int32ty = llvm::Type::getInt32Ty(global);
llvm::ConstantInt* getInt32(int n)
{
return llvm::ConstantInt::get(llvm::Type::getInt32Ty(global), n);
}
int main()
{
//setup everything for a minimal example
llvm::Module* mainModule = new llvm::Module("main", global);
llvm::FunctionType* ftype = llvm::FunctionType::get(int32ty, false);
llvm::Function* mainFunction = llvm::Function::Create(
ftype, llvm::GlobalValue::InternalLinkage, "main", mainModule);
llvm::BasicBlock* bblock = llvm::BasicBlock::Create(
global, "entry", mainFunction, 0);
llvm::AllocaInst* mem = new llvm::AllocaInst(llvm::Type::getInt32PtrTy(global, 0x1000)
, getInt32(0x1000), 0x1000, "mem", bblock);
//tests
//this works
std::cout << "Testing with one element vector" << std::endl;
std::vector<llvm::Value*> vect_1;
vect_1.push_back(getInt32(0));
llvm::GetElementPtrInst* gep1 =
llvm::GetElementPtrInst::CreateInBounds(mem, llvm::ArrayRef<llvm::Value*>(vect_1)
, "retval", bblock);
std::cout << "done" << std::endl;
//this works too, but I can't find this signature in the documentation
std::cout << "Testing with Value* instead of ArrayRef" << std::endl;
llvm::GetElementPtrInst::CreateInBounds(mem, getInt32(0), "retval", bblock);
std::cout << "done" << std::endl;
//this segfaults
std::cout << "Filling two element vector" << std::endl;
std::vector<llvm::Value*> vect_2;
vect_2.push_back(getInt32(0));
vect_2.push_back(getInt32(1));
std::cout << "Testing with two element vector" << std::endl;
//segfault
llvm::GetElementPtrInst* gep2 =
llvm::GetElementPtrInst::CreateInBounds(mem, llvm::ArrayRef<llvm::Value*>(vect_2)
, "retval", bblock);
std::cout << "done" << std::endl;
mainModule->dump();
llvm::verifyFunction(*mainFunction);
}