diff --git a/llvm/include/llvm/CodeGen/SlotIndexes.h b/llvm/include/llvm/CodeGen/SlotIndexes.h --- a/llvm/include/llvm/CodeGen/SlotIndexes.h +++ b/llvm/include/llvm/CodeGen/SlotIndexes.h @@ -611,15 +611,18 @@ MachineInstr *InsertionPoint = nullptr) { MachineFunction::iterator nextMBB = std::next(MachineFunction::iterator(mbb)); + bool isLastMBB = nextMBB == mbb->getParent()->end(); IndexListEntry *startEntry = nullptr; IndexListEntry *endEntry = nullptr; IndexList::iterator newItr; if (InsertionPoint) { startEntry = createEntry(nullptr, 0); - endEntry = getInstructionIndex(*InsertionPoint).listEntry(); - newItr = indexList.insert(endEntry->getIterator(), startEntry); - } else if (nextMBB == mbb->getParent()->end()) { + endEntry = isLastMBB ? &indexList.back() + : getMBBStartIdx(&*nextMBB).listEntry(); + auto insIdx = getInstructionIndex(*InsertionPoint).listEntry(); + newItr = indexList.insert(insIdx->getIterator(), startEntry); + } else if (isLastMBB) { startEntry = &indexList.back(); endEntry = createEntry(nullptr, 0); newItr = indexList.insertAfter(startEntry->getIterator(), endEntry);