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 21 #include "MCTargetDesc/WebAssemblyMCTargetDesc.h" 22 #include "WebAssembly.h" 23 #include "WebAssemblyMachineFunctionInfo.h" 24 #include "WebAssemblySubtarget.h" 25 #include "WebAssemblyUtilities.h" 26 #include "llvm/CodeGen/MachineDominators.h" 27 #include "llvm/CodeGen/MachineFunction.h" 28 #include "llvm/CodeGen/MachineInstrBuilder.h" 29 #include "llvm/CodeGen/MachineLoopInfo.h" 30 #include "llvm/CodeGen/MachineRegisterInfo.h" 31 #include "llvm/CodeGen/Passes.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/raw_ostream.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(); 44 AU.addRequired<MachineDominatorTree>(); 45 AU.addPreserved<MachineDominatorTree>(); 46 AU.addRequired<MachineLoopInfo>(); 47 AU.addPreserved<MachineLoopInfo>(); 48 MachineFunctionPass::getAnalysisUsage(AU); 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 59 char WebAssemblyCFGStackify::ID = 0; 60 FunctionPass *llvm::createWebAssemblyCFGStackify() { 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. 69 static bool ExplicitlyBranchesTo(MachineBasicBlock *Pred, 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( 80 MachineBasicBlock &MBB, MachineFunction &MF, 81 SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 82 DenseMap<const MachineInstr *, MachineInstr *> &BlockTops, 83 DenseMap<const MachineInstr *, MachineInstr *> &LoopTops, 84 const WebAssemblyInstrInfo &TII, 85 const MachineLoopInfo &MLI, 86 MachineDominatorTree &MDT, 87 WebAssemblyFunctionInfo &MFI) { 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, MBB.findDebugLoc(InsertPos), 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, MBB.findPrevDebugLoc(InsertPos), 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( 169 MachineBasicBlock &MBB, MachineFunction &MF, 170 SmallVectorImpl<MachineBasicBlock *> &ScopeTops, 171 DenseMap<const MachineInstr *, MachineInstr *> &LoopTops, 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()) { 182 MachineBasicBlock *Label = MF.CreateMachineBasicBlock(); 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, MBB.findDebugLoc(InsertPos), 197 TII.get(WebAssembly::LOOP)) 198 .addImm(int64_t(WebAssembly::ExprType::Void)); 199 200 // Mark the end of the loop (using arbitrary debug location that branched 201 // to the loop end as its location). 202 DebugLoc EndDL = (*AfterLoop->pred_rbegin())->findBranchDebugLoc(); 203 MachineInstr *End = BuildMI(*AfterLoop, AfterLoop->begin(), EndDL, 204 TII.get(WebAssembly::END_LOOP)); 205 LoopTops[End] = Begin; 206 207 assert((!ScopeTops[AfterLoop->getNumber()] || 208 ScopeTops[AfterLoop->getNumber()]->getNumber() < MBB.getNumber()) && 209 "With block sorting the outermost loop for a block should be first."); 210 if (!ScopeTops[AfterLoop->getNumber()]) 211 ScopeTops[AfterLoop->getNumber()] = &MBB; 212 } 213 214 static unsigned 215 GetDepth(const SmallVectorImpl<const MachineBasicBlock *> &Stack, 216 const MachineBasicBlock *MBB) { 217 unsigned Depth = 0; 218 for (auto X : reverse(Stack)) { 219 if (X == MBB) 220 break; 221 ++Depth; 222 } 223 assert(Depth < Stack.size() && "Branch destination should be in scope"); 224 return Depth; 225 } 226 227 /// In normal assembly languages, when the end of a function is unreachable, 228 /// because the function ends in an infinite loop or a noreturn call or similar, 229 /// it isn't necessary to worry about the function return type at the end of 230 /// the function, because it's never reached. However, in WebAssembly, blocks 231 /// that end at the function end need to have a return type signature that 232 /// matches the function signature, even though it's unreachable. This function 233 /// checks for such cases and fixes up the signatures. 234 static void FixEndsAtEndOfFunction( 235 MachineFunction &MF, 236 const WebAssemblyFunctionInfo &MFI, 237 DenseMap<const MachineInstr *, MachineInstr *> &BlockTops, 238 DenseMap<const MachineInstr *, MachineInstr *> &LoopTops) { 239 assert(MFI.getResults().size() <= 1); 240 241 if (MFI.getResults().empty()) 242 return; 243 244 WebAssembly::ExprType retType; 245 switch (MFI.getResults().front().SimpleTy) { 246 case MVT::i32: retType = WebAssembly::ExprType::I32; break; 247 case MVT::i64: retType = WebAssembly::ExprType::I64; break; 248 case MVT::f32: retType = WebAssembly::ExprType::F32; break; 249 case MVT::f64: retType = WebAssembly::ExprType::F64; break; 250 case MVT::v16i8: retType = WebAssembly::ExprType::I8x16; break; 251 case MVT::v8i16: retType = WebAssembly::ExprType::I16x8; break; 252 case MVT::v4i32: retType = WebAssembly::ExprType::I32x4; break; 253 case MVT::v4f32: retType = WebAssembly::ExprType::F32x4; break; 254 case MVT::ExceptRef: retType = WebAssembly::ExprType::ExceptRef; break; 255 default: llvm_unreachable("unexpected return type"); 256 } 257 258 for (MachineBasicBlock &MBB : reverse(MF)) { 259 for (MachineInstr &MI : reverse(MBB)) { 260 if (MI.isPosition() || MI.isDebugValue()) 261 continue; 262 if (MI.getOpcode() == WebAssembly::END_BLOCK) { 263 BlockTops[&MI]->getOperand(0).setImm(int32_t(retType)); 264 continue; 265 } 266 if (MI.getOpcode() == WebAssembly::END_LOOP) { 267 LoopTops[&MI]->getOperand(0).setImm(int32_t(retType)); 268 continue; 269 } 270 // Something other than an `end`. We're done. 271 return; 272 } 273 } 274 } 275 276 // WebAssembly functions end with an end instruction, as if the function body 277 // were a block. 278 static void AppendEndToFunction( 279 MachineFunction &MF, 280 const WebAssemblyInstrInfo &TII) { 281 BuildMI(MF.back(), MF.back().end(), 282 MF.back().findPrevDebugLoc(MF.back().end()), 283 TII.get(WebAssembly::END_FUNCTION)); 284 } 285 286 /// Insert LOOP and BLOCK markers at appropriate places. 287 static void PlaceMarkers(MachineFunction &MF, const MachineLoopInfo &MLI, 288 const WebAssemblyInstrInfo &TII, 289 MachineDominatorTree &MDT, 290 WebAssemblyFunctionInfo &MFI) { 291 // For each block whose label represents the end of a scope, record the block 292 // which holds the beginning of the scope. This will allow us to quickly skip 293 // over scoped regions when walking blocks. We allocate one more than the 294 // number of blocks in the function to accommodate for the possible fake block 295 // we may insert at the end. 296 SmallVector<MachineBasicBlock *, 8> ScopeTops(MF.getNumBlockIDs() + 1); 297 298 // For each LOOP_END, the corresponding LOOP. 299 DenseMap<const MachineInstr *, MachineInstr *> LoopTops; 300 301 // For each END_BLOCK, the corresponding BLOCK. 302 DenseMap<const MachineInstr *, MachineInstr *> BlockTops; 303 304 for (auto &MBB : MF) { 305 // Place the LOOP for MBB if MBB is the header of a loop. 306 PlaceLoopMarker(MBB, MF, ScopeTops, LoopTops, TII, MLI); 307 308 // Place the BLOCK for MBB if MBB is branched to from above. 309 PlaceBlockMarker(MBB, MF, ScopeTops, BlockTops, LoopTops, TII, MLI, MDT, MFI); 310 } 311 312 // Now rewrite references to basic blocks to be depth immediates. 313 SmallVector<const MachineBasicBlock *, 8> Stack; 314 for (auto &MBB : reverse(MF)) { 315 for (auto &MI : reverse(MBB)) { 316 switch (MI.getOpcode()) { 317 case WebAssembly::BLOCK: 318 assert(ScopeTops[Stack.back()->getNumber()]->getNumber() <= MBB.getNumber() && 319 "Block should be balanced"); 320 Stack.pop_back(); 321 break; 322 case WebAssembly::LOOP: 323 assert(Stack.back() == &MBB && "Loop top should be balanced"); 324 Stack.pop_back(); 325 break; 326 case WebAssembly::END_BLOCK: 327 Stack.push_back(&MBB); 328 break; 329 case WebAssembly::END_LOOP: 330 Stack.push_back(LoopTops[&MI]->getParent()); 331 break; 332 default: 333 if (MI.isTerminator()) { 334 // Rewrite MBB operands to be depth immediates. 335 SmallVector<MachineOperand, 4> Ops(MI.operands()); 336 while (MI.getNumOperands() > 0) 337 MI.RemoveOperand(MI.getNumOperands() - 1); 338 for (auto MO : Ops) { 339 if (MO.isMBB()) 340 MO = MachineOperand::CreateImm(GetDepth(Stack, MO.getMBB())); 341 MI.addOperand(MF, MO); 342 } 343 } 344 break; 345 } 346 } 347 } 348 assert(Stack.empty() && "Control flow should be balanced"); 349 350 // Fix up block/loop signatures at the end of the function to conform to 351 // WebAssembly's rules. 352 FixEndsAtEndOfFunction(MF, MFI, BlockTops, LoopTops); 353 354 // Add an end instruction at the end of the function body. 355 if (!MF.getSubtarget<WebAssemblySubtarget>() 356 .getTargetTriple().isOSBinFormatELF()) 357 AppendEndToFunction(MF, TII); 358 } 359 360 bool WebAssemblyCFGStackify::runOnMachineFunction(MachineFunction &MF) { 361 DEBUG(dbgs() << "********** CFG Stackifying **********\n" 362 "********** Function: " 363 << MF.getName() << '\n'); 364 365 const auto &MLI = getAnalysis<MachineLoopInfo>(); 366 auto &MDT = getAnalysis<MachineDominatorTree>(); 367 // Liveness is not tracked for VALUE_STACK physreg. 368 const auto &TII = *MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo(); 369 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>(); 370 MF.getRegInfo().invalidateLiveness(); 371 372 // Place the BLOCK and LOOP markers to indicate the beginnings of scopes. 373 PlaceMarkers(MF, MLI, TII, MDT, MFI); 374 375 return true; 376 } 377