Can we create multiple IRBuilders on one BasicBlock?

It seems like the document says nothing about this case. For example, I have tested these code using LLVM 14:

  auto entryBB = BasicBlock::Create(gCtx, "entry", kMainFun);
  llvm::IRBuilder<> irb0(entryBB);
  llvm::IRBuilder<> irb1(entryBB);
  llvm::IRBuilder<> irb2(entryBB);

  irb0.CreateAlloca(kIntTy, nullptr, "0");
  irb1.CreateAlloca(kIntTy, nullptr, "1");
  irb2.CreateAlloca(kIntTy, nullptr, "2");

  llvm::IRBuilder<> irb3(entryBB);
  llvm::IRBuilder<> irb4(entryBB);
  llvm::IRBuilder<> irb5(entryBB);

  irb3.CreateAlloca(kIntTy, nullptr, "3");
  irb4.CreateAlloca(kIntTy, nullptr, "4");
  irb5.CreateAlloca(kIntTy, nullptr, "5");

  irb0.CreateAlloca(kIntTy, nullptr, "6");
  irb1.CreateAlloca(kIntTy, nullptr, "7");
  irb2.CreateAlloca(kIntTy, nullptr, "8");

  entryBB->print(llvm::outs());

It prints 0 to 8 just as the executing order:

e:
  %"0" = alloca i32, align 4
  %"1" = alloca i32, align 4
  %"2" = alloca i32, align 4
  %"3" = alloca i32, align 4
  %"4" = alloca i32, align 4
  %"5" = alloca i32, align 4
  %"6" = alloca i32, align 4
  %"7" = alloca i32, align 4
  %"8" = alloca i32, align 4

But I don’t know whether this is the expected behavior or not.

Yes, that’s expected. The IRBuilder conceptually always inserts before its insertion point.

That said, it’s really not how IRBuilder is meant to be used. There is usually one “stream” of instructions that is constructed at a time, and so one IRBuilder. I can’t think of a reason why one would want multiple IRBuilders in flight.

(You can use the InsertPointGuard RAII helper to temporarily move an IRBuilder elsewhere.)

Oh, I see. I guess llvm uses linked list inside and that explains why 6,7,8 are after 3,4,5. Thank you!