LLVM  5.0.0
WebAssemblyCFGStackify.cpp
Go to the documentation of this file.
1 //===-- WebAssemblyCFGStackify.cpp - CFG Stackification -------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief This file implements a CFG stacking pass.
12 ///
13 /// This pass inserts BLOCK and LOOP markers to mark the start of scopes, since
14 /// scope boundaries serve as the labels for WebAssembly's control transfers.
15 ///
16 /// This is sufficient to convert arbitrary CFGs into a form that works on
17 /// WebAssembly, provided that all loops are single-entry.
18 ///
19 //===----------------------------------------------------------------------===//
20 
22 #include "WebAssembly.h"
24 #include "WebAssemblySubtarget.h"
25 #include "WebAssemblyUtilities.h"
31 #include "llvm/CodeGen/Passes.h"
32 #include "llvm/Support/Debug.h"
34 using namespace llvm;
35 
36 #define DEBUG_TYPE "wasm-cfg-stackify"
37 
38 namespace {
39 class WebAssemblyCFGStackify final : public MachineFunctionPass {
40  StringRef getPassName() const override { return "WebAssembly CFG Stackify"; }
41 
42  void getAnalysisUsage(AnalysisUsage &AU) const override {
43  AU.setPreservesCFG();
49  }
50 
51  bool runOnMachineFunction(MachineFunction &MF) override;
52 
53 public:
54  static char ID; // Pass identification, replacement for typeid
55  WebAssemblyCFGStackify() : MachineFunctionPass(ID) {}
56 };
57 } // end anonymous namespace
58 
61  return new WebAssemblyCFGStackify();
62 }
63 
64 /// Test whether Pred has any terminators explicitly branching to MBB, as
65 /// opposed to falling through. Note that it's possible (eg. in unoptimized
66 /// code) for a branch instruction to both branch to a block and fallthrough
67 /// to it, so we check the actual branch operands to see if there are any
68 /// explicit mentions.
70  MachineBasicBlock *MBB) {
71  for (MachineInstr &MI : Pred->terminators())
72  for (MachineOperand &MO : MI.explicit_operands())
73  if (MO.isMBB() && MO.getMBB() == MBB)
74  return true;
75  return false;
76 }
77 
78 /// Insert a BLOCK marker for branches to MBB (if needed).
79 static void PlaceBlockMarker(
85  const MachineLoopInfo &MLI,
88  // First compute the nearest common dominator of all forward non-fallthrough
89  // predecessors so that we minimize the time that the BLOCK is on the stack,
90  // which reduces overall stack height.
91  MachineBasicBlock *Header = nullptr;
92  bool IsBranchedTo = false;
93  int MBBNumber = MBB.getNumber();
94  for (MachineBasicBlock *Pred : MBB.predecessors())
95  if (Pred->getNumber() < MBBNumber) {
96  Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
97  if (ExplicitlyBranchesTo(Pred, &MBB))
98  IsBranchedTo = true;
99  }
100  if (!Header)
101  return;
102  if (!IsBranchedTo)
103  return;
104 
105  assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
106  MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
107 
108  // If the nearest common dominator is inside a more deeply nested context,
109  // walk out to the nearest scope which isn't more deeply nested.
110  for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
111  if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
112  if (ScopeTop->getNumber() > Header->getNumber()) {
113  // Skip over an intervening scope.
114  I = std::next(MachineFunction::iterator(ScopeTop));
115  } else {
116  // We found a scope level at an appropriate depth.
117  Header = ScopeTop;
118  break;
119  }
120  }
121  }
122 
123  // Decide where in Header to put the BLOCK.
124  MachineBasicBlock::iterator InsertPos;
125  MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
126  if (HeaderLoop && MBB.getNumber() > LoopBottom(HeaderLoop)->getNumber()) {
127  // Header is the header of a loop that does not lexically contain MBB, so
128  // the BLOCK needs to be above the LOOP, after any END constructs.
129  InsertPos = Header->begin();
130  while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
131  InsertPos->getOpcode() == WebAssembly::END_LOOP)
132  ++InsertPos;
133  } else {
134  // Otherwise, insert the BLOCK as late in Header as we can, but before the
135  // beginning of the local expression tree and any nested BLOCKs.
136  InsertPos = Header->getFirstTerminator();
137  while (InsertPos != Header->begin() &&
138  WebAssembly::isChild(*std::prev(InsertPos), MFI) &&
139  std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
140  std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
141  std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
142  --InsertPos;
143  }
144 
145  // Add the BLOCK.
146  MachineInstr *Begin = BuildMI(*Header, InsertPos, DebugLoc(),
147  TII.get(WebAssembly::BLOCK))
148  .addImm(int64_t(WebAssembly::ExprType::Void));
149 
150  // Mark the end of the block.
151  InsertPos = MBB.begin();
152  while (InsertPos != MBB.end() &&
153  InsertPos->getOpcode() == WebAssembly::END_LOOP &&
154  LoopTops[&*InsertPos]->getParent()->getNumber() >= Header->getNumber())
155  ++InsertPos;
156  MachineInstr *End = BuildMI(MBB, InsertPos, DebugLoc(),
157  TII.get(WebAssembly::END_BLOCK));
158  BlockTops[End] = Begin;
159 
160  // Track the farthest-spanning scope that ends at this point.
161  int Number = MBB.getNumber();
162  if (!ScopeTops[Number] ||
163  ScopeTops[Number]->getNumber() > Header->getNumber())
164  ScopeTops[Number] = Header;
165 }
166 
167 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
168 static void PlaceLoopMarker(
172  const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
173  MachineLoop *Loop = MLI.getLoopFor(&MBB);
174  if (!Loop || Loop->getHeader() != &MBB)
175  return;
176 
177  // The operand of a LOOP is the first block after the loop. If the loop is the
178  // bottom of the function, insert a dummy block at the end.
179  MachineBasicBlock *Bottom = LoopBottom(Loop);
180  auto Iter = std::next(MachineFunction::iterator(Bottom));
181  if (Iter == MF.end()) {
183  // Give it a fake predecessor so that AsmPrinter prints its label.
184  Label->addSuccessor(Label);
185  MF.push_back(Label);
186  Iter = std::next(MachineFunction::iterator(Bottom));
187  }
188  MachineBasicBlock *AfterLoop = &*Iter;
189 
190  // Mark the beginning of the loop (after the end of any existing loop that
191  // ends here).
192  auto InsertPos = MBB.begin();
193  while (InsertPos != MBB.end() &&
194  InsertPos->getOpcode() == WebAssembly::END_LOOP)
195  ++InsertPos;
196  MachineInstr *Begin = BuildMI(MBB, InsertPos, DebugLoc(),
197  TII.get(WebAssembly::LOOP))
198  .addImm(int64_t(WebAssembly::ExprType::Void));
199 
200  // Mark the end of the loop.
201  MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), DebugLoc(),
202  TII.get(WebAssembly::END_LOOP));
203  LoopTops[End] = Begin;
204 
205  assert((!ScopeTops[AfterLoop->getNumber()] ||
206  ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
207  "With block sorting the outermost loop for a block should be first.");
208  if (!ScopeTops[AfterLoop->getNumber()])
209  ScopeTops[AfterLoop->getNumber()] = &MBB;
210 }
211 
212 static unsigned
214  const MachineBasicBlock *MBB) {
215  unsigned Depth = 0;
216  for (auto X : reverse(Stack)) {
217  if (X == MBB)
218  break;
219  ++Depth;
220  }
221  assert(Depth < Stack.size() && "Branch destination should be in scope");
222  return Depth;
223 }
224 
225 /// In normal assembly languages, when the end of a function is unreachable,
226 /// because the function ends in an infinite loop or a noreturn call or similar,
227 /// it isn't necessary to worry about the function return type at the end of
228 /// the function, because it's never reached. However, in WebAssembly, blocks
229 /// that end at the function end need to have a return type signature that
230 /// matches the function signature, even though it's unreachable. This function
231 /// checks for such cases and fixes up the signatures.
233  MachineFunction &MF,
234  const WebAssemblyFunctionInfo &MFI,
237  assert(MFI.getResults().size() <= 1);
238 
239  if (MFI.getResults().empty())
240  return;
241 
242  WebAssembly::ExprType retType;
243  switch (MFI.getResults().front().SimpleTy) {
244  case MVT::i32: retType = WebAssembly::ExprType::I32; break;
245  case MVT::i64: retType = WebAssembly::ExprType::I64; break;
246  case MVT::f32: retType = WebAssembly::ExprType::F32; break;
247  case MVT::f64: retType = WebAssembly::ExprType::F64; break;
248  case MVT::v16i8: retType = WebAssembly::ExprType::I8x16; break;
249  case MVT::v8i16: retType = WebAssembly::ExprType::I16x8; break;
250  case MVT::v4i32: retType = WebAssembly::ExprType::I32x4; break;
251  case MVT::v4f32: retType = WebAssembly::ExprType::F32x4; break;
252  default: llvm_unreachable("unexpected return type");
253  }
254 
255  for (MachineBasicBlock &MBB : reverse(MF)) {
256  for (MachineInstr &MI : reverse(MBB)) {
257  if (MI.isPosition() || MI.isDebugValue())
258  continue;
259  if (MI.getOpcode() == WebAssembly::END_BLOCK) {
260  BlockTops[&MI]->getOperand(0).setImm(int32_t(retType));
261  continue;
262  }
263  if (MI.getOpcode() == WebAssembly::END_LOOP) {
264  LoopTops[&MI]->getOperand(0).setImm(int32_t(retType));
265  continue;
266  }
267  // Something other than an `end`. We're done.
268  return;
269  }
270  }
271 }
272 
273 // WebAssembly functions end with an end instruction, as if the function body
274 // were a block.
276  MachineFunction &MF,
277  const WebAssemblyInstrInfo &TII) {
278  BuildMI(MF.back(), MF.back().end(), DebugLoc(),
279  TII.get(WebAssembly::END_FUNCTION));
280 }
281 
282 /// Insert LOOP and BLOCK markers at appropriate places.
283 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
284  const WebAssemblyInstrInfo &TII,
287  // For each block whose label represents the end of a scope, record the block
288  // which holds the beginning of the scope. This will allow us to quickly skip
289  // over scoped regions when walking blocks. We allocate one more than the
290  // number of blocks in the function to accommodate for the possible fake block
291  // we may insert at the end.
293 
294  // For each LOOP_END, the corresponding LOOP.
296 
297  // For each END_BLOCK, the corresponding BLOCK.
299 
300  for (auto &MBB : MF) {
301  // Place the LOOP for MBB if MBB is the header of a loop.
302  PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
303 
304  // Place the BLOCK for MBB if MBB is branched to from above.
305  PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI);
306  }
307 
308  // Now rewrite references to basic blocks to be depth immediates.
310  for (auto &MBB : reverse(MF)) {
311  for (auto &MI : reverse(MBB)) {
312  switch (MI.getOpcode()) {
313  case WebAssembly::BLOCK:
314  assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
315  "Block should be balanced");
316  Stack.pop_back();
317  break;
318  case WebAssembly::LOOP:
319  assert(Stack.back() == &MBB && "Loop top should be balanced");
320  Stack.pop_back();
321  break;
323  Stack.push_back(&MBB);
324  break;
325  case WebAssembly::END_LOOP:
326  Stack.push_back(LoopTops[&MI]->getParent());
327  break;
328  default:
329  if (MI.isTerminator()) {
330  // Rewrite MBB operands to be depth immediates.
331  SmallVector<MachineOperand, 4> Ops(MI.operands());
332  while (MI.getNumOperands() > 0)
333  MI.RemoveOperand(MI.getNumOperands() - 1);
334  for (auto MO : Ops) {
335  if (MO.isMBB())
336  MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
337  MI.addOperand(MF, MO);
338  }
339  }
340  break;
341  }
342  }
343  }
344  assert(Stack.empty() && "Control flow should be balanced");
345 
346  // Fix up block/loop signatures at the end of the function to conform to
347  // WebAssembly's rules.
348  FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops);
349 
350  // Add an end instruction at the end of the function body.
351  if (!MF.getSubtarget<WebAssemblySubtarget>()
353  AppendEndToFunction(MF, TII);
354 }
355 
356 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
357  DEBUG(dbgs() << "********** CFG Stackifying **********\n"
358  "********** Function: "
359  << MF.getName() << '\n');
360 
361  const auto &MLI = getAnalysis<MachineLoopInfo>();
362  auto &MDT = getAnalysis<MachineDominatorTree>();
363  // Liveness is not tracked for VALUE_STACK physreg.
364  const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
367 
368  // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
369  PlaceMarkers(MF, MLI, TII, MDT, MFI);
370 
371  return true;
372 }
const Triple & getTargetTriple() const
MachineBasicBlock * LoopBottom(const MachineLoop *Loop)
Return the "bottom" block of a loop.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they're not in a MachineFuncti...
static unsigned GetDepth(const SmallVectorImpl< const MachineBasicBlock * > &Stack, const MachineBasicBlock *MBB)
iterator getFirstTerminator()
Returns an iterator to the first terminator instruction of this basic block.
A debug info location.
Definition: DebugLoc.h:34
static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, const WebAssemblyInstrInfo &TII, MachineDominatorTree &MDT, WebAssemblyFunctionInfo &MFI)
Insert LOOP and BLOCK markers at appropriate places.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end...
static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, MachineBasicBlock *MBB)
Test whether Pred has any terminators explicitly branching to MBB, as opposed to falling through...
BlockT * getHeader() const
Definition: LoopInfo.h:103
AnalysisUsage & addRequired()
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID's allocated.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
iterator_range< iterator > terminators()
static void FixEndsAtEndOfFunction(MachineFunction &MF, const WebAssemblyFunctionInfo &MFI, DenseMap< const MachineInstr *, MachineInstr * > &BlockTops, DenseMap< const MachineInstr *, MachineInstr * > &LoopTops)
In normal assembly languages, when the end of a function is unreachable, because the function ends in...
ExprType
This is used to indicate block signatures.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:60
static void PlaceBlockMarker(MachineBasicBlock &MBB, MachineFunction &MF, SmallVectorImpl< MachineBasicBlock * > &ScopeTops, DenseMap< const MachineInstr *, MachineInstr * > &BlockTops, DenseMap< const MachineInstr *, MachineInstr * > &LoopTops, const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI, MachineDominatorTree &MDT, WebAssemblyFunctionInfo &MFI)
Insert a BLOCK marker for branches to MBB (if needed).
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
Definition: STLExtras.h:250
const MachineBasicBlock & front() const
MachineBasicBlock * findNearestCommonDominator(MachineBasicBlock *A, MachineBasicBlock *B)
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
MachineBasicBlock * CreateMachineBasicBlock(const BasicBlock *bb=nullptr)
CreateMachineBasicBlock - Allocate a new MachineBasicBlock.
static void AppendEndToFunction(MachineFunction &MF, const WebAssemblyInstrInfo &TII)
This file contains the declaration of the WebAssembly-specific utility functions. ...
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
This file provides WebAssembly-specific target descriptions.
Represent the analysis usage information of a pass.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
static const unsigned End
const std::vector< MVT > & getResults() const
Ty * getInfo()
getInfo - Keep track of various per-function pieces of information for backends that would like to do...
FunctionPass class - This class is used to implement most global optimizations.
Definition: Pass.h:298
iterator_range< pred_iterator > predecessors()
static void PlaceLoopMarker(MachineBasicBlock &MBB, MachineFunction &MF, SmallVectorImpl< MachineBasicBlock * > &ScopeTops, DenseMap< const MachineInstr *, MachineInstr * > &LoopTops, const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI)
Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
This file declares the WebAssembly-specific subclass of TargetSubtarget.
Iterator for intrusive lists based on ilist_node.
#define E
Definition: LargeTest.cpp:27
void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
MachineOperand class - Representation of each machine instruction operand.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:861
FunctionPass * createWebAssemblyCFGStackify()
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:278
void invalidateLiveness()
invalidateLiveness - Indicates that register liveness is no longer being tracked accurately.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
llvm_unreachable("Unknown RegBank!")
Representation of each machine instruction.
Definition: MachineInstr.h:59
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
bool isOSBinFormatELF() const
Tests whether the OS uses the ELF binary format.
Definition: Triple.h:577
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:360
static MachineOperand CreateImm(int64_t Val)
#define I(x, y, z)
Definition: MD5.cpp:58
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:135
This file declares WebAssembly-specific per-machine-function information.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
void push_back(MachineBasicBlock *MBB)
static const Function * getParent(const Value *V)
#define DEBUG(X)
Definition: Debug.h:118
const MachineBasicBlock & back() const
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
bool isChild(const MachineInstr &MI, const WebAssemblyFunctionInfo &MFI)
Test whether MI is a child of some other node in an expression tree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...