[LLVMdev] replacing a global variable by a constant

Chris Lattner clattner at apple.com
Fri Dec 5 08:32:38 PST 2008


On Dec 5, 2008, at 8:15 AM, Ralf Karrenberg wrote:

> Thanks a lot for your help Matthijs! :)
>
> basically this does the job quite nicely I think:
> for (llvm::GlobalVariable::use_iterator U = gv->use_begin(); U !=
> gv->use_end(); ++U) {
>    llvm::Instruction *I = llvm::cast<llvm::Instruction>(U);
>    I->replaceAllUsesWith(constPtr);
>    I->eraseFromParent();
> }

You're deferencing an invalidated iterator here.  Try this:

for (llvm::GlobalVariable::use_iterator U = gv->use_begin(); U != gv- 
 >use_end(); ) {
    llvm::Instruction *I = llvm::cast<llvm::Instruction>(U++);
    I->replaceAllUsesWith(constPtr);
    I->eraseFromParent();
}

Even this is not guaranteed to work depending on if an instruction can  
use the global more than once (think a call instruction).

If you know that all users are loads, the edited code above should work.

-Chris



More information about the llvm-dev mailing list