#include "MCTargetDesc/WebAssemblyMCTargetDesc.h"
#include "Utils/WebAssemblyUtilities.h"
#include "WebAssembly.h"
#include "WebAssemblyExceptionInfo.h"
#include "WebAssemblySortRegion.h"
#include "WebAssemblySubtarget.h"
#include "llvm/ADT/PriorityQueue.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineLoopInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/Passes.h"
#include "llvm/CodeGen/WasmEHFuncInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
using WebAssembly::SortRegion;
using WebAssembly::SortRegionInfo;
#define DEBUG_TYPE "wasm-cfg-sort"
static cl::opt<bool> WasmDisableEHPadSort(
"wasm-disable-ehpad-sort", cl::ReallyHidden,
cl::desc(
"WebAssembly: Disable EH pad-first sort order. Testing purpose only."),
cl::init(false));
namespace {
class WebAssemblyCFGSort final : public MachineFunctionPass {
StringRef getPassName() const override { return "WebAssembly CFG Sort"; }
void getAnalysisUsage(AnalysisUsage &AU) const override {
AU.setPreservesCFG();
AU.addRequired<MachineDominatorTree>();
AU.addPreserved<MachineDominatorTree>();
AU.addRequired<MachineLoopInfo>();
AU.addPreserved<MachineLoopInfo>();
AU.addRequired<WebAssemblyExceptionInfo>();
AU.addPreserved<WebAssemblyExceptionInfo>();
MachineFunctionPass::getAnalysisUsage(AU);
}
bool runOnMachineFunction(MachineFunction &MF) override;
public:
static char ID; WebAssemblyCFGSort() : MachineFunctionPass(ID) {}
};
}
char WebAssemblyCFGSort::ID = 0;
INITIALIZE_PASS(WebAssemblyCFGSort, DEBUG_TYPE,
"Reorders blocks in topological order", false, false)
FunctionPass *llvm::createWebAssemblyCFGSort() {
return new WebAssemblyCFGSort();
}
static void maybeUpdateTerminator(MachineBasicBlock *MBB) {
#ifndef NDEBUG
bool AnyBarrier = false;
#endif
bool AllAnalyzable = true;
for (const MachineInstr &Term : MBB->terminators()) {
#ifndef NDEBUG
AnyBarrier |= Term.isBarrier();
#endif
AllAnalyzable &= Term.isBranch() && !Term.isIndirectBranch();
}
assert((AnyBarrier || AllAnalyzable) &&
"analyzeBranch needs to analyze any block with a fallthrough");
MachineFunction *MF = MBB->getParent();
MachineBasicBlock *OriginalSuccessor =
unsigned(MBB->getNumber() + 1) < MF->getNumBlockIDs()
? MF->getBlockNumbered(MBB->getNumber() + 1)
: nullptr;
if (AllAnalyzable)
MBB->updateTerminator(OriginalSuccessor);
}
namespace {
struct CompareBlockNumbers {
bool operator()(const MachineBasicBlock *A,
const MachineBasicBlock *B) const {
if (!WasmDisableEHPadSort) {
if (A->isEHPad() && !B->isEHPad())
return false;
if (!A->isEHPad() && B->isEHPad())
return true;
}
return A->getNumber() > B->getNumber();
}
};
struct CompareBlockNumbersBackwards {
bool operator()(const MachineBasicBlock *A,
const MachineBasicBlock *B) const {
if (!WasmDisableEHPadSort) {
if (A->isEHPad() && !B->isEHPad())
return false;
if (!A->isEHPad() && B->isEHPad())
return true;
}
return A->getNumber() < B->getNumber();
}
};
struct Entry {
const SortRegion *TheRegion;
unsigned NumBlocksLeft;
std::vector<MachineBasicBlock *> Deferred;
explicit Entry(const SortRegion *R)
: TheRegion(R), NumBlocksLeft(R->getNumBlocks()) {}
};
}
static void sortBlocks(MachineFunction &MF, const MachineLoopInfo &MLI,
const WebAssemblyExceptionInfo &WEI,
const MachineDominatorTree &MDT) {
MF.RenumberBlocks();
SmallVector<unsigned, 16> NumPredsLeft(MF.getNumBlockIDs(), 0);
for (MachineBasicBlock &MBB : MF) {
unsigned N = MBB.pred_size();
if (MachineLoop *L = MLI.getLoopFor(&MBB))
if (L->getHeader() == &MBB)
for (const MachineBasicBlock *Pred : MBB.predecessors())
if (L->contains(Pred))
--N;
NumPredsLeft[MBB.getNumber()] = N;
}
PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
CompareBlockNumbers>
Preferred;
PriorityQueue<MachineBasicBlock *, std::vector<MachineBasicBlock *>,
CompareBlockNumbersBackwards>
Ready;
const auto *EHInfo = MF.getWasmEHFuncInfo();
SortRegionInfo SRI(MLI, WEI);
SmallVector<Entry, 4> Entries;
for (MachineBasicBlock *MBB = &MF.front();;) {
const SortRegion *R = SRI.getRegionFor(MBB);
if (R) {
if (R->getHeader() == MBB)
Entries.push_back(Entry(R));
for (Entry &E : Entries)
if (E.TheRegion->contains(MBB) && --E.NumBlocksLeft == 0)
for (auto DeferredBlock : E.Deferred)
Ready.push(DeferredBlock);
while (!Entries.empty() && Entries.back().NumBlocksLeft == 0)
Entries.pop_back();
}
for (MachineBasicBlock *Succ : MBB->successors()) {
if (MachineLoop *SuccL = MLI.getLoopFor(Succ))
if (SuccL->getHeader() == Succ && SuccL->contains(MBB))
continue;
if (--NumPredsLeft[Succ->getNumber()] == 0) {
if (EHInfo && EHInfo->hasUnwindSrcs(Succ)) {
SmallPtrSet<MachineBasicBlock *, 4> UnwindSrcs =
EHInfo->getUnwindSrcs(Succ);
bool IsDeferred = false;
for (Entry &E : Entries) {
if (UnwindSrcs.count(E.TheRegion->getHeader())) {
E.Deferred.push_back(Succ);
IsDeferred = true;
break;
}
}
if (IsDeferred)
continue;
}
Preferred.push(Succ);
}
}
MachineBasicBlock *Next = nullptr;
while (!Preferred.empty()) {
Next = Preferred.top();
Preferred.pop();
if (!Entries.empty() &&
!MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
Entries.back().Deferred.push_back(Next);
Next = nullptr;
continue;
}
if (Next->getNumber() < MBB->getNumber() &&
(WasmDisableEHPadSort || !Next->isEHPad()) &&
(!R || !R->contains(Next) ||
R->getHeader()->getNumber() < Next->getNumber())) {
Ready.push(Next);
Next = nullptr;
continue;
}
break;
}
if (!Next) {
if (Ready.empty()) {
maybeUpdateTerminator(MBB);
break;
}
for (;;) {
Next = Ready.top();
Ready.pop();
if (!Entries.empty() &&
!MDT.dominates(Entries.back().TheRegion->getHeader(), Next)) {
Entries.back().Deferred.push_back(Next);
continue;
}
break;
}
}
Next->moveAfter(MBB);
maybeUpdateTerminator(MBB);
MBB = Next;
}
assert(Entries.empty() && "Active sort region list not finished");
MF.RenumberBlocks();
#ifndef NDEBUG
SmallSetVector<const SortRegion *, 8> OnStack;
OnStack.insert(nullptr);
for (auto &MBB : MF) {
assert(MBB.getNumber() >= 0 && "Renumbered blocks should be non-negative.");
const SortRegion *Region = SRI.getRegionFor(&MBB);
if (Region && &MBB == Region->getHeader()) {
if (Region->isLoop()) {
for (auto Pred : MBB.predecessors())
assert(
(Pred->getNumber() < MBB.getNumber() || Region->contains(Pred)) &&
"Loop header predecessors must be loop predecessors or "
"backedges");
} else {
for (auto Pred : MBB.predecessors())
assert(Pred->getNumber() < MBB.getNumber() &&
"Non-loop-header predecessors should be topologically sorted");
}
assert(OnStack.insert(Region) &&
"Regions should be declared at most once.");
} else {
for (auto Pred : MBB.predecessors())
assert(Pred->getNumber() < MBB.getNumber() &&
"Non-loop-header predecessors should be topologically sorted");
assert(OnStack.count(SRI.getRegionFor(&MBB)) &&
"Blocks must be nested in their regions");
}
while (OnStack.size() > 1 && &MBB == SRI.getBottom(OnStack.back()))
OnStack.pop_back();
}
assert(OnStack.pop_back_val() == nullptr &&
"The function entry block shouldn't actually be a region header");
assert(OnStack.empty() &&
"Control flow stack pushes and pops should be balanced.");
#endif
}
bool WebAssemblyCFGSort::runOnMachineFunction(MachineFunction &MF) {
LLVM_DEBUG(dbgs() << "********** CFG Sorting **********\n"
"********** Function: "
<< MF.getName() << '\n');
const auto &MLI = getAnalysis<MachineLoopInfo>();
const auto &WEI = getAnalysis<WebAssemblyExceptionInfo>();
auto &MDT = getAnalysis<MachineDominatorTree>();
MF.getRegInfo().invalidateLiveness();
sortBlocks(MF, MLI, WEI, MDT);
return true;
}