LLVM  7.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 /// 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 
60 INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE,
61  "Insert BLOCK and LOOP markers for WebAssembly scopes",
62  false, false)
63 
65  return new WebAssemblyCFGStackify();
66 }
67 
68 /// Test whether Pred has any terminators explicitly branching to MBB, as
69 /// opposed to falling through. Note that it's possible (eg. in unoptimized
70 /// code) for a branch instruction to both branch to a block and fallthrough
71 /// to it, so we check the actual branch operands to see if there are any
72 /// explicit mentions.
74  MachineBasicBlock *MBB) {
75  for (MachineInstr &MI : Pred->terminators())
76  for (MachineOperand &MO : MI.explicit_operands())
77  if (MO.isMBB() && MO.getMBB() == MBB)
78  return true;
79  return false;
80 }
81 
82 /// Insert a BLOCK marker for branches to MBB (if needed).
83 static void PlaceBlockMarker(
89  const MachineLoopInfo &MLI,
92  // First compute the nearest common dominator of all forward non-fallthrough
93  // predecessors so that we minimize the time that the BLOCK is on the stack,
94  // which reduces overall stack height.
95  MachineBasicBlock *Header = nullptr;
96  bool IsBranchedTo = false;
97  int MBBNumber = MBB.getNumber();
98  for (MachineBasicBlock *Pred : MBB.predecessors())
99  if (Pred->getNumber() < MBBNumber) {
100  Header = Header ? MDT.findNearestCommonDominator(Header, Pred) : Pred;
101  if (ExplicitlyBranchesTo(Pred, &MBB))
102  IsBranchedTo = true;
103  }
104  if (!Header)
105  return;
106  if (!IsBranchedTo)
107  return;
108 
109  assert(&MBB != &MF.front() && "Header blocks shouldn't have predecessors");
110  MachineBasicBlock *LayoutPred = &*std::prev(MachineFunction::iterator(&MBB));
111 
112  // If the nearest common dominator is inside a more deeply nested context,
113  // walk out to the nearest scope which isn't more deeply nested.
114  for (MachineFunction::iterator I(LayoutPred), E(Header); I != E; --I) {
115  if (MachineBasicBlock *ScopeTop = ScopeTops[I->getNumber()]) {
116  if (ScopeTop->getNumber() > Header->getNumber()) {
117  // Skip over an intervening scope.
118  I = std::next(MachineFunction::iterator(ScopeTop));
119  } else {
120  // We found a scope level at an appropriate depth.
121  Header = ScopeTop;
122  break;
123  }
124  }
125  }
126 
127  // Decide where in Header to put the BLOCK.
128  MachineBasicBlock::iterator InsertPos;
129  MachineLoop *HeaderLoop = MLI.getLoopFor(Header);
130  if (HeaderLoop &&
131  MBB.getNumber() > WebAssembly::getBottom(HeaderLoop)->getNumber()) {
132  // Header is the header of a loop that does not lexically contain MBB, so
133  // the BLOCK needs to be above the LOOP, after any END constructs.
134  InsertPos = Header->begin();
135  while (InsertPos->getOpcode() == WebAssembly::END_BLOCK ||
136  InsertPos->getOpcode() == WebAssembly::END_LOOP)
137  ++InsertPos;
138  } else {
139  // Otherwise, insert the BLOCK as late in Header as we can, but before the
140  // beginning of the local expression tree and any nested BLOCKs.
141  InsertPos = Header->getFirstTerminator();
142  while (InsertPos != Header->begin() &&
143  WebAssembly::isChild(*std::prev(InsertPos), MFI) &&
144  std::prev(InsertPos)->getOpcode() != WebAssembly::LOOP &&
145  std::prev(InsertPos)->getOpcode() != WebAssembly::END_BLOCK &&
146  std::prev(InsertPos)->getOpcode() != WebAssembly::END_LOOP)
147  --InsertPos;
148  }
149 
150  // Add the BLOCK.
151  MachineInstr *Begin =
152  BuildMI(*Header, InsertPos, Header->findDebugLoc(InsertPos),
153  TII.get(WebAssembly::BLOCK))
154  .addImm(int64_t(WebAssembly::ExprType::Void));
155 
156  // Mark the end of the block.
157  InsertPos = MBB.begin();
158  while (InsertPos != MBB.end() &&
159  InsertPos->getOpcode() == WebAssembly::END_LOOP &&
160  LoopTops[&*InsertPos]->getParent()->getNumber() >= Header->getNumber())
161  ++InsertPos;
162  MachineInstr *End = BuildMI(MBB, InsertPos, MBB.findPrevDebugLoc(InsertPos),
163  TII.get(WebAssembly::END_BLOCK));
164  BlockTops[End] = Begin;
165 
166  // Track the farthest-spanning scope that ends at this point.
167  int Number = MBB.getNumber();
168  if (!ScopeTops[Number] ||
169  ScopeTops[Number]->getNumber() > Header->getNumber())
170  ScopeTops[Number] = Header;
171 }
172 
173 /// Insert a LOOP marker for a loop starting at MBB (if it's a loop header).
174 static void PlaceLoopMarker(
178  const WebAssemblyInstrInfo &TII, const MachineLoopInfo &MLI) {
179  MachineLoop *Loop = MLI.getLoopFor(&MBB);
180  if (!Loop || Loop->getHeader() != &MBB)
181  return;
182 
183  // The operand of a LOOP is the first block after the loop. If the loop is the
184  // bottom of the function, insert a dummy block at the end.
186  auto Iter = std::next(MachineFunction::iterator(Bottom));
187  if (Iter == MF.end()) {
189  // Give it a fake predecessor so that AsmPrinter prints its label.
190  Label->addSuccessor(Label);
191  MF.push_back(Label);
192  Iter = std::next(MachineFunction::iterator(Bottom));
193  }
194  MachineBasicBlock *AfterLoop = &*Iter;
195 
196  // Mark the beginning of the loop (after the end of any existing loop that
197  // ends here).
198  auto InsertPos = MBB.begin();
199  while (InsertPos != MBB.end() &&
200  InsertPos->getOpcode() == WebAssembly::END_LOOP)
201  ++InsertPos;
202  MachineInstr *Begin = BuildMI(MBB, InsertPos, MBB.findDebugLoc(InsertPos),
203  TII.get(WebAssembly::LOOP))
204  .addImm(int64_t(WebAssembly::ExprType::Void));
205 
206  // Mark the end of the loop (using arbitrary debug location that branched
207  // to the loop end as its location).
208  DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc();
209  MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), EndDL,
210  TII.get(WebAssembly::END_LOOP));
211  LoopTops[End] = Begin;
212 
213  assert((!ScopeTops[AfterLoop->getNumber()] ||
214  ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) &&
215  "With block sorting the outermost loop for a block should be first.");
216  if (!ScopeTops[AfterLoop->getNumber()])
217  ScopeTops[AfterLoop->getNumber()] = &MBB;
218 }
219 
220 static unsigned
222  const MachineBasicBlock *MBB) {
223  unsigned Depth = 0;
224  for (auto X : reverse(Stack)) {
225  if (X == MBB)
226  break;
227  ++Depth;
228  }
229  assert(Depth < Stack.size() && "Branch destination should be in scope");
230  return Depth;
231 }
232 
233 /// In normal assembly languages, when the end of a function is unreachable,
234 /// because the function ends in an infinite loop or a noreturn call or similar,
235 /// it isn't necessary to worry about the function return type at the end of
236 /// the function, because it's never reached. However, in WebAssembly, blocks
237 /// that end at the function end need to have a return type signature that
238 /// matches the function signature, even though it's unreachable. This function
239 /// checks for such cases and fixes up the signatures.
241  MachineFunction &MF,
242  const WebAssemblyFunctionInfo &MFI,
245  assert(MFI.getResults().size() <= 1);
246 
247  if (MFI.getResults().empty())
248  return;
249 
250  WebAssembly::ExprType retType;
251  switch (MFI.getResults().front().SimpleTy) {
252  case MVT::i32: retType = WebAssembly::ExprType::I32; break;
253  case MVT::i64: retType = WebAssembly::ExprType::I64; break;
254  case MVT::f32: retType = WebAssembly::ExprType::F32; break;
255  case MVT::f64: retType = WebAssembly::ExprType::F64; break;
256  case MVT::v16i8: retType = WebAssembly::ExprType::I8x16; break;
257  case MVT::v8i16: retType = WebAssembly::ExprType::I16x8; break;
258  case MVT::v4i32: retType = WebAssembly::ExprType::I32x4; break;
259  case MVT::v4f32: retType = WebAssembly::ExprType::F32x4; break;
260  case MVT::ExceptRef: retType = WebAssembly::ExprType::ExceptRef; break;
261  default: llvm_unreachable("unexpected return type");
262  }
263 
264  for (MachineBasicBlock &MBB : reverse(MF)) {
265  for (MachineInstr &MI : reverse(MBB)) {
266  if (MI.isPosition() || MI.isDebugInstr())
267  continue;
268  if (MI.getOpcode() == WebAssembly::END_BLOCK) {
269  BlockTops[&MI]->getOperand(0).setImm(int32_t(retType));
270  continue;
271  }
272  if (MI.getOpcode() == WebAssembly::END_LOOP) {
273  LoopTops[&MI]->getOperand(0).setImm(int32_t(retType));
274  continue;
275  }
276  // Something other than an `end`. We're done.
277  return;
278  }
279  }
280 }
281 
282 // WebAssembly functions end with an end instruction, as if the function body
283 // were a block.
285  MachineFunction &MF,
286  const WebAssemblyInstrInfo &TII) {
287  BuildMI(MF.back(), MF.back().end(),
288  MF.back().findPrevDebugLoc(MF.back().end()),
289  TII.get(WebAssembly::END_FUNCTION));
290 }
291 
292 /// Insert LOOP and BLOCK markers at appropriate places.
293 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI,
294  const WebAssemblyInstrInfo &TII,
297  // For each block whose label represents the end of a scope, record the block
298  // which holds the beginning of the scope. This will allow us to quickly skip
299  // over scoped regions when walking blocks. We allocate one more than the
300  // number of blocks in the function to accommodate for the possible fake block
301  // we may insert at the end.
303 
304  // For each LOOP_END, the corresponding LOOP.
306 
307  // For each END_BLOCK, the corresponding BLOCK.
309 
310  for (auto &MBB : MF) {
311  // Place the LOOP for MBB if MBB is the header of a loop.
312  PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI);
313 
314  // Place the BLOCK for MBB if MBB is branched to from above.
315  PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI);
316  }
317 
318  // Now rewrite references to basic blocks to be depth immediates.
320  for (auto &MBB : reverse(MF)) {
321  for (auto &MI : reverse(MBB)) {
322  switch (MI.getOpcode()) {
323  case WebAssembly::BLOCK:
324  assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() &&
325  "Block should be balanced");
326  Stack.pop_back();
327  break;
328  case WebAssembly::LOOP:
329  assert(Stack.back() == &MBB && "Loop top should be balanced");
330  Stack.pop_back();
331  break;
333  Stack.push_back(&MBB);
334  break;
335  case WebAssembly::END_LOOP:
336  Stack.push_back(LoopTops[&MI]->getParent());
337  break;
338  default:
339  if (MI.isTerminator()) {
340  // Rewrite MBB operands to be depth immediates.
341  SmallVector<MachineOperand, 4> Ops(MI.operands());
342  while (MI.getNumOperands() > 0)
343  MI.RemoveOperand(MI.getNumOperands() - 1);
344  for (auto MO : Ops) {
345  if (MO.isMBB())
346  MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB()));
347  MI.addOperand(MF, MO);
348  }
349  }
350  break;
351  }
352  }
353  }
354  assert(Stack.empty() && "Control flow should be balanced");
355 
356  // Fix up block/loop signatures at the end of the function to conform to
357  // WebAssembly's rules.
358  FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops);
359 
360  // Add an end instruction at the end of the function body.
361  AppendEndToFunction(MF, TII);
362 }
363 
364 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) {
365  LLVM_DEBUG(dbgs() << "********** CFG Stackifying **********\n"
366  "********** Function: "
367  << MF.getName() << '\n');
368 
369  const auto &MLI = getAnalysis<MachineLoopInfo>();
370  auto &MDT = getAnalysis<MachineDominatorTree>();
371  // Liveness is not tracked for VALUE_STACK physreg.
372  const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
375 
376  // Place the BLOCK and LOOP markers to indicate the beginnings of scopes.
377  PlaceMarkers(MF, MLI, TII, MDT, MFI);
378 
379  return true;
380 }
pred_reverse_iterator pred_rbegin()
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID&#39;s allocated.
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...
AnalysisUsage & addRequired()
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
const HexagonInstrInfo * TII
INITIALIZE_PASS(WebAssemblyCFGStackify, DEBUG_TYPE, "Insert BLOCK and LOOP markers for WebAssembly scopes", false, false) FunctionPass *llvm
static unsigned GetDepth(const SmallVectorImpl< const MachineBasicBlock *> &Stack, const MachineBasicBlock *MBB)
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 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).
BlockT * getHeader() const
Definition: LoopInfo.h:100
#define DEBUG_TYPE
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
DebugLoc findPrevDebugLoc(instr_iterator MBBI)
Find the previous valid DebugLoc preceding MBBI, skipping and DBG_VALUE instructions.
int getNumber() const
MachineBasicBlocks are uniquely numbered at the function level, unless they&#39;re not in a MachineFuncti...
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)
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
This file contains the declaration of the WebAssembly-specific utility functions. ...
MachineInstrBuilder BuildMI(MachineFunction &MF, const DebugLoc &DL, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DebugLoc findDebugLoc(instr_iterator MBBI)
Find the next valid DebugLoc starting at MBBI, skipping any DBG_VALUE and DBG_LABEL instructions...
This file provides WebAssembly-specific target descriptions.
Represent the analysis usage information of a pass.
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:285
iterator_range< pred_iterator > predecessors()
const MachineBasicBlock & front() const
size_t size() const
Definition: SmallVector.h:53
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This file declares the WebAssembly-specific subclass of TargetSubtarget.
Iterator for intrusive lists based on ilist_node.
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 &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
ExprType
This is used to indicate block signatures.
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:286
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:133
Representation of each machine instruction.
Definition: MachineInstr.h:60
This class is derived from MachineFunctionInfo and contains private WebAssembly-specific information ...
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
Represents a single loop in the control flow graph.
Definition: LoopInfo.h:459
static MachineOperand CreateImm(int64_t Val)
#define I(x, y, z)
Definition: MD5.cpp:58
This file declares WebAssembly-specific per-machine-function information.
const MachineBasicBlock & back() const
const std::vector< MVT > & getResults() const
FunctionPass * createWebAssemblyCFGStackify()
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
MachineBasicBlock * getBottom(const T *Unit)
Return the "bottom" block of an entity, which can be either a MachineLoop or WebAssemblyException.
MachineLoop * getLoopFor(const MachineBasicBlock *BB) const
Return the innermost loop that BB lives in.
void push_back(MachineBasicBlock *MBB)
static const Function * getParent(const Value *V)
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&#39;s a loop header).
IRTranslator LLVM IR MI
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
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...
#define LLVM_DEBUG(X)
Definition: Debug.h:119
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...