blob: dc2aab875932926e45dab49124fa2aa6022ed3c8 [file] [log] [blame]
Dan Gohman1462faa2015-11-16 16:18:28 +00001//===-- WebAssemblyRegStackify.cpp - Register 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
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000011/// This file implements a register stacking pass.
Dan Gohman1462faa2015-11-16 16:18:28 +000012///
13/// This pass reorders instructions to put register uses and defs in an order
14/// such that they form single-use expression trees. Registers fitting this form
15/// are then marked as "stackified", meaning references to them are replaced by
Dan Gohmane0405332016-10-03 22:43:53 +000016/// "push" and "pop" from the value stack.
Dan Gohman1462faa2015-11-16 16:18:28 +000017///
Dan Gohman31448f12015-12-08 03:43:03 +000018/// This is primarily a code size optimization, since temporary values on the
Dan Gohmane0405332016-10-03 22:43:53 +000019/// value stack don't need to be named.
Dan Gohman1462faa2015-11-16 16:18:28 +000020///
21//===----------------------------------------------------------------------===//
22
Dan Gohman4ba48162015-11-18 16:12:01 +000023#include "MCTargetDesc/WebAssemblyMCTargetDesc.h" // for WebAssembly::ARGUMENT_*
Chandler Carruth6bda14b2017-06-06 11:49:48 +000024#include "WebAssembly.h"
Dan Gohman7a6b9822015-11-29 22:32:02 +000025#include "WebAssemblyMachineFunctionInfo.h"
Dan Gohmanb6fd39a2016-01-19 16:59:23 +000026#include "WebAssemblySubtarget.h"
Dan Gohman4fc4e422016-10-24 19:49:43 +000027#include "WebAssemblyUtilities.h"
Yury Delendik7c18d602018-09-25 18:59:34 +000028#include "llvm/ADT/SmallPtrSet.h"
Dan Gohman81719f82015-11-25 16:55:01 +000029#include "llvm/Analysis/AliasAnalysis.h"
Matthias Braunf8422972017-12-13 02:51:04 +000030#include "llvm/CodeGen/LiveIntervals.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000031#include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
Dan Gohmanadf28172016-01-28 01:22:44 +000032#include "llvm/CodeGen/MachineDominators.h"
33#include "llvm/CodeGen/MachineInstrBuilder.h"
Dan Gohman82607f52017-02-24 23:46:05 +000034#include "llvm/CodeGen/MachineModuleInfoImpls.h"
Dan Gohman1462faa2015-11-16 16:18:28 +000035#include "llvm/CodeGen/MachineRegisterInfo.h"
36#include "llvm/CodeGen/Passes.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/raw_ostream.h"
39using namespace llvm;
40
41#define DEBUG_TYPE "wasm-reg-stackify"
42
43namespace {
44class WebAssemblyRegStackify final : public MachineFunctionPass {
Mehdi Amini117296c2016-10-01 02:56:57 +000045 StringRef getPassName() const override {
Dan Gohman1462faa2015-11-16 16:18:28 +000046 return "WebAssembly Register Stackify";
47 }
48
49 void getAnalysisUsage(AnalysisUsage &AU) const override {
50 AU.setPreservesCFG();
Dan Gohman81719f82015-11-25 16:55:01 +000051 AU.addRequired<AAResultsWrapperPass>();
Dan Gohmanadf28172016-01-28 01:22:44 +000052 AU.addRequired<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000053 AU.addRequired<LiveIntervals>();
Dan Gohman1462faa2015-11-16 16:18:28 +000054 AU.addPreserved<MachineBlockFrequencyInfo>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000055 AU.addPreserved<SlotIndexes>();
56 AU.addPreserved<LiveIntervals>();
Dan Gohman8887d1f2015-12-25 00:31:02 +000057 AU.addPreservedID(LiveVariablesID);
Dan Gohmanadf28172016-01-28 01:22:44 +000058 AU.addPreserved<MachineDominatorTree>();
Dan Gohman1462faa2015-11-16 16:18:28 +000059 MachineFunctionPass::getAnalysisUsage(AU);
60 }
61
62 bool runOnMachineFunction(MachineFunction &MF) override;
63
64public:
65 static char ID; // Pass identification, replacement for typeid
66 WebAssemblyRegStackify() : MachineFunctionPass(ID) {}
67};
68} // end anonymous namespace
69
70char WebAssemblyRegStackify::ID = 0;
Jacob Gravelle40926452018-03-30 20:36:58 +000071INITIALIZE_PASS(WebAssemblyRegStackify, DEBUG_TYPE,
72 "Reorder instructions to use the WebAssembly value stack",
73 false, false)
74
Dan Gohman1462faa2015-11-16 16:18:28 +000075FunctionPass *llvm::createWebAssemblyRegStackify() {
76 return new WebAssemblyRegStackify();
77}
78
Dan Gohmanb0992da2015-11-20 02:19:12 +000079// Decorate the given instruction with implicit operands that enforce the
Dan Gohman8887d1f2015-12-25 00:31:02 +000080// expression stack ordering constraints for an instruction which is on
81// the expression stack.
82static void ImposeStackOrdering(MachineInstr *MI) {
Dan Gohmane0405332016-10-03 22:43:53 +000083 // Write the opaque VALUE_STACK register.
84 if (!MI->definesRegister(WebAssembly::VALUE_STACK))
85 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohman4da4abd2015-12-05 00:51:40 +000086 /*isDef=*/true,
87 /*isImp=*/true));
Dan Gohman4da4abd2015-12-05 00:51:40 +000088
Dan Gohmane0405332016-10-03 22:43:53 +000089 // Also read the opaque VALUE_STACK register.
90 if (!MI->readsRegister(WebAssembly::VALUE_STACK))
91 MI->addOperand(MachineOperand::CreateReg(WebAssembly::VALUE_STACK,
Dan Gohmana712a6c2015-12-14 22:37:23 +000092 /*isDef=*/false,
93 /*isImp=*/true));
Dan Gohmanb0992da2015-11-20 02:19:12 +000094}
95
Dan Gohmane81021a2016-11-08 19:40:38 +000096// Convert an IMPLICIT_DEF instruction into an instruction which defines
97// a constant zero value.
98static void ConvertImplicitDefToConstZero(MachineInstr *MI,
99 MachineRegisterInfo &MRI,
100 const TargetInstrInfo *TII,
101 MachineFunction &MF) {
102 assert(MI->getOpcode() == TargetOpcode::IMPLICIT_DEF);
103
Heejin Ahnf208f632018-09-05 01:27:38 +0000104 const auto *RegClass = MRI.getRegClass(MI->getOperand(0).getReg());
Dan Gohmane81021a2016-11-08 19:40:38 +0000105 if (RegClass == &WebAssembly::I32RegClass) {
106 MI->setDesc(TII->get(WebAssembly::CONST_I32));
107 MI->addOperand(MachineOperand::CreateImm(0));
108 } else if (RegClass == &WebAssembly::I64RegClass) {
109 MI->setDesc(TII->get(WebAssembly::CONST_I64));
110 MI->addOperand(MachineOperand::CreateImm(0));
111 } else if (RegClass == &WebAssembly::F32RegClass) {
112 MI->setDesc(TII->get(WebAssembly::CONST_F32));
113 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000114 Type::getFloatTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000115 MI->addOperand(MachineOperand::CreateFPImm(Val));
116 } else if (RegClass == &WebAssembly::F64RegClass) {
117 MI->setDesc(TII->get(WebAssembly::CONST_F64));
118 ConstantFP *Val = cast<ConstantFP>(Constant::getNullValue(
David Blaikie21109242017-12-15 23:52:06 +0000119 Type::getDoubleTy(MF.getFunction().getContext())));
Dan Gohmane81021a2016-11-08 19:40:38 +0000120 MI->addOperand(MachineOperand::CreateFPImm(Val));
Thomas Lively6ff31fe2018-10-31 23:50:53 +0000121 } else if (RegClass == &WebAssembly::V128RegClass) {
122 // TODO: make splat instead of constant
123 MI->setDesc(TII->get(WebAssembly::CONST_V128_v16i8));
124 for (int I = 0; I < 16; ++I)
125 MI->addOperand(MachineOperand::CreateImm(0));
Dan Gohmane81021a2016-11-08 19:40:38 +0000126 } else {
127 llvm_unreachable("Unexpected reg class");
128 }
129}
130
Dan Gohman2644d742016-05-17 04:05:31 +0000131// Determine whether a call to the callee referenced by
132// MI->getOperand(CalleeOpNo) reads memory, writes memory, and/or has side
133// effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000134static void QueryCallee(const MachineInstr &MI, unsigned CalleeOpNo, bool &Read,
135 bool &Write, bool &Effects, bool &StackPointer) {
Dan Gohmand08cd152016-05-17 21:14:26 +0000136 // All calls can use the stack pointer.
137 StackPointer = true;
138
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000139 const MachineOperand &MO = MI.getOperand(CalleeOpNo);
Dan Gohman2644d742016-05-17 04:05:31 +0000140 if (MO.isGlobal()) {
141 const Constant *GV = MO.getGlobal();
142 if (const GlobalAlias *GA = dyn_cast<GlobalAlias>(GV))
143 if (!GA->isInterposable())
144 GV = GA->getAliasee();
145
146 if (const Function *F = dyn_cast<Function>(GV)) {
147 if (!F->doesNotThrow())
148 Effects = true;
149 if (F->doesNotAccessMemory())
150 return;
151 if (F->onlyReadsMemory()) {
152 Read = true;
153 return;
154 }
155 }
156 }
157
158 // Assume the worst.
159 Write = true;
160 Read = true;
161 Effects = true;
162}
163
Dan Gohmand08cd152016-05-17 21:14:26 +0000164// Determine whether MI reads memory, writes memory, has side effects,
Dan Gohman82607f52017-02-24 23:46:05 +0000165// and/or uses the stack pointer value.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000166static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read,
167 bool &Write, bool &Effects, bool &StackPointer) {
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000168 assert(!MI.isTerminator());
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000169
Heejin Ahn5ef4d5f2018-05-31 22:25:54 +0000170 if (MI.isDebugInstr() || MI.isPosition())
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000171 return;
Dan Gohman2644d742016-05-17 04:05:31 +0000172
173 // Check for loads.
Justin Lebard98cf002016-09-10 01:03:20 +0000174 if (MI.mayLoad() && !MI.isDereferenceableInvariantLoad(&AA))
Dan Gohman2644d742016-05-17 04:05:31 +0000175 Read = true;
176
177 // Check for stores.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000178 if (MI.mayStore()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000179 Write = true;
Dan Gohmand08cd152016-05-17 21:14:26 +0000180
Sam Clegg9d24fb72017-06-16 23:59:10 +0000181 // Check for stores to __stack_pointer.
182 for (auto MMO : MI.memoperands()) {
183 const MachinePointerInfo &MPI = MMO->getPointerInfo();
184 if (MPI.V.is<const PseudoSourceValue *>()) {
185 auto PSV = MPI.V.get<const PseudoSourceValue *>();
186 if (const ExternalSymbolPseudoSourceValue *EPSV =
187 dyn_cast<ExternalSymbolPseudoSourceValue>(PSV))
188 if (StringRef(EPSV->getSymbol()) == "__stack_pointer") {
189 StackPointer = true;
190 }
Dan Gohmand08cd152016-05-17 21:14:26 +0000191 }
192 }
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000193 } else if (MI.hasOrderedMemoryRef()) {
194 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000195 case WebAssembly::DIV_S_I32:
196 case WebAssembly::DIV_S_I64:
197 case WebAssembly::REM_S_I32:
198 case WebAssembly::REM_S_I64:
199 case WebAssembly::DIV_U_I32:
200 case WebAssembly::DIV_U_I64:
201 case WebAssembly::REM_U_I32:
202 case WebAssembly::REM_U_I64:
203 case WebAssembly::I32_TRUNC_S_F32:
204 case WebAssembly::I64_TRUNC_S_F32:
205 case WebAssembly::I32_TRUNC_S_F64:
206 case WebAssembly::I64_TRUNC_S_F64:
207 case WebAssembly::I32_TRUNC_U_F32:
208 case WebAssembly::I64_TRUNC_U_F32:
209 case WebAssembly::I32_TRUNC_U_F64:
210 case WebAssembly::I64_TRUNC_U_F64:
Dan Gohman2644d742016-05-17 04:05:31 +0000211 // These instruction have hasUnmodeledSideEffects() returning true
212 // because they trap on overflow and invalid so they can't be arbitrarily
213 // moved, however hasOrderedMemoryRef() interprets this plus their lack
214 // of memoperands as having a potential unknown memory reference.
215 break;
216 default:
Dan Gohman10545702016-05-17 22:24:18 +0000217 // Record volatile accesses, unless it's a call, as calls are handled
Dan Gohman2644d742016-05-17 04:05:31 +0000218 // specially below.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000219 if (!MI.isCall()) {
Dan Gohman2644d742016-05-17 04:05:31 +0000220 Write = true;
Dan Gohman10545702016-05-17 22:24:18 +0000221 Effects = true;
222 }
Dan Gohman2644d742016-05-17 04:05:31 +0000223 break;
224 }
225 }
226
227 // Check for side effects.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000228 if (MI.hasUnmodeledSideEffects()) {
229 switch (MI.getOpcode()) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000230 case WebAssembly::DIV_S_I32:
231 case WebAssembly::DIV_S_I64:
232 case WebAssembly::REM_S_I32:
233 case WebAssembly::REM_S_I64:
234 case WebAssembly::DIV_U_I32:
235 case WebAssembly::DIV_U_I64:
236 case WebAssembly::REM_U_I32:
237 case WebAssembly::REM_U_I64:
238 case WebAssembly::I32_TRUNC_S_F32:
239 case WebAssembly::I64_TRUNC_S_F32:
240 case WebAssembly::I32_TRUNC_S_F64:
241 case WebAssembly::I64_TRUNC_S_F64:
242 case WebAssembly::I32_TRUNC_U_F32:
243 case WebAssembly::I64_TRUNC_U_F32:
244 case WebAssembly::I32_TRUNC_U_F64:
245 case WebAssembly::I64_TRUNC_U_F64:
Dan Gohman2644d742016-05-17 04:05:31 +0000246 // These instructions have hasUnmodeledSideEffects() returning true
247 // because they trap on overflow and invalid so they can't be arbitrarily
248 // moved, however in the specific case of register stackifying, it is safe
249 // to move them because overflow and invalid are Undefined Behavior.
250 break;
251 default:
252 Effects = true;
253 break;
254 }
255 }
256
257 // Analyze calls.
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000258 if (MI.isCall()) {
Heejin Ahn56e79dd2018-08-28 17:49:39 +0000259 unsigned CalleeOpNo = WebAssembly::getCalleeOpNo(MI);
260 QueryCallee(MI, CalleeOpNo, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000261 }
262}
263
264// Test whether Def is safe and profitable to rematerialize.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000265static bool ShouldRematerialize(const MachineInstr &Def, AliasAnalysis &AA,
Dan Gohman2644d742016-05-17 04:05:31 +0000266 const WebAssemblyInstrInfo *TII) {
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000267 return Def.isAsCheapAsAMove() && TII->isTriviallyReMaterializable(Def, &AA);
Dan Gohman2644d742016-05-17 04:05:31 +0000268}
269
Dan Gohman12de0b92016-05-17 20:19:47 +0000270// Identify the definition for this register at this point. This is a
271// generalization of MachineRegisterInfo::getUniqueVRegDef that uses
272// LiveIntervals to handle complex cases.
Dan Gohman2644d742016-05-17 04:05:31 +0000273static MachineInstr *GetVRegDef(unsigned Reg, const MachineInstr *Insert,
274 const MachineRegisterInfo &MRI,
Heejin Ahnf208f632018-09-05 01:27:38 +0000275 const LiveIntervals &LIS) {
Dan Gohman2644d742016-05-17 04:05:31 +0000276 // Most registers are in SSA form here so we try a quick MRI query first.
277 if (MachineInstr *Def = MRI.getUniqueVRegDef(Reg))
278 return Def;
279
280 // MRI doesn't know what the Def is. Try asking LIS.
281 if (const VNInfo *ValNo = LIS.getInterval(Reg).getVNInfoBefore(
282 LIS.getInstructionIndex(*Insert)))
283 return LIS.getInstructionFromIndex(ValNo->def);
284
285 return nullptr;
286}
287
Dan Gohman12de0b92016-05-17 20:19:47 +0000288// Test whether Reg, as defined at Def, has exactly one use. This is a
289// generalization of MachineRegisterInfo::hasOneUse that uses LiveIntervals
290// to handle complex cases.
Heejin Ahnf208f632018-09-05 01:27:38 +0000291static bool HasOneUse(unsigned Reg, MachineInstr *Def, MachineRegisterInfo &MRI,
292 MachineDominatorTree &MDT, LiveIntervals &LIS) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000293 // Most registers are in SSA form here so we try a quick MRI query first.
294 if (MRI.hasOneUse(Reg))
295 return true;
296
297 bool HasOne = false;
298 const LiveInterval &LI = LIS.getInterval(Reg);
Heejin Ahnf208f632018-09-05 01:27:38 +0000299 const VNInfo *DefVNI =
300 LI.getVNInfoAt(LIS.getInstructionIndex(*Def).getRegSlot());
Dan Gohman12de0b92016-05-17 20:19:47 +0000301 assert(DefVNI);
Dominic Chena8a63822016-08-17 23:42:27 +0000302 for (auto &I : MRI.use_nodbg_operands(Reg)) {
Dan Gohman12de0b92016-05-17 20:19:47 +0000303 const auto &Result = LI.Query(LIS.getInstructionIndex(*I.getParent()));
304 if (Result.valueIn() == DefVNI) {
305 if (!Result.isKill())
306 return false;
307 if (HasOne)
308 return false;
309 HasOne = true;
310 }
311 }
312 return HasOne;
313}
314
Dan Gohman8887d1f2015-12-25 00:31:02 +0000315// Test whether it's safe to move Def to just before Insert.
Dan Gohman81719f82015-11-25 16:55:01 +0000316// TODO: Compute memory dependencies in a way that doesn't require always
317// walking the block.
318// TODO: Compute memory dependencies in a way that uses AliasAnalysis to be
319// more precise.
320static bool IsSafeToMove(const MachineInstr *Def, const MachineInstr *Insert,
Derek Schuffe9e68912016-09-30 18:02:54 +0000321 AliasAnalysis &AA, const MachineRegisterInfo &MRI) {
Dan Gohman391a98a2015-12-03 23:07:03 +0000322 assert(Def->getParent() == Insert->getParent());
Dan Gohman8887d1f2015-12-25 00:31:02 +0000323
324 // Check for register dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000325 SmallVector<unsigned, 4> MutableRegisters;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000326 for (const MachineOperand &MO : Def->operands()) {
327 if (!MO.isReg() || MO.isUndef())
328 continue;
329 unsigned Reg = MO.getReg();
330
331 // If the register is dead here and at Insert, ignore it.
332 if (MO.isDead() && Insert->definesRegister(Reg) &&
333 !Insert->readsRegister(Reg))
334 continue;
335
336 if (TargetRegisterInfo::isPhysicalRegister(Reg)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000337 // Ignore ARGUMENTS; it's just used to keep the ARGUMENT_* instructions
338 // from moving down, and we've already checked for that.
339 if (Reg == WebAssembly::ARGUMENTS)
340 continue;
Dan Gohman8887d1f2015-12-25 00:31:02 +0000341 // If the physical register is never modified, ignore it.
342 if (!MRI.isPhysRegModified(Reg))
343 continue;
344 // Otherwise, it's a physical register with unknown liveness.
345 return false;
346 }
347
Derek Schuffe9e68912016-09-30 18:02:54 +0000348 // If one of the operands isn't in SSA form, it has different values at
349 // different times, and we need to make sure we don't move our use across
350 // a different def.
351 if (!MO.isDef() && !MRI.hasOneDef(Reg))
352 MutableRegisters.push_back(Reg);
Dan Gohman8887d1f2015-12-25 00:31:02 +0000353 }
354
Dan Gohmand08cd152016-05-17 21:14:26 +0000355 bool Read = false, Write = false, Effects = false, StackPointer = false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000356 Query(*Def, AA, Read, Write, Effects, StackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000357
358 // If the instruction does not access memory and has no side effects, it has
359 // no additional dependencies.
Derek Schuffe9e68912016-09-30 18:02:54 +0000360 bool HasMutableRegisters = !MutableRegisters.empty();
361 if (!Read && !Write && !Effects && !StackPointer && !HasMutableRegisters)
Dan Gohman2644d742016-05-17 04:05:31 +0000362 return true;
363
364 // Scan through the intervening instructions between Def and Insert.
365 MachineBasicBlock::const_iterator D(Def), I(Insert);
366 for (--I; I != D; --I) {
367 bool InterveningRead = false;
368 bool InterveningWrite = false;
369 bool InterveningEffects = false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000370 bool InterveningStackPointer = false;
Duncan P. N. Exon Smith500d0462016-07-08 19:36:40 +0000371 Query(*I, AA, InterveningRead, InterveningWrite, InterveningEffects,
Dan Gohmand08cd152016-05-17 21:14:26 +0000372 InterveningStackPointer);
Dan Gohman2644d742016-05-17 04:05:31 +0000373 if (Effects && InterveningEffects)
374 return false;
375 if (Read && InterveningWrite)
376 return false;
377 if (Write && (InterveningRead || InterveningWrite))
378 return false;
Dan Gohmand08cd152016-05-17 21:14:26 +0000379 if (StackPointer && InterveningStackPointer)
380 return false;
Derek Schuffe9e68912016-09-30 18:02:54 +0000381
382 for (unsigned Reg : MutableRegisters)
383 for (const MachineOperand &MO : I->operands())
384 if (MO.isReg() && MO.isDef() && MO.getReg() == Reg)
385 return false;
Dan Gohman2644d742016-05-17 04:05:31 +0000386 }
387
388 return true;
Dan Gohman81719f82015-11-25 16:55:01 +0000389}
390
Dan Gohmanadf28172016-01-28 01:22:44 +0000391/// Test whether OneUse, a use of Reg, dominates all of Reg's other uses.
392static bool OneUseDominatesOtherUses(unsigned Reg, const MachineOperand &OneUse,
393 const MachineBasicBlock &MBB,
394 const MachineRegisterInfo &MRI,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000395 const MachineDominatorTree &MDT,
Dan Gohman10545702016-05-17 22:24:18 +0000396 LiveIntervals &LIS,
397 WebAssemblyFunctionInfo &MFI) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000398 const LiveInterval &LI = LIS.getInterval(Reg);
399
400 const MachineInstr *OneUseInst = OneUse.getParent();
401 VNInfo *OneUseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*OneUseInst));
402
Dominic Chena8a63822016-08-17 23:42:27 +0000403 for (const MachineOperand &Use : MRI.use_nodbg_operands(Reg)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000404 if (&Use == &OneUse)
405 continue;
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000406
Dan Gohmanadf28172016-01-28 01:22:44 +0000407 const MachineInstr *UseInst = Use.getParent();
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000408 VNInfo *UseVNI = LI.getVNInfoBefore(LIS.getInstructionIndex(*UseInst));
409
410 if (UseVNI != OneUseVNI)
411 continue;
412
Dan Gohmanadf28172016-01-28 01:22:44 +0000413 const MachineInstr *OneUseInst = OneUse.getParent();
Dan Gohman12de0b92016-05-17 20:19:47 +0000414 if (UseInst == OneUseInst) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000415 // Another use in the same instruction. We need to ensure that the one
416 // selected use happens "before" it.
417 if (&OneUse > &Use)
418 return false;
419 } else {
420 // Test that the use is dominated by the one selected use.
Dan Gohman10545702016-05-17 22:24:18 +0000421 while (!MDT.dominates(OneUseInst, UseInst)) {
422 // Actually, dominating is over-conservative. Test that the use would
423 // happen after the one selected use in the stack evaluation order.
424 //
425 // This is needed as a consequence of using implicit get_locals for
426 // uses and implicit set_locals for defs.
Dominic Chen4173fff2016-08-11 04:10:56 +0000427 if (UseInst->getDesc().getNumDefs() == 0)
Dan Gohman10545702016-05-17 22:24:18 +0000428 return false;
429 const MachineOperand &MO = UseInst->getOperand(0);
430 if (!MO.isReg())
431 return false;
432 unsigned DefReg = MO.getReg();
433 if (!TargetRegisterInfo::isVirtualRegister(DefReg) ||
434 !MFI.isVRegStackified(DefReg))
435 return false;
Yury Delendikb3857e42018-09-26 23:49:21 +0000436 assert(MRI.hasOneNonDBGUse(DefReg));
437 const MachineOperand &NewUse = *MRI.use_nodbg_begin(DefReg);
Dan Gohman10545702016-05-17 22:24:18 +0000438 const MachineInstr *NewUseInst = NewUse.getParent();
439 if (NewUseInst == OneUseInst) {
440 if (&OneUse > &NewUse)
441 return false;
442 break;
443 }
444 UseInst = NewUseInst;
445 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000446 }
447 }
448 return true;
449}
450
Dan Gohman4fc4e422016-10-24 19:49:43 +0000451/// Get the appropriate tee opcode for the given register class.
452static unsigned GetTeeOpcode(const TargetRegisterClass *RC) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000453 if (RC == &WebAssembly::I32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000454 return WebAssembly::TEE_I32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000455 if (RC == &WebAssembly::I64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000456 return WebAssembly::TEE_I64;
Dan Gohmanadf28172016-01-28 01:22:44 +0000457 if (RC == &WebAssembly::F32RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000458 return WebAssembly::TEE_F32;
Dan Gohmanadf28172016-01-28 01:22:44 +0000459 if (RC == &WebAssembly::F64RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000460 return WebAssembly::TEE_F64;
Derek Schuff39bf39f2016-08-02 23:16:09 +0000461 if (RC == &WebAssembly::V128RegClass)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000462 return WebAssembly::TEE_V128;
Dan Gohmanadf28172016-01-28 01:22:44 +0000463 llvm_unreachable("Unexpected register class");
464}
465
Dan Gohman2644d742016-05-17 04:05:31 +0000466// Shrink LI to its uses, cleaning up LI.
467static void ShrinkToUses(LiveInterval &LI, LiveIntervals &LIS) {
468 if (LIS.shrinkToUses(&LI)) {
Heejin Ahnf208f632018-09-05 01:27:38 +0000469 SmallVector<LiveInterval *, 4> SplitLIs;
Dan Gohman2644d742016-05-17 04:05:31 +0000470 LIS.splitSeparateComponents(LI, SplitLIs);
471 }
472}
473
Yury Delendik7c18d602018-09-25 18:59:34 +0000474static void MoveDebugValues(unsigned Reg, MachineInstr *Insert,
475 MachineBasicBlock &MBB, MachineRegisterInfo &MRI) {
476 for (auto &Op : MRI.reg_operands(Reg)) {
477 MachineInstr *MI = Op.getParent();
478 assert(MI != nullptr);
479 if (MI->isDebugValue() && MI->getParent() == &MBB)
480 MBB.splice(Insert, &MBB, MI);
481 }
482}
483
484static void UpdateDebugValuesReg(unsigned Reg, unsigned NewReg,
485 MachineBasicBlock &MBB,
486 MachineRegisterInfo &MRI) {
487 for (auto &Op : MRI.reg_operands(Reg)) {
488 MachineInstr *MI = Op.getParent();
489 assert(MI != nullptr);
490 if (MI->isDebugValue() && MI->getParent() == &MBB)
491 Op.setReg(NewReg);
492 }
493}
494
Dan Gohmanadf28172016-01-28 01:22:44 +0000495/// A single-use def in the same block with no intervening memory or register
496/// dependencies; move the def down and nest it with the current instruction.
Heejin Ahnf208f632018-09-05 01:27:38 +0000497static MachineInstr *MoveForSingleUse(unsigned Reg, MachineOperand &Op,
498 MachineInstr *Def, MachineBasicBlock &MBB,
Dan Gohmanadf28172016-01-28 01:22:44 +0000499 MachineInstr *Insert, LiveIntervals &LIS,
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000500 WebAssemblyFunctionInfo &MFI,
501 MachineRegisterInfo &MRI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000502 LLVM_DEBUG(dbgs() << "Move for single use: "; Def->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000503
Dan Gohmanadf28172016-01-28 01:22:44 +0000504 MBB.splice(Insert, &MBB, Def);
Yury Delendik7c18d602018-09-25 18:59:34 +0000505 MoveDebugValues(Reg, Insert, MBB, MRI);
JF Bastien1afd1e22016-02-28 15:33:53 +0000506 LIS.handleMove(*Def);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000507
Dan Gohman12de0b92016-05-17 20:19:47 +0000508 if (MRI.hasOneDef(Reg) && MRI.hasOneUse(Reg)) {
509 // No one else is using this register for anything so we can just stackify
510 // it in place.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000511 MFI.stackifyVReg(Reg);
512 } else {
Dan Gohman12de0b92016-05-17 20:19:47 +0000513 // The register may have unrelated uses or defs; create a new register for
514 // just our one def and use so that we can stackify it.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000515 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
516 Def->getOperand(0).setReg(NewReg);
517 Op.setReg(NewReg);
518
519 // Tell LiveIntervals about the new register.
520 LIS.createAndComputeVirtRegInterval(NewReg);
521
522 // Tell LiveIntervals about the changes to the old register.
523 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000524 LI.removeSegment(LIS.getInstructionIndex(*Def).getRegSlot(),
525 LIS.getInstructionIndex(*Op.getParent()).getRegSlot(),
526 /*RemoveDeadValNo=*/true);
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000527
528 MFI.stackifyVReg(NewReg);
Dan Gohman2644d742016-05-17 04:05:31 +0000529
Yury Delendik7c18d602018-09-25 18:59:34 +0000530 UpdateDebugValuesReg(Reg, NewReg, MBB, MRI);
531
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000532 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000533 }
534
Dan Gohmanadf28172016-01-28 01:22:44 +0000535 ImposeStackOrdering(Def);
536 return Def;
537}
538
Yury Delendik7c18d602018-09-25 18:59:34 +0000539static void CloneDebugValues(unsigned Reg, MachineInstr *Insert,
540 unsigned TargetReg, MachineBasicBlock &MBB,
541 MachineRegisterInfo &MRI,
542 const WebAssemblyInstrInfo *TII) {
543 SmallPtrSet<MachineInstr *, 4> Instrs;
544 for (auto &Op : MRI.reg_operands(Reg)) {
545 MachineInstr *MI = Op.getParent();
546 assert(MI != nullptr);
547 if (MI->isDebugValue() && MI->getParent() == &MBB &&
548 Instrs.find(MI) == Instrs.end())
549 Instrs.insert(MI);
550 }
551 for (const auto &MI : Instrs) {
552 MachineInstr &Clone = TII->duplicate(MBB, Insert, *MI);
553 for (unsigned i = 0, e = Clone.getNumOperands(); i != e; ++i) {
554 MachineOperand &MO = Clone.getOperand(i);
555 if (MO.isReg() && MO.getReg() == Reg)
556 MO.setReg(TargetReg);
557 }
558 LLVM_DEBUG(dbgs() << " - - Cloned DBG_VALUE: "; Clone.dump());
559 }
560}
561
Dan Gohmanadf28172016-01-28 01:22:44 +0000562/// A trivially cloneable instruction; clone it and nest the new copy with the
563/// current instruction.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000564static MachineInstr *RematerializeCheapDef(
565 unsigned Reg, MachineOperand &Op, MachineInstr &Def, MachineBasicBlock &MBB,
566 MachineBasicBlock::instr_iterator Insert, LiveIntervals &LIS,
567 WebAssemblyFunctionInfo &MFI, MachineRegisterInfo &MRI,
568 const WebAssemblyInstrInfo *TII, const WebAssemblyRegisterInfo *TRI) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000569 LLVM_DEBUG(dbgs() << "Rematerializing cheap def: "; Def.dump());
570 LLVM_DEBUG(dbgs() << " - for use in "; Op.getParent()->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000571
Dan Gohmanadf28172016-01-28 01:22:44 +0000572 unsigned NewReg = MRI.createVirtualRegister(MRI.getRegClass(Reg));
573 TII->reMaterialize(MBB, Insert, NewReg, 0, Def, *TRI);
574 Op.setReg(NewReg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000575 MachineInstr *Clone = &*std::prev(Insert);
JF Bastien13d3b9b2016-02-27 16:38:23 +0000576 LIS.InsertMachineInstrInMaps(*Clone);
Dan Gohmanadf28172016-01-28 01:22:44 +0000577 LIS.createAndComputeVirtRegInterval(NewReg);
578 MFI.stackifyVReg(NewReg);
579 ImposeStackOrdering(Clone);
580
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000581 LLVM_DEBUG(dbgs() << " - Cloned to "; Clone->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000582
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000583 // Shrink the interval.
584 bool IsDead = MRI.use_empty(Reg);
585 if (!IsDead) {
586 LiveInterval &LI = LIS.getInterval(Reg);
Dan Gohman2644d742016-05-17 04:05:31 +0000587 ShrinkToUses(LI, LIS);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000588 IsDead = !LI.liveAt(LIS.getInstructionIndex(Def).getDeadSlot());
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000589 }
590
Dan Gohmanadf28172016-01-28 01:22:44 +0000591 // If that was the last use of the original, delete the original.
Yury Delendik7c18d602018-09-25 18:59:34 +0000592 // Move or clone corresponding DBG_VALUEs to the 'Insert' location.
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000593 if (IsDead) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000594 LLVM_DEBUG(dbgs() << " - Deleting original\n");
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000595 SlotIndex Idx = LIS.getInstructionIndex(Def).getRegSlot();
Dan Gohmanadf28172016-01-28 01:22:44 +0000596 LIS.removePhysRegDefAt(WebAssembly::ARGUMENTS, Idx);
Dan Gohmanadf28172016-01-28 01:22:44 +0000597 LIS.removeInterval(Reg);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000598 LIS.RemoveMachineInstrFromMaps(Def);
599 Def.eraseFromParent();
Yury Delendik7c18d602018-09-25 18:59:34 +0000600
601 MoveDebugValues(Reg, &*Insert, MBB, MRI);
602 UpdateDebugValuesReg(Reg, NewReg, MBB, MRI);
603 } else {
604 CloneDebugValues(Reg, &*Insert, NewReg, MBB, MRI, TII);
Dan Gohmanadf28172016-01-28 01:22:44 +0000605 }
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000606
Dan Gohmanadf28172016-01-28 01:22:44 +0000607 return Clone;
608}
609
610/// A multiple-use def in the same block with no intervening memory or register
611/// dependencies; move the def down, nest it with the current instruction, and
Dan Gohman4fc4e422016-10-24 19:49:43 +0000612/// insert a tee to satisfy the rest of the uses. As an illustration, rewrite
613/// this:
Dan Gohmanadf28172016-01-28 01:22:44 +0000614///
615/// Reg = INST ... // Def
616/// INST ..., Reg, ... // Insert
617/// INST ..., Reg, ...
618/// INST ..., Reg, ...
619///
620/// to this:
621///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000622/// DefReg = INST ... // Def (to become the new Insert)
Dan Gohman4fc4e422016-10-24 19:49:43 +0000623/// TeeReg, Reg = TEE_... DefReg
Dan Gohmanadf28172016-01-28 01:22:44 +0000624/// INST ..., TeeReg, ... // Insert
Dan Gohman6c8f20d2016-05-23 17:42:57 +0000625/// INST ..., Reg, ...
626/// INST ..., Reg, ...
Dan Gohmanadf28172016-01-28 01:22:44 +0000627///
Dan Gohman8aa237c2016-02-16 15:17:21 +0000628/// with DefReg and TeeReg stackified. This eliminates a get_local from the
Dan Gohmanadf28172016-01-28 01:22:44 +0000629/// resulting code.
630static MachineInstr *MoveAndTeeForMultiUse(
631 unsigned Reg, MachineOperand &Op, MachineInstr *Def, MachineBasicBlock &MBB,
632 MachineInstr *Insert, LiveIntervals &LIS, WebAssemblyFunctionInfo &MFI,
633 MachineRegisterInfo &MRI, const WebAssemblyInstrInfo *TII) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000634 LLVM_DEBUG(dbgs() << "Move and tee for multi-use:"; Def->dump());
Dan Gohman2644d742016-05-17 04:05:31 +0000635
Dan Gohman12de0b92016-05-17 20:19:47 +0000636 // Move Def into place.
Dan Gohmanadf28172016-01-28 01:22:44 +0000637 MBB.splice(Insert, &MBB, Def);
JF Bastien1afd1e22016-02-28 15:33:53 +0000638 LIS.handleMove(*Def);
Dan Gohman12de0b92016-05-17 20:19:47 +0000639
640 // Create the Tee and attach the registers.
Dan Gohmanadf28172016-01-28 01:22:44 +0000641 const auto *RegClass = MRI.getRegClass(Reg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000642 unsigned TeeReg = MRI.createVirtualRegister(RegClass);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000643 unsigned DefReg = MRI.createVirtualRegister(RegClass);
Dan Gohman33e694a2016-05-12 04:19:09 +0000644 MachineOperand &DefMO = Def->getOperand(0);
Dan Gohmanadf28172016-01-28 01:22:44 +0000645 MachineInstr *Tee = BuildMI(MBB, Insert, Insert->getDebugLoc(),
Dan Gohman4fc4e422016-10-24 19:49:43 +0000646 TII->get(GetTeeOpcode(RegClass)), TeeReg)
Dan Gohman12de0b92016-05-17 20:19:47 +0000647 .addReg(Reg, RegState::Define)
Dan Gohman33e694a2016-05-12 04:19:09 +0000648 .addReg(DefReg, getUndefRegState(DefMO.isDead()));
Dan Gohmanadf28172016-01-28 01:22:44 +0000649 Op.setReg(TeeReg);
Dan Gohman33e694a2016-05-12 04:19:09 +0000650 DefMO.setReg(DefReg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000651 SlotIndex TeeIdx = LIS.InsertMachineInstrInMaps(*Tee).getRegSlot();
652 SlotIndex DefIdx = LIS.getInstructionIndex(*Def).getRegSlot();
653
Yury Delendik7c18d602018-09-25 18:59:34 +0000654 MoveDebugValues(Reg, Insert, MBB, MRI);
655
Dan Gohman12de0b92016-05-17 20:19:47 +0000656 // Tell LiveIntervals we moved the original vreg def from Def to Tee.
657 LiveInterval &LI = LIS.getInterval(Reg);
658 LiveInterval::iterator I = LI.FindSegmentContaining(DefIdx);
659 VNInfo *ValNo = LI.getVNInfoAt(DefIdx);
660 I->start = TeeIdx;
661 ValNo->def = TeeIdx;
662 ShrinkToUses(LI, LIS);
663
664 // Finish stackifying the new regs.
Dan Gohmanadf28172016-01-28 01:22:44 +0000665 LIS.createAndComputeVirtRegInterval(TeeReg);
Dan Gohman8aa237c2016-02-16 15:17:21 +0000666 LIS.createAndComputeVirtRegInterval(DefReg);
667 MFI.stackifyVReg(DefReg);
Dan Gohmanadf28172016-01-28 01:22:44 +0000668 MFI.stackifyVReg(TeeReg);
669 ImposeStackOrdering(Def);
670 ImposeStackOrdering(Tee);
Dan Gohman12de0b92016-05-17 20:19:47 +0000671
Yury Delendik7c18d602018-09-25 18:59:34 +0000672 CloneDebugValues(Reg, Tee, DefReg, MBB, MRI, TII);
673 CloneDebugValues(Reg, Insert, TeeReg, MBB, MRI, TII);
674
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000675 LLVM_DEBUG(dbgs() << " - Replaced register: "; Def->dump());
676 LLVM_DEBUG(dbgs() << " - Tee instruction: "; Tee->dump());
Dan Gohmanadf28172016-01-28 01:22:44 +0000677 return Def;
678}
679
680namespace {
681/// A stack for walking the tree of instructions being built, visiting the
682/// MachineOperands in DFS order.
683class TreeWalkerState {
684 typedef MachineInstr::mop_iterator mop_iterator;
685 typedef std::reverse_iterator<mop_iterator> mop_reverse_iterator;
686 typedef iterator_range<mop_reverse_iterator> RangeTy;
687 SmallVector<RangeTy, 4> Worklist;
688
689public:
690 explicit TreeWalkerState(MachineInstr *Insert) {
691 const iterator_range<mop_iterator> &Range = Insert->explicit_uses();
692 if (Range.begin() != Range.end())
693 Worklist.push_back(reverse(Range));
694 }
695
696 bool Done() const { return Worklist.empty(); }
697
698 MachineOperand &Pop() {
699 RangeTy &Range = Worklist.back();
700 MachineOperand &Op = *Range.begin();
701 Range = drop_begin(Range, 1);
702 if (Range.begin() == Range.end())
703 Worklist.pop_back();
704 assert((Worklist.empty() ||
705 Worklist.back().begin() != Worklist.back().end()) &&
706 "Empty ranges shouldn't remain in the worklist");
707 return Op;
708 }
709
710 /// Push Instr's operands onto the stack to be visited.
711 void PushOperands(MachineInstr *Instr) {
712 const iterator_range<mop_iterator> &Range(Instr->explicit_uses());
713 if (Range.begin() != Range.end())
714 Worklist.push_back(reverse(Range));
715 }
716
717 /// Some of Instr's operands are on the top of the stack; remove them and
718 /// re-insert them starting from the beginning (because we've commuted them).
719 void ResetTopOperands(MachineInstr *Instr) {
720 assert(HasRemainingOperands(Instr) &&
721 "Reseting operands should only be done when the instruction has "
722 "an operand still on the stack");
723 Worklist.back() = reverse(Instr->explicit_uses());
724 }
725
726 /// Test whether Instr has operands remaining to be visited at the top of
727 /// the stack.
728 bool HasRemainingOperands(const MachineInstr *Instr) const {
729 if (Worklist.empty())
730 return false;
731 const RangeTy &Range = Worklist.back();
732 return Range.begin() != Range.end() && Range.begin()->getParent() == Instr;
733 }
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000734
735 /// Test whether the given register is present on the stack, indicating an
736 /// operand in the tree that we haven't visited yet. Moving a definition of
737 /// Reg to a point in the tree after that would change its value.
Dan Gohman10545702016-05-17 22:24:18 +0000738 ///
739 /// This is needed as a consequence of using implicit get_locals for
740 /// uses and implicit set_locals for defs.
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000741 bool IsOnStack(unsigned Reg) const {
742 for (const RangeTy &Range : Worklist)
743 for (const MachineOperand &MO : Range)
744 if (MO.isReg() && MO.getReg() == Reg)
745 return true;
746 return false;
747 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000748};
749
750/// State to keep track of whether commuting is in flight or whether it's been
751/// tried for the current instruction and didn't work.
752class CommutingState {
753 /// There are effectively three states: the initial state where we haven't
754 /// started commuting anything and we don't know anything yet, the tenative
755 /// state where we've commuted the operands of the current instruction and are
756 /// revisting it, and the declined state where we've reverted the operands
757 /// back to their original order and will no longer commute it further.
758 bool TentativelyCommuting;
759 bool Declined;
760
761 /// During the tentative state, these hold the operand indices of the commuted
762 /// operands.
763 unsigned Operand0, Operand1;
764
765public:
766 CommutingState() : TentativelyCommuting(false), Declined(false) {}
767
768 /// Stackification for an operand was not successful due to ordering
769 /// constraints. If possible, and if we haven't already tried it and declined
770 /// it, commute Insert's operands and prepare to revisit it.
771 void MaybeCommute(MachineInstr *Insert, TreeWalkerState &TreeWalker,
772 const WebAssemblyInstrInfo *TII) {
773 if (TentativelyCommuting) {
774 assert(!Declined &&
775 "Don't decline commuting until you've finished trying it");
776 // Commuting didn't help. Revert it.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000777 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000778 TentativelyCommuting = false;
779 Declined = true;
780 } else if (!Declined && TreeWalker.HasRemainingOperands(Insert)) {
781 Operand0 = TargetInstrInfo::CommuteAnyOperandIndex;
782 Operand1 = TargetInstrInfo::CommuteAnyOperandIndex;
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000783 if (TII->findCommutedOpIndices(*Insert, Operand0, Operand1)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000784 // Tentatively commute the operands and try again.
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000785 TII->commuteInstruction(*Insert, /*NewMI=*/false, Operand0, Operand1);
Dan Gohmanadf28172016-01-28 01:22:44 +0000786 TreeWalker.ResetTopOperands(Insert);
787 TentativelyCommuting = true;
788 Declined = false;
789 }
790 }
791 }
792
793 /// Stackification for some operand was successful. Reset to the default
794 /// state.
795 void Reset() {
796 TentativelyCommuting = false;
797 Declined = false;
798 }
799};
800} // end anonymous namespace
801
Dan Gohman1462faa2015-11-16 16:18:28 +0000802bool WebAssemblyRegStackify::runOnMachineFunction(MachineFunction &MF) {
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000803 LLVM_DEBUG(dbgs() << "********** Register Stackifying **********\n"
804 "********** Function: "
805 << MF.getName() << '\n');
Dan Gohman1462faa2015-11-16 16:18:28 +0000806
807 bool Changed = false;
808 MachineRegisterInfo &MRI = MF.getRegInfo();
809 WebAssemblyFunctionInfo &MFI = *MF.getInfo<WebAssemblyFunctionInfo>();
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000810 const auto *TII = MF.getSubtarget<WebAssemblySubtarget>().getInstrInfo();
811 const auto *TRI = MF.getSubtarget<WebAssemblySubtarget>().getRegisterInfo();
Dan Gohman81719f82015-11-25 16:55:01 +0000812 AliasAnalysis &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
Dan Gohmanadf28172016-01-28 01:22:44 +0000813 MachineDominatorTree &MDT = getAnalysis<MachineDominatorTree>();
Dan Gohman8887d1f2015-12-25 00:31:02 +0000814 LiveIntervals &LIS = getAnalysis<LiveIntervals>();
Dan Gohmand70e5902015-12-08 03:30:42 +0000815
Dan Gohman1462faa2015-11-16 16:18:28 +0000816 // Walk the instructions from the bottom up. Currently we don't look past
817 // block boundaries, and the blocks aren't ordered so the block visitation
818 // order isn't significant, but we may want to change this in the future.
819 for (MachineBasicBlock &MBB : MF) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000820 // Don't use a range-based for loop, because we modify the list as we're
821 // iterating over it and the end iterator may change.
822 for (auto MII = MBB.rbegin(); MII != MBB.rend(); ++MII) {
823 MachineInstr *Insert = &*MII;
Dan Gohman81719f82015-11-25 16:55:01 +0000824 // Don't nest anything inside an inline asm, because we don't have
825 // constraints for $push inputs.
826 if (Insert->getOpcode() == TargetOpcode::INLINEASM)
Dan Gohman595e8ab2016-02-22 17:45:20 +0000827 continue;
828
829 // Ignore debugging intrinsics.
830 if (Insert->getOpcode() == TargetOpcode::DBG_VALUE)
831 continue;
Dan Gohman81719f82015-11-25 16:55:01 +0000832
Dan Gohman1462faa2015-11-16 16:18:28 +0000833 // Iterate through the inputs in reverse order, since we'll be pulling
Dan Gohman53d13992015-12-02 18:08:49 +0000834 // operands off the stack in LIFO order.
Dan Gohmanadf28172016-01-28 01:22:44 +0000835 CommutingState Commuting;
836 TreeWalkerState TreeWalker(Insert);
837 while (!TreeWalker.Done()) {
838 MachineOperand &Op = TreeWalker.Pop();
839
Dan Gohman1462faa2015-11-16 16:18:28 +0000840 // We're only interested in explicit virtual register operands.
Dan Gohmanadf28172016-01-28 01:22:44 +0000841 if (!Op.isReg())
Dan Gohman1462faa2015-11-16 16:18:28 +0000842 continue;
843
844 unsigned Reg = Op.getReg();
Dan Gohmanadf28172016-01-28 01:22:44 +0000845 assert(Op.isUse() && "explicit_uses() should only iterate over uses");
846 assert(!Op.isImplicit() &&
847 "explicit_uses() should only iterate over explicit operands");
848 if (TargetRegisterInfo::isPhysicalRegister(Reg))
Dan Gohman1462faa2015-11-16 16:18:28 +0000849 continue;
850
Dan Gohmanffc184b2016-10-03 22:32:21 +0000851 // Identify the definition for this register at this point.
Dan Gohman2644d742016-05-17 04:05:31 +0000852 MachineInstr *Def = GetVRegDef(Reg, Insert, MRI, LIS);
853 if (!Def)
854 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000855
Dan Gohman81719f82015-11-25 16:55:01 +0000856 // Don't nest an INLINE_ASM def into anything, because we don't have
857 // constraints for $pop outputs.
858 if (Def->getOpcode() == TargetOpcode::INLINEASM)
859 continue;
860
Dan Gohman4ba48162015-11-18 16:12:01 +0000861 // Argument instructions represent live-in registers and not real
862 // instructions.
Dan Gohman4fc4e422016-10-24 19:49:43 +0000863 if (WebAssembly::isArgument(*Def))
Dan Gohman4ba48162015-11-18 16:12:01 +0000864 continue;
865
Dan Gohmanadf28172016-01-28 01:22:44 +0000866 // Decide which strategy to take. Prefer to move a single-use value
Dan Gohman4fc4e422016-10-24 19:49:43 +0000867 // over cloning it, and prefer cloning over introducing a tee.
Dan Gohmanadf28172016-01-28 01:22:44 +0000868 // For moving, we require the def to be in the same block as the use;
869 // this makes things simpler (LiveIntervals' handleMove function only
870 // supports intra-block moves) and it's MachineSink's job to catch all
871 // the sinking opportunities anyway.
872 bool SameBlock = Def->getParent() == &MBB;
Derek Schuffe9e68912016-09-30 18:02:54 +0000873 bool CanMove = SameBlock && IsSafeToMove(Def, Insert, AA, MRI) &&
Dan Gohmanfbfe5ec2016-01-28 03:59:09 +0000874 !TreeWalker.IsOnStack(Reg);
Dan Gohman12de0b92016-05-17 20:19:47 +0000875 if (CanMove && HasOneUse(Reg, Def, MRI, MDT, LIS)) {
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000876 Insert = MoveForSingleUse(Reg, Op, Def, MBB, Insert, LIS, MFI, MRI);
Duncan P. N. Exon Smith9cfc75c2016-06-30 00:01:54 +0000877 } else if (ShouldRematerialize(*Def, AA, TII)) {
878 Insert =
879 RematerializeCheapDef(Reg, Op, *Def, MBB, Insert->getIterator(),
880 LIS, MFI, MRI, TII, TRI);
Sam Cleggcf2a9e22018-07-16 23:09:29 +0000881 } else if (CanMove &&
Dan Gohman10545702016-05-17 22:24:18 +0000882 OneUseDominatesOtherUses(Reg, Op, MBB, MRI, MDT, LIS, MFI)) {
Dan Gohmanadf28172016-01-28 01:22:44 +0000883 Insert = MoveAndTeeForMultiUse(Reg, Op, Def, MBB, Insert, LIS, MFI,
884 MRI, TII);
885 } else {
886 // We failed to stackify the operand. If the problem was ordering
887 // constraints, Commuting may be able to help.
888 if (!CanMove && SameBlock)
889 Commuting.MaybeCommute(Insert, TreeWalker, TII);
890 // Proceed to the next operand.
891 continue;
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000892 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000893
Dan Gohmane81021a2016-11-08 19:40:38 +0000894 // If the instruction we just stackified is an IMPLICIT_DEF, convert it
895 // to a constant 0 so that the def is explicit, and the push/pop
896 // correspondence is maintained.
897 if (Insert->getOpcode() == TargetOpcode::IMPLICIT_DEF)
898 ConvertImplicitDefToConstZero(Insert, MRI, TII, MF);
899
Dan Gohmanadf28172016-01-28 01:22:44 +0000900 // We stackified an operand. Add the defining instruction's operands to
901 // the worklist stack now to continue to build an ever deeper tree.
902 Commuting.Reset();
903 TreeWalker.PushOperands(Insert);
Dan Gohman1462faa2015-11-16 16:18:28 +0000904 }
Dan Gohmanadf28172016-01-28 01:22:44 +0000905
906 // If we stackified any operands, skip over the tree to start looking for
907 // the next instruction we can build a tree on.
908 if (Insert != &*MII) {
Dan Gohman8f59cf72016-01-06 18:29:35 +0000909 ImposeStackOrdering(&*MII);
Eric Liuc7e5a9c2016-09-12 09:35:59 +0000910 MII = MachineBasicBlock::iterator(Insert).getReverse();
Dan Gohmanadf28172016-01-28 01:22:44 +0000911 Changed = true;
912 }
Dan Gohman1462faa2015-11-16 16:18:28 +0000913 }
914 }
915
Dan Gohmane0405332016-10-03 22:43:53 +0000916 // If we used VALUE_STACK anywhere, add it to the live-in sets everywhere so
Dan Gohmanadf28172016-01-28 01:22:44 +0000917 // that it never looks like a use-before-def.
Dan Gohmanb0992da2015-11-20 02:19:12 +0000918 if (Changed) {
Dan Gohmane0405332016-10-03 22:43:53 +0000919 MF.getRegInfo().addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000920 for (MachineBasicBlock &MBB : MF)
Dan Gohmane0405332016-10-03 22:43:53 +0000921 MBB.addLiveIn(WebAssembly::VALUE_STACK);
Dan Gohmanb0992da2015-11-20 02:19:12 +0000922 }
923
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000924#ifndef NDEBUG
Dan Gohmanb6fd39a2016-01-19 16:59:23 +0000925 // Verify that pushes and pops are performed in LIFO order.
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000926 SmallVector<unsigned, 0> Stack;
927 for (MachineBasicBlock &MBB : MF) {
928 for (MachineInstr &MI : MBB) {
Shiva Chen801bf7e2018-05-09 02:42:00 +0000929 if (MI.isDebugInstr())
Dan Gohman0cfb5f82016-05-10 04:24:02 +0000930 continue;
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000931 for (MachineOperand &MO : reverse(MI.explicit_operands())) {
Dan Gohman7a6b9822015-11-29 22:32:02 +0000932 if (!MO.isReg())
933 continue;
Dan Gohmanadf28172016-01-28 01:22:44 +0000934 unsigned Reg = MO.getReg();
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000935
Dan Gohmanadf28172016-01-28 01:22:44 +0000936 if (MFI.isVRegStackified(Reg)) {
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000937 if (MO.isDef())
Dan Gohmanadf28172016-01-28 01:22:44 +0000938 Stack.push_back(Reg);
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000939 else
Dan Gohmanadf28172016-01-28 01:22:44 +0000940 assert(Stack.pop_back_val() == Reg &&
941 "Register stack pop should be paired with a push");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000942 }
943 }
944 }
945 // TODO: Generalize this code to support keeping values on the stack across
946 // basic block boundaries.
Dan Gohmanadf28172016-01-28 01:22:44 +0000947 assert(Stack.empty() &&
948 "Register stack pushes and pops should be balanced");
Dan Gohman7bafa0e2015-11-20 02:33:24 +0000949 }
950#endif
951
Dan Gohman1462faa2015-11-16 16:18:28 +0000952 return Changed;
953}