Null GlobalVariable during asm generation

Hey,

I am writing a ModulePass for LLVM. I want to create a new GlobalVariable for each global static array defined in a module, assign to the new GlobalVariable the result of a function call. My code seems to be creating the global variable correctly, but after the pass completes, I get an error saying

Operand is null

store %3 <!null operand>

My code is the following:

std::string gvName("__memsafe_gv_");
gvname.append(global->getName());
GlobalVariable *gv = new GlobalVariable(*module,
              PointerType::get(global->getType()->getArrayElementType(), 0),
              false,
              global->getLinkage(),
              0,
              gvName);
gv->setAlignment(global->getAlignment());
gv->setInitializer(UndefValue::get(
              PointerType::get(global->getType()->getArrayElementType(), 0)));

Value *val = insert_function_call(); // Returns CallInst or BitCast as needed

Value *cast = IRBuilder.CreateBitCast(val,
               PointerType::get(type->getArrayElementType(), 0));
IRBuilder.CreateStore(cast, gv);

If I dump gv, val, cast, and the store I get the following:

@__memsafe_gv_foo = global i8* undef, align 1 %2 = bitcast i8* %1 to [6 x i8]* %3 = bitcast [6 x i8]* %2 to i8* store i8* %3, i8** @__memsafe_gv_foo

Am I missing something that I have to do for global variables? Thanks for the help.