[LLVMdev] Moving instructions from one basic block to another

Frank Winter fwinter at jlab.org
Fri Jun 26 09:08:01 PDT 2015


Say, you have basic blocks BB_source and BB_dest, where BB_source 
contains many instructions and some of them you'd like to move to 
BB_dest where the builder's insertion point currently points to. The 
instructions to move are stored in a SetVector<Value*> in no particular 
order. Thus, moving the instructions (removeFromParent and 
Builder->insert) while iterating over the set vector causes problems a 
la 'value does not dominate all uses'. However, iterating over BB_source 
and checking for presence of the processed instruction in the set vector 
and moving it to BB_dest seems to invalidate the iterator. Here's the 
code I am trying:

   for (BasicBlock::iterator inst = BB_source->begin() ;
        inst != BB_source->end() ;
        ++inst ) {
     if (Instruction *Inst = dyn_cast<Instruction>(inst)) {
       if (set_vector->instructions.count(Inst)) {
        Inst->removeFromParent();
        Builder->Insert(Inst);
       }
     }
   }

That doesn't work. I was already wondering if I am on the right path 
since the simplified version doesn't compile:


   for (BasicBlock::iterator inst = BB_source->begin() ;
        inst != BB_source->end() ;
        ++inst ) {
       if (set_vector->instructions.count(inst)) {
        inst->removeFromParent();
        Builder->Insert(inst);
     }
   }

How would You do that?

Thanks,
Frank









More information about the llvm-dev mailing list