在下面的代码片段中,我将Instruction
插入到Function::iterator bs
指向的BasicBlock
中。内部循环遍历此BasicBlock
中包含的指令。
现在,在内部循环插入这些指令后,程序进入一个带有指令序列的无限循环:
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
xor
and
mul
...
如何插入正在迭代的数据结构中,同时避免进入无限循环?
不知何故,迭代器发疯了(或者它失效了(。如何解决这个问题有共同的成语吗?
for (Function::iterator bs = F.begin(), be = F.end(); bs != be; ++bs) {
for (BasicBlock::iterator is = bs->begin(), ie = be->end(); is != ie; ++is) {
Instruction& inst = *is;
BinaryOperator* binop = dyn_cast<BinaryOperator>(&inst);
if (!binop) {
continue;
}
unsigned opcode = binop->getOpcode();
errs() << binop->getOpcodeName() << "n";
if (opcode != Instruction::Add) {
continue;
}
IRBuilder<> builder(binop);
Value* v = builder.CreateAdd(builder.CreateXor(binop->getOperand(0), binop->getOperand(1)),
builder.CreateMul(ConstantInt::get(binop->getType(), 2),
builder.CreateAnd(binop->getOperand(0), binop->getOperand(1))));
ReplaceInstWithValue(bs->getInstList(), is, v); // THINGS GO WRONG HERE!
}
}
不幸的是,您未能提供足够的详细信息,但我强烈怀疑您将新元素插入容器的方式使现有迭代器(对其他元素(无效。这是许多容器类的常见行为,例如 std::vector<>::insert()
,如果新size()
迭代器超过 capacity()
,则所有现有迭代器无效(否则只有插入点之前元素的现有迭代器仍然有效(。
避免这种情况的方法是使用没有此问题的容器,例如std::list<>
,因为std::list<>::insert()
不会使任何现有的迭代器或引用无效。