LLVM 24.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"
42#include "llvm/CodeGen/Passes.h"
44#include "llvm/IR/Analysis.h"
45#include "llvm/Support/Debug.h"
47using namespace llvm;
48
49#define DEBUG_TYPE "wasm-mem-intrinsic-results"
50
51namespace {
52class WebAssemblyMemIntrinsicResultsImpl {
53public:
54 WebAssemblyMemIntrinsicResultsImpl(MachineDominatorTree *MDT,
55 LiveIntervals *LIS,
56 const TargetLibraryInfo *LibInfo,
57 const LibcallLoweringInfo &LibCalls)
58 : MDT(MDT), LIS(LIS), LibInfo(LibInfo), LibCalls(LibCalls) {}
59 bool runOnMachineFunction(MachineFunction &MF);
60
61private:
63 LiveIntervals *LIS;
64 const TargetLibraryInfo *LibInfo;
65 const LibcallLoweringInfo &LibCalls;
66
67 StringRef MemcpyName, MemmoveName, MemsetName;
68
69 bool optimizeCall(MachineBasicBlock &MBB, MachineInstr &MI,
70 const MachineRegisterInfo &MRI) const;
71};
72
73class WebAssemblyMemIntrinsicResultsLegacy final : public MachineFunctionPass {
74public:
75 static char ID; // Pass identification, replacement for typeid
76 WebAssemblyMemIntrinsicResultsLegacy() : MachineFunctionPass(ID) {}
77
78 StringRef getPassName() const override {
79 return "WebAssembly Memory Intrinsic Results";
80 }
81
82 void getAnalysisUsage(AnalysisUsage &AU) const override {
83 AU.setPreservesCFG();
94 }
95
96 bool runOnMachineFunction(MachineFunction &MF) override;
97};
98} // end anonymous namespace
99
100char WebAssemblyMemIntrinsicResultsLegacy::ID = 0;
101INITIALIZE_PASS(WebAssemblyMemIntrinsicResultsLegacy, DEBUG_TYPE,
102 "Optimize memory intrinsic result values for WebAssembly",
103 false, false)
104
106 return new WebAssemblyMemIntrinsicResultsLegacy();
107}
108
109// Replace uses of FromReg with ToReg if they are dominated by MI.
111 unsigned FromReg, unsigned ToReg,
112 const MachineRegisterInfo &MRI,
114 LiveIntervals &LIS) {
115 bool Changed = false;
116
117 LiveInterval *FromLI = &LIS.getInterval(FromReg);
118 LiveInterval *ToLI = &LIS.getInterval(ToReg);
119
121 VNInfo *FromVNI = FromLI->getVNInfoAt(FromIdx);
122
124
125 for (MachineOperand &O :
127 MachineInstr *Where = O.getParent();
128
129 // Check that MI dominates the instruction in the normal way.
130 if (&MI == Where || !MDT.dominates(&MI, Where))
131 continue;
132
133 // If this use gets a different value, skip it.
134 SlotIndex WhereIdx = LIS.getInstructionIndex(*Where);
135 VNInfo *WhereVNI = FromLI->getVNInfoAt(WhereIdx);
136 if (WhereVNI && WhereVNI != FromVNI)
137 continue;
138
139 // Make sure ToReg isn't clobbered before it gets there.
140 VNInfo *ToVNI = ToLI->getVNInfoAt(WhereIdx);
141 if (ToVNI && ToVNI != FromVNI)
142 continue;
143
144 Changed = true;
145 LLVM_DEBUG(dbgs() << "Setting operand " << O << " in " << *Where << " from "
146 << MI << "\n");
147 O.setReg(ToReg);
148
149 // If the store's def was previously dead, it is no longer.
150 if (!O.isUndef()) {
151 MI.getOperand(0).setIsDead(false);
152
153 Indices.push_back(WhereIdx.getRegSlot());
154 }
155 }
156
157 if (Changed) {
158 // Extend ToReg's liveness.
159 LIS.extendToIndices(*ToLI, Indices);
160
161 // Shrink FromReg's liveness.
162 LIS.shrinkToUses(FromLI);
163
164 // If we replaced all dominated uses, FromReg is now killed at MI.
165 if (!FromLI->liveAt(FromIdx.getDeadSlot()))
166 MI.addRegisterKilled(FromReg, MBB.getParent()
167 ->getSubtarget<WebAssemblySubtarget>()
168 .getRegisterInfo());
169 }
170
171 return Changed;
172}
173
174bool WebAssemblyMemIntrinsicResultsImpl::optimizeCall(
176 const MachineRegisterInfo &MRI) const {
177 MachineOperand &Op1 = MI.getOperand(1);
178 if (!Op1.isSymbol())
179 return false;
180
181 StringRef Name(Op1.getSymbolName());
182
183 // TODO: Could generalize by parsing to LibcallImpl and checking signature
184 // attributes
185 bool CallReturnsInput =
186 Name == MemcpyName || Name == MemmoveName || Name == MemsetName;
187 if (!CallReturnsInput)
188 return false;
189
190 LibFunc Func;
191 if (!LibInfo->getLibFunc(Name, Func))
192 return false;
193
194 Register FromReg = MI.getOperand(2).getReg();
195 Register ToReg = MI.getOperand(0).getReg();
196 if (MRI.getRegClass(FromReg) != MRI.getRegClass(ToReg))
197 report_fatal_error("Memory Intrinsic results: call to builtin function "
198 "with wrong signature, from/to mismatch");
199 return replaceDominatedUses(MBB, MI, FromReg, ToReg, MRI, *MDT, *LIS);
200}
201
202bool WebAssemblyMemIntrinsicResultsImpl::runOnMachineFunction(
203 MachineFunction &MF) {
204 LLVM_DEBUG({
205 dbgs() << "********** Memory Intrinsic Results **********\n"
206 << "********** Function: " << MF.getName() << '\n';
207 });
208
209 MachineRegisterInfo &MRI = MF.getRegInfo();
210
212 LibCalls.getLibcallImpl(RTLIB::MEMCPY));
214 LibCalls.getLibcallImpl(RTLIB::MEMMOVE));
216 LibCalls.getLibcallImpl(RTLIB::MEMSET));
217
218 bool Changed = false;
219
220 // We don't preserve SSA form.
221 MRI.leaveSSA();
222
223 assert(MRI.tracksLiveness() &&
224 "MemIntrinsicResults expects liveness tracking");
225
226 for (auto &MBB : MF) {
227 LLVM_DEBUG(dbgs() << "Basic Block: " << MBB.getName() << '\n');
228 for (auto &MI : MBB)
229 switch (MI.getOpcode()) {
230 default:
231 break;
232 case WebAssembly::CALL:
233 Changed |= optimizeCall(MBB, MI, MRI);
234 break;
235 }
236 }
237
238 return Changed;
239}
240
241bool WebAssemblyMemIntrinsicResultsLegacy::runOnMachineFunction(
242 MachineFunction &MF) {
243 MachineDominatorTree *MDT =
244 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
245 LiveIntervals *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
246 const TargetLibraryInfo *LibInfo =
247 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(MF.getFunction());
248 const WebAssemblySubtarget &Subtarget =
249 MF.getSubtarget<WebAssemblySubtarget>();
250 const LibcallLoweringInfo &LibCalls =
251 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
252 *MF.getFunction().getParent(), Subtarget);
253 WebAssemblyMemIntrinsicResultsImpl Impl(MDT, LIS, LibInfo, LibCalls);
254 return Impl.runOnMachineFunction(MF);
255}
256
257PreservedAnalyses
262 const TargetLibraryInfo *LibInfo =
264 .getManager()
265 .getResult<TargetLibraryAnalysis>(MF.getFunction());
266 const WebAssemblySubtarget &Subtarget =
268 const LibcallLoweringInfo &LibCalls =
270 .getCachedResult<LibcallLoweringModuleAnalysis>(
271 *MF.getFunction().getParent())
272 ->getLibcallLowering(Subtarget);
273 WebAssemblyMemIntrinsicResultsImpl Impl(MDT, LIS, LibInfo, LibCalls);
274 bool Changed = Impl.runOnMachineFunction(MF);
275 if (!Changed)
276 return PreservedAnalyses::all();
279 .preserve<LiveIntervalsAnalysis>()
280 .preserve<SlotIndexesAnalysis>();
281}
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:119
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.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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:275
Represents analyses that only rely on functions' control flow.
Definition Analysis.h:73
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...
Tracks which library functions to use for a particular subtarget.
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.
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,...
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
iterator_range< use_nodbg_iterator > use_nodbg_operands(Register Reg) const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
Definition Analysis.h:118
PreservedAnalyses & preserveSet()
Mark an analysis set as preserved.
Definition Analysis.h:151
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.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Analysis pass providing the TargetLibraryInfo.
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.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const WebAssemblyRegisterInfo * getRegisterInfo() const override
Changed
Pass manager infrastructure for declaring and invalidating analyses.
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.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
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:633
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
Definition Error.cpp:163
FunctionPass * createWebAssemblyMemIntrinsicResultsLegacyPass()
static StringRef getLibcallImplName(RTLIB::LibcallImpl CallImpl)
Get the libcall routine name for the specified libcall implementation.