I collected a sequence of LLVM instructions, want to make a copy of each and insert them into a PREVIOUS location inside the same function (all globals and locals are properly declared before the PREVIOUS location).
Here is the list of instructions I want to duplicate and insert:
0 %90 = load i32* @strstart, align 4
1 %91 = add i32 %90, 2
2 %88 = load i32* @ins_h, align 4
3 %92 = getelementptr inbounds [65536 x i8]* @window, i32 0, i32 %91
4 %89 = shl i32 %88, 5
5 %93 = load i8* %92, align 1
6 %.masked = and i32 %89, 32736
7 %94 = zext i8 %93 to i32
8 %95 = xor i32 %94, %.masked
9 %.sum73 = or i32 %95, 32768
10 %104 = getelementptr inbounds [65536 x i16]* @prev, i32 0, i32 %.sum73
11 %take_addr2 = getelementptr i16* %104
12 %105 = bitcast i16* %take_addr2 to i8*
13 call void @bkp_memory(i8* %105, i32 2)
{basically, I want to duplicate the bkp_memory() call, everything else are its dependent instructions.}
I put them into a std::vector<Instruction *> coll, with the following code trying to do the replication and insertion:
std::vector<Instruction *>::iterator p;
Instruction * pi = PREVIOUS_POSITION;
BasicBlock * pb = PREVIOUS_POSITION->getParent();
for(p = coll.begin(); p != coll.end(); ++p){
Instruction * CurI = * p;
Instruction * CloneI = CurI->clone();
CloneI->setName(CurI->getName());
errs() << *CloneI << “\n”;
pb->getInstList().insertAfter(pi, CloneI); // Inserts newInst after pi in pb
// adjust pi: point to the newly inserted inst:
pi = CurI;
}//end of for loop on p
However, I got the following errors:
--- Insert New (cloned) Instructions: ...
<badref> = load i32* @strstart, align 4
<badref> = add i32 <badref>, 2
<badref> = load i32* @ins_h, align 4
<badref> = getelementptr inbounds [65536 x i8]* @window, i32 0, i32 <badref>
<badref> = shl i32 <badref>, 5
<badref> = load i8* <badref>, align 1
%.masked = and i32 <badref>, 32736
<badref> = zext i8 <badref> to i32
<badref> = xor i32 <badref>, %.masked
%.sum73 = or i32 <badref>, 32768
<badref> = getelementptr inbounds [65536 x i16]* @prev, i32 0, i32 %.sum73
%take_addr2 = getelementptr i16* <badref>
<badref> = bitcast i16* %take_addr2 to i8*
call void @bkp_memory(i8* <badref>, i32 2)
Instruction does not dominate all uses!
%95 = add i32 %93, 2
%90 = getelementptr inbounds [65536 x i8]* @window, i32 0, i32 %95
Instruction does not dominate all uses!
%97 = getelementptr inbounds [65536 x i8]* @window, i32 0, i32 %95
%92 = load i8* %97, align 1
Instruction does not dominate all uses!
%.masked = and i32 %91, 32736
%101 = xor i32 %100, %.masked
Broken module found, compilation aborted!
What am I doing wrong here?
Does the <badref> sound alarm to anyone?
What is the right approach I should take here?
Thank you very much
Chuck