#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "WebAssembly.h"
#include "WebAssemblySubtarget.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/Support/Debug.h"
using namespace llvm;
#define DEBUG_TYPE "wasm-fix-irreducible-control-flow"
namespace {
using BlockVector = SmallVector<MachineBasicBlock *, 4>;
using BlockSet = SmallPtrSet<MachineBasicBlock *, 4>;
static BlockVector getSortedEntries(const BlockSet &Entries) {
BlockVector SortedEntries(Entries.begin(), Entries.end());
llvm::sort(SortedEntries,
[](const MachineBasicBlock *A, const MachineBasicBlock *B) {
auto ANum = A->getNumber();
auto BNum = B->getNumber();
return ANum < BNum;
});
return SortedEntries;
}
class ReachabilityGraph {
public:
ReachabilityGraph(MachineBasicBlock *Entry, const BlockSet &Blocks)
: Entry(Entry), Blocks(Blocks) {
#ifndef NDEBUG
for (auto *MBB : Blocks) {
if (MBB != Entry) {
for (auto *Pred : MBB->predecessors()) {
assert(inRegion(Pred));
}
}
}
#endif
calculate();
}
bool canReach(MachineBasicBlock *From, MachineBasicBlock *To) const {
assert(inRegion(From) && inRegion(To));
auto I = Reachable.find(From);
if (I == Reachable.end())
return false;
return I->second.count(To);
}
const BlockSet &getLoopers() const { return Loopers; }
const BlockSet &getLoopEntries() const { return LoopEntries; }
const BlockSet &getLoopEnterers(MachineBasicBlock *LoopEntry) const {
assert(inRegion(LoopEntry));
auto I = LoopEnterers.find(LoopEntry);
assert(I != LoopEnterers.end());
return I->second;
}
private:
MachineBasicBlock *Entry;
const BlockSet &Blocks;
BlockSet Loopers, LoopEntries;
DenseMap<MachineBasicBlock *, BlockSet> LoopEnterers;
bool inRegion(MachineBasicBlock *MBB) const { return Blocks.count(MBB); }
DenseMap<MachineBasicBlock *, BlockSet> Reachable;
void calculate() {
using BlockPair = std::pair<MachineBasicBlock *, MachineBasicBlock *>;
SmallVector<BlockPair, 4> WorkList;
for (auto *MBB : Blocks) {
for (auto *Succ : MBB->successors()) {
if (Succ != Entry && inRegion(Succ)) {
Reachable[MBB].insert(Succ);
WorkList.emplace_back(MBB, Succ);
}
}
}
while (!WorkList.empty()) {
MachineBasicBlock *MBB, *Succ;
std::tie(MBB, Succ) = WorkList.pop_back_val();
assert(inRegion(MBB) && Succ != Entry && inRegion(Succ));
if (MBB != Entry) {
for (auto *Pred : MBB->predecessors()) {
if (Reachable[Pred].insert(Succ).second) {
WorkList.emplace_back(Pred, Succ);
}
}
}
}
for (auto *MBB : Blocks) {
if (canReach(MBB, MBB)) {
Loopers.insert(MBB);
}
}
assert(!Loopers.count(Entry));
for (auto *Looper : Loopers) {
for (auto *Pred : Looper->predecessors()) {
if (!canReach(Looper, Pred)) {
LoopEntries.insert(Looper);
LoopEnterers[Looper].insert(Pred);
}
}
}
}
};
class LoopBlocks {
public:
LoopBlocks(MachineBasicBlock *Entry, const BlockSet &Enterers)
: Entry(Entry), Enterers(Enterers) {
calculate();
}
BlockSet &getBlocks() { return Blocks; }
private:
MachineBasicBlock *Entry;
const BlockSet &Enterers;
BlockSet Blocks;
void calculate() {
BlockVector WorkList;
BlockSet AddedToWorkList;
Blocks.insert(Entry);
for (auto *Pred : Entry->predecessors()) {
if (!Enterers.count(Pred)) {
WorkList.push_back(Pred);
AddedToWorkList.insert(Pred);
}
}
while (!WorkList.empty()) {
auto *MBB = WorkList.pop_back_val();
assert(!Enterers.count(MBB));
if (Blocks.insert(MBB).second) {
for (auto *Pred : MBB->predecessors()) {
if (AddedToWorkList.insert(Pred).second)
WorkList.push_back(Pred);
}
}
}
}
};
class WebAssemblyFixIrreducibleControlFlow final : public MachineFunctionPass {
StringRef getPassName() const override {
return "WebAssembly Fix Irreducible Control Flow";
}
bool runOnMachineFunction(MachineFunction &MF) override;
bool processRegion(MachineBasicBlock *Entry, BlockSet &Blocks,
MachineFunction &MF);
void makeSingleEntryLoop(BlockSet &Entries, BlockSet &Blocks,
MachineFunction &MF, const ReachabilityGraph &Graph);
public:
static char ID; WebAssemblyFixIrreducibleControlFlow() : MachineFunctionPass(ID) {}
};
bool WebAssemblyFixIrreducibleControlFlow::processRegion(
MachineBasicBlock *Entry, BlockSet &Blocks, MachineFunction &MF) {
bool Changed = false;
while (true) {
ReachabilityGraph Graph(Entry, Blocks);
bool FoundIrreducibility = false;
for (auto *LoopEntry : getSortedEntries(Graph.getLoopEntries())) {
BlockSet MutualLoopEntries;
MutualLoopEntries.insert(LoopEntry);
for (auto *OtherLoopEntry : Graph.getLoopEntries()) {
if (OtherLoopEntry != LoopEntry &&
Graph.canReach(LoopEntry, OtherLoopEntry) &&
Graph.canReach(OtherLoopEntry, LoopEntry)) {
MutualLoopEntries.insert(OtherLoopEntry);
}
}
if (MutualLoopEntries.size() > 1) {
makeSingleEntryLoop(MutualLoopEntries, Blocks, MF, Graph);
FoundIrreducibility = true;
Changed = true;
break;
}
}
if (FoundIrreducibility) {
continue;
}
for (auto *LoopEntry : Graph.getLoopEntries()) {
LoopBlocks InnerBlocks(LoopEntry, Graph.getLoopEnterers(LoopEntry));
if (processRegion(LoopEntry, InnerBlocks.getBlocks(), MF)) {
Changed = true;
}
}
return Changed;
}
}
void WebAssemblyFixIrreducibleControlFlow::makeSingleEntryLoop(
BlockSet &Entries, BlockSet &Blocks, MachineFunction &MF,
const ReachabilityGraph &Graph) {
assert(Entries.size() >= 2);
BlockVector SortedEntries = getSortedEntries(Entries);
#ifndef NDEBUG
for (auto Block : SortedEntries)
assert(Block->getNumber() != -1);
if (SortedEntries.size() > 1) {
for (auto I = SortedEntries.begin(), E = SortedEntries.end() - 1; I != E;
++I) {
auto ANum = (*I)->getNumber();
auto BNum = (*(std::next(I)))->getNumber();
assert(ANum != BNum);
}
}
#endif
MachineBasicBlock *Dispatch = MF.CreateMachineBasicBlock();
MF.insert(MF.end(), Dispatch);
Blocks.insert(Dispatch);
const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
MachineInstrBuilder MIB =
BuildMI(Dispatch, DebugLoc(), TII.get(WebAssembly::BR_TABLE_I32));
MachineRegisterInfo &MRI = MF.getRegInfo();
Register Reg = MRI.createVirtualRegister(&WebAssembly::I32RegClass);
MIB.addReg(Reg);
DenseMap<MachineBasicBlock *, unsigned> Indices;
for (auto *Entry : SortedEntries) {
auto Pair = Indices.insert(std::make_pair(Entry, 0));
assert(Pair.second);
unsigned Index = MIB.getInstr()->getNumExplicitOperands() - 1;
Pair.first->second = Index;
MIB.addMBB(Entry);
Dispatch->addSuccessor(Entry);
}
BlockVector AllPreds;
for (auto *Entry : SortedEntries) {
for (auto *Pred : Entry->predecessors()) {
if (Pred != Dispatch) {
AllPreds.push_back(Pred);
}
}
}
DenseSet<MachineBasicBlock *> InLoop;
for (auto *Pred : AllPreds) {
for (auto *Entry : Pred->successors()) {
if (!Entries.count(Entry))
continue;
if (Graph.canReach(Entry, Pred)) {
InLoop.insert(Pred);
break;
}
}
}
DenseMap<PointerIntPair<MachineBasicBlock *, 1, bool>, MachineBasicBlock *>
EntryToLayoutPred;
for (auto *Pred : AllPreds) {
bool PredInLoop = InLoop.count(Pred);
for (auto *Entry : Pred->successors())
if (Entries.count(Entry) && Pred->isLayoutSuccessor(Entry))
EntryToLayoutPred[{Entry, PredInLoop}] = Pred;
}
DenseMap<PointerIntPair<MachineBasicBlock *, 1, bool>, MachineBasicBlock *>
Map;
for (auto *Pred : AllPreds) {
bool PredInLoop = InLoop.count(Pred);
for (auto *Entry : Pred->successors()) {
if (!Entries.count(Entry) || Map.count({Entry, PredInLoop}))
continue;
if (auto *OtherPred = EntryToLayoutPred.lookup({Entry, PredInLoop}))
if (OtherPred != Pred)
continue;
MachineBasicBlock *Routing = MF.CreateMachineBasicBlock();
MF.insert(Pred->isLayoutSuccessor(Entry)
? MachineFunction::iterator(Entry)
: MF.end(),
Routing);
Blocks.insert(Routing);
BuildMI(Routing, DebugLoc(), TII.get(WebAssembly::CONST_I32), Reg)
.addImm(Indices[Entry]);
BuildMI(Routing, DebugLoc(), TII.get(WebAssembly::BR)).addMBB(Dispatch);
Routing->addSuccessor(Dispatch);
Map[{Entry, PredInLoop}] = Routing;
}
}
for (auto *Pred : AllPreds) {
bool PredInLoop = InLoop.count(Pred);
for (MachineInstr &Term : Pred->terminators())
for (auto &Op : Term.explicit_uses())
if (Op.isMBB() && Indices.count(Op.getMBB()))
Op.setMBB(Map[{Op.getMBB(), PredInLoop}]);
for (auto *Succ : Pred->successors()) {
if (!Entries.count(Succ))
continue;
auto *Routing = Map[{Succ, PredInLoop}];
Pred->replaceSuccessor(Succ, Routing);
}
}
MIB.addMBB(MIB.getInstr()
->getOperand(MIB.getInstr()->getNumExplicitOperands() - 1)
.getMBB());
}
}
char WebAssemblyFixIrreducibleControlFlow::ID = 0;
INITIALIZE_PASS(WebAssemblyFixIrreducibleControlFlow, DEBUG_TYPE,
"Removes irreducible control flow", false, false)
FunctionPass *llvm::createWebAssemblyFixIrreducibleControlFlow() {
return new WebAssemblyFixIrreducibleControlFlow();
}
static bool hasArgumentDef(unsigned Reg, const MachineRegisterInfo &MRI) {
for (const auto &Def : MRI.def_instructions(Reg))
if (WebAssembly::isArgument(Def.getOpcode()))
return true;
return false;
}
static void addImplicitDefs(MachineFunction &MF) {
const MachineRegisterInfo &MRI = MF.getRegInfo();
const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
MachineBasicBlock &Entry = *MF.begin();
for (unsigned I = 0, E = MRI.getNumVirtRegs(); I < E; ++I) {
Register Reg = Register::index2VirtReg(I);
if (MRI.use_nodbg_empty(Reg))
continue;
if (hasArgumentDef(Reg, MRI))
continue;
BuildMI(Entry, Entry.begin(), DebugLoc(),
TII.get(WebAssembly::IMPLICIT_DEF), Reg);
}
for (MachineInstr &MI : llvm::make_early_inc_range(Entry)) {
if (WebAssembly::isArgument(MI.getOpcode())) {
MI.removeFromParent();
Entry.insert(Entry.begin(), &MI);
}
}
}
bool WebAssemblyFixIrreducibleControlFlow::runOnMachineFunction(
MachineFunction &MF) {
LLVM_DEBUG(dbgs() << "********** Fixing Irreducible Control Flow **********\n"
"********** Function: "
<< MF.getName() << '\n');
BlockSet AllBlocks;
for (auto &MBB : MF) {
AllBlocks.insert(&MBB);
}
if (LLVM_UNLIKELY(processRegion(&*MF.begin(), AllBlocks, MF))) {
MF.RenumberBlocks();
addImplicitDefs(MF);
return true;
}
return false;
}