LLVM 23.0.0git
WebAssemblyMemIntrinsicResults.cpp
Go to the documentation of this file.
1//== WebAssemblyMemIntrinsicResults.cpp - Optimize memory intrinsic results ==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8///
9/// \file
10/// This file implements an optimization pass using memory intrinsic results.
11///
12/// Calls to memory intrinsics (memcpy, memmove, memset) return the destination
13/// address. They are in the form of
14/// %dst_new = call @memcpy %dst, %src, %len
15/// where %dst and %dst_new registers contain the same value.
16///
17/// This is to enable an optimization wherein uses of the %dst register used in
18/// the parameter can be replaced by uses of the %dst_new register used in the
19/// result, making the %dst register more likely to be single-use, thus more
20/// likely to be useful to register stackifying, and potentially also exposing
21/// the call instruction itself to register stackifying. These both can reduce
22/// local.get/local.set traffic.
23///
24/// The LLVM intrinsics for these return void so they can't use the returned
25/// attribute and consequently aren't handled by the OptimizeReturned pass.
26///
27//===----------------------------------------------------------------------===//
28
30#include "WebAssembly.h"
38#include "llvm/CodeGen/Passes.h"
39#include "llvm/Support/Debug.h"
41using namespace llvm;
42
43#define DEBUG_TYPE "wasm-mem-intrinsic-results"
44
45namespace {
46class WebAssemblyMemIntrinsicResults final : public MachineFunctionPass {
47public:
48 static char ID; // Pass identification, replacement for typeid
49 WebAssemblyMemIntrinsicResults() : MachineFunctionPass(ID) {}
50
51 StringRef getPassName() const override {
52 return "WebAssembly Memory Intrinsic Results";
53 }
54
55 void getAnalysisUsage(AnalysisUsage &AU) const override {
56 AU.setPreservesCFG();
67 }
68
69 bool runOnMachineFunction(MachineFunction &MF) override;
70
71private:
73 LiveIntervals *LIS;
74 const TargetLibraryInfo *LibInfo;
75
76 StringRef MemcpyName, MemmoveName, MemsetName;
77
78 bool optimizeCall(MachineBasicBlock &MBB, MachineInstr &MI,
79 const MachineRegisterInfo &MRI) const;
80};
81} // end anonymous namespace
82
83char WebAssemblyMemIntrinsicResults::ID = 0;
84INITIALIZE_PASS(WebAssemblyMemIntrinsicResults, DEBUG_TYPE,
85 "Optimize memory intrinsic result values for WebAssembly",
86 false, false)
87
89 return new WebAssemblyMemIntrinsicResults();
90}
91
92// Replace uses of FromReg with ToReg if they are dominated by MI.
94 unsigned FromReg, unsigned ToReg,
97 LiveIntervals &LIS) {
98 bool Changed = false;
99
100 LiveInterval *FromLI = &LIS.getInterval(FromReg);
101 LiveInterval *ToLI = &LIS.getInterval(ToReg);
102
104 VNInfo *FromVNI = FromLI->getVNInfoAt(FromIdx);
105
107
108 for (MachineOperand &O :
109 llvm::make_early_inc_range(MRI.use_nodbg_operands(FromReg))) {
110 MachineInstr *Where = O.getParent();
111
112 // Check that MI dominates the instruction in the normal way.
113 if (&MI == Where || !MDT.dominates(&MI, Where))
114 continue;
115
116 // If this use gets a different value, skip it.
117 SlotIndex WhereIdx = LIS.getInstructionIndex(*Where);
118 VNInfo *WhereVNI = FromLI->getVNInfoAt(WhereIdx);
119 if (WhereVNI && WhereVNI != FromVNI)
120 continue;
121
122 // Make sure ToReg isn't clobbered before it gets there.
123 VNInfo *ToVNI = ToLI->getVNInfoAt(WhereIdx);
124 if (ToVNI && ToVNI != FromVNI)
125 continue;
126
127 Changed = true;
128 LLVM_DEBUG(dbgs() << "Setting operand " << O << " in " << *Where << " from "
129 << MI << "\n");
130 O.setReg(ToReg);
131
132 // If the store's def was previously dead, it is no longer.
133 if (!O.isUndef()) {
134 MI.getOperand(0).setIsDead(false);
135
136 Indices.push_back(WhereIdx.getRegSlot());
137 }
138 }
139
140 if (Changed) {
141 // Extend ToReg's liveness.
142 LIS.extendToIndices(*ToLI, Indices);
143
144 // Shrink FromReg's liveness.
145 LIS.shrinkToUses(FromLI);
146
147 // If we replaced all dominated uses, FromReg is now killed at MI.
148 if (!FromLI->liveAt(FromIdx.getDeadSlot()))
149 MI.addRegisterKilled(FromReg, MBB.getParent()
150 ->getSubtarget<WebAssemblySubtarget>()
151 .getRegisterInfo());
152 }
153
154 return Changed;
155}
156
157bool WebAssemblyMemIntrinsicResults::optimizeCall(
159 const MachineRegisterInfo &MRI) const {
160 MachineOperand &Op1 = MI.getOperand(1);
161 if (!Op1.isSymbol())
162 return false;
163
164 StringRef Name(Op1.getSymbolName());
165
166 // TODO: Could generalize by parsing to LibcallImpl and checking signature
167 // attributes
168 bool CallReturnsInput =
169 Name == MemcpyName || Name == MemmoveName || Name == MemsetName;
170 if (!CallReturnsInput)
171 return false;
172
173 LibFunc Func;
174 if (!LibInfo->getLibFunc(Name, Func))
175 return false;
176
177 Register FromReg = MI.getOperand(2).getReg();
178 Register ToReg = MI.getOperand(0).getReg();
179 if (MRI.getRegClass(FromReg) != MRI.getRegClass(ToReg))
180 report_fatal_error("Memory Intrinsic results: call to builtin function "
181 "with wrong signature, from/to mismatch");
182 return replaceDominatedUses(MBB, MI, FromReg, ToReg, MRI, *MDT, *LIS);
183}
184
185bool WebAssemblyMemIntrinsicResults::runOnMachineFunction(MachineFunction &MF) {
186 LLVM_DEBUG({
187 dbgs() << "********** Memory Intrinsic Results **********\n"
188 << "********** Function: " << MF.getName() << '\n';
189 });
190
191 MachineRegisterInfo &MRI = MF.getRegInfo();
192 LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
193 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
194 const WebAssemblySubtarget &Subtarget =
195 MF.getSubtarget<WebAssemblySubtarget>();
196 LibInfo =
197 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(MF.getFunction());
198 const LibcallLoweringInfo &Libcalls =
199 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
200 *MF.getFunction().getParent(), Subtarget);
201
203 Libcalls.getLibcallImpl(RTLIB::MEMCPY));
205 Libcalls.getLibcallImpl(RTLIB::MEMMOVE));
207 Libcalls.getLibcallImpl(RTLIB::MEMSET));
208
209 bool Changed = false;
210
211 // We don't preserve SSA form.
212 MRI.leaveSSA();
213
214 assert(MRI.tracksLiveness() &&
215 "MemIntrinsicResults expects liveness tracking");
216
217 for (auto &MBB : MF) {
218 LLVM_DEBUG(dbgs() << "Basic Block: " << MBB.getName() << '\n');
219 for (auto &MI : MBB)
220 switch (MI.getOpcode()) {
221 default:
222 break;
223 case WebAssembly::CALL:
224 Changed |= optimizeCall(MBB, MI, MRI);
225 break;
226 }
227 }
228
229 return Changed;
230}
unsigned const MachineRegisterInfo * MRI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
MachineBasicBlock & MBB
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Promote Memory to Register
Definition Mem2Reg.cpp:110
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:114
This file provides WebAssembly-specific target descriptions.
This file declares WebAssembly-specific per-machine-function information.
static bool replaceDominatedUses(MachineBasicBlock &MBB, MachineInstr &MI, unsigned FromReg, unsigned ToReg, const MachineRegisterInfo &MRI, MachineDominatorTree &MDT, LiveIntervals &LIS)
This file declares the WebAssembly-specific subclass of TargetSubtarget.
This file contains the entry points for global functions defined in the LLVM WebAssembly back-end.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
LLVM_ABI void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition Pass.cpp:270
FunctionPass class - This class is used to implement most global optimizations.
Definition Pass.h:314
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI RTLIB::LibcallImpl getLibcallImpl(RTLIB::Libcall Call) const
Return the lowering's selection of implementation call for Call.
LiveInterval - This class represents the liveness of a register, or stack slot.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
LiveInterval & getInterval(Register Reg)
LLVM_ABI bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr * > *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses.
LLVM_ABI void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
bool liveAt(SlotIndex index) const
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
LLVM_ABI StringRef getName() const
Return the name of the corresponding LLVM basic block, or an empty string.
Analysis pass which computes a MachineDominatorTree.
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
bool dominates(const MachineInstr *A, const MachineInstr *B) const
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
bool isSymbol() const
isSymbol - Tests if this is a MO_ExternalSymbol operand.
const char * getSymbolName() const
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
SlotIndex - An opaque wrapper around machine indexes.
Definition SlotIndexes.h:66
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
StringRef - Represent a constant reference to a string, i.e.
Definition StringRef.h:55
Provides information about what library functions are available for the current target.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
VNInfo - Value Number Information.
const WebAssemblyRegisterInfo * getRegisterInfo() const override
Changed
unsigned ID
LLVM IR allows to use arbitrary numbers as calling convention identifiers.
Definition CallingConv.h:24
NodeAddr< FuncNode * > Func
Definition RDFGraph.h:393
This is an optimization pass for GlobalISel generic memory operations.
Definition Types.h:26
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
Definition STLExtras.h:632
FunctionPass * createWebAssemblyMemIntrinsicResults()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:207
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.