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"
41#include "llvm/CodeGen/Passes.h"
43#include "llvm/IR/Analysis.h"
44#include "llvm/Support/Debug.h"
46using namespace llvm;
47
48#define DEBUG_TYPE "wasm-mem-intrinsic-results"
49
50namespace {
51class WebAssemblyMemIntrinsicResultsImpl {
52public:
53 WebAssemblyMemIntrinsicResultsImpl(MachineDominatorTree *MDT,
54 LiveIntervals *LIS,
55 const TargetLibraryInfo *LibInfo,
56 const LibcallLoweringInfo &LibCalls)
57 : MDT(MDT), LIS(LIS), LibInfo(LibInfo), LibCalls(LibCalls) {}
58 bool runOnMachineFunction(MachineFunction &MF);
59
60private:
62 LiveIntervals *LIS;
63 const TargetLibraryInfo *LibInfo;
64 const LibcallLoweringInfo &LibCalls;
65
66 StringRef MemcpyName, MemmoveName, MemsetName;
67
68 bool optimizeCall(MachineBasicBlock &MBB, MachineInstr &MI,
69 const MachineRegisterInfo &MRI) const;
70};
71
72class WebAssemblyMemIntrinsicResultsLegacy final : public MachineFunctionPass {
73public:
74 static char ID; // Pass identification, replacement for typeid
75 WebAssemblyMemIntrinsicResultsLegacy() : MachineFunctionPass(ID) {}
76
77 StringRef getPassName() const override {
78 return "WebAssembly Memory Intrinsic Results";
79 }
80
81 void getAnalysisUsage(AnalysisUsage &AU) const override {
82 AU.setPreservesCFG();
90 }
91
92 bool runOnMachineFunction(MachineFunction &MF) override;
93};
94} // end anonymous namespace
95
96char WebAssemblyMemIntrinsicResultsLegacy::ID = 0;
97INITIALIZE_PASS(WebAssemblyMemIntrinsicResultsLegacy, DEBUG_TYPE,
98 "Optimize memory intrinsic result values for WebAssembly",
99 false, false)
100
102 return new WebAssemblyMemIntrinsicResultsLegacy();
103}
104
105// Replace uses of FromReg with ToReg if they are dominated by MI.
107 unsigned FromReg, unsigned ToReg,
108 const MachineRegisterInfo &MRI,
110 LiveIntervals &LIS) {
111 bool Changed = false;
112
113 LiveInterval *FromLI = &LIS.getInterval(FromReg);
114 LiveInterval *ToLI = &LIS.getInterval(ToReg);
115
117 VNInfo *FromVNI = FromLI->getVNInfoAt(FromIdx);
118
120
121 for (MachineOperand &O :
123 MachineInstr *Where = O.getParent();
124
125 // Check that MI dominates the instruction in the normal way.
126 if (&MI == Where || !MDT.dominates(&MI, Where))
127 continue;
128
129 // If this use gets a different value, skip it.
130 SlotIndex WhereIdx = LIS.getInstructionIndex(*Where);
131 VNInfo *WhereVNI = FromLI->getVNInfoAt(WhereIdx);
132 if (WhereVNI && WhereVNI != FromVNI)
133 continue;
134
135 // Make sure ToReg isn't clobbered before it gets there.
136 VNInfo *ToVNI = ToLI->getVNInfoAt(WhereIdx);
137 if (ToVNI && ToVNI != FromVNI)
138 continue;
139
140 Changed = true;
141 LLVM_DEBUG(dbgs() << "Setting operand " << O << " in " << *Where << " from "
142 << MI << "\n");
143 O.setReg(ToReg);
144
145 // If the store's def was previously dead, it is no longer.
146 if (!O.isUndef()) {
147 MI.getOperand(0).setIsDead(false);
148
149 Indices.push_back(WhereIdx.getRegSlot());
150 }
151 }
152
153 if (Changed) {
154 // Extend ToReg's liveness.
155 LIS.extendToIndices(*ToLI, Indices);
156
157 // Shrink FromReg's liveness.
158 LIS.shrinkToUses(FromLI);
159
160 // If we replaced all dominated uses, FromReg is now killed at MI.
161 if (!FromLI->liveAt(FromIdx.getDeadSlot()))
162 MI.addRegisterKilled(FromReg, MBB.getParent()
163 ->getSubtarget<WebAssemblySubtarget>()
164 .getRegisterInfo());
165 }
166
167 return Changed;
168}
169
170bool WebAssemblyMemIntrinsicResultsImpl::optimizeCall(
172 const MachineRegisterInfo &MRI) const {
173 MachineOperand &Op1 = MI.getOperand(1);
174 if (!Op1.isSymbol())
175 return false;
176
177 StringRef Name(Op1.getSymbolName());
178
179 // TODO: Could generalize by parsing to LibcallImpl and checking signature
180 // attributes
181 bool CallReturnsInput =
182 Name == MemcpyName || Name == MemmoveName || Name == MemsetName;
183 if (!CallReturnsInput)
184 return false;
185
186 if (LibInfo->getLibFunc(Name) == NotLibFunc)
187 return false;
188
189 Register FromReg = MI.getOperand(2).getReg();
190 Register ToReg = MI.getOperand(0).getReg();
191 if (MRI.getRegClass(FromReg) != MRI.getRegClass(ToReg))
192 report_fatal_error("Memory Intrinsic results: call to builtin function "
193 "with wrong signature, from/to mismatch");
194 return replaceDominatedUses(MBB, MI, FromReg, ToReg, MRI, *MDT, *LIS);
195}
196
197bool WebAssemblyMemIntrinsicResultsImpl::runOnMachineFunction(
198 MachineFunction &MF) {
199 LLVM_DEBUG({
200 dbgs() << "********** Memory Intrinsic Results **********\n"
201 << "********** Function: " << MF.getName() << '\n';
202 });
203
204 MachineRegisterInfo &MRI = MF.getRegInfo();
205
207 LibCalls.getLibcallImpl(RTLIB::MEMCPY));
209 LibCalls.getLibcallImpl(RTLIB::MEMMOVE));
211 LibCalls.getLibcallImpl(RTLIB::MEMSET));
212
213 bool Changed = false;
214
215 // We don't preserve SSA form.
216 MRI.leaveSSA();
217
218 assert(MRI.tracksLiveness() &&
219 "MemIntrinsicResults expects liveness tracking");
220
221 for (auto &MBB : MF) {
222 LLVM_DEBUG(dbgs() << "Basic Block: " << MBB.getName() << '\n');
223 for (auto &MI : MBB)
224 switch (MI.getOpcode()) {
225 default:
226 break;
227 case WebAssembly::CALL:
228 Changed |= optimizeCall(MBB, MI, MRI);
229 break;
230 }
231 }
232
233 return Changed;
234}
235
236bool WebAssemblyMemIntrinsicResultsLegacy::runOnMachineFunction(
237 MachineFunction &MF) {
238 MachineDominatorTree *MDT =
239 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
240 LiveIntervals *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
241 const TargetLibraryInfo *LibInfo =
242 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(MF.getFunction());
243 const WebAssemblySubtarget &Subtarget =
244 MF.getSubtarget<WebAssemblySubtarget>();
245 const LibcallLoweringInfo &LibCalls =
246 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
247 *MF.getFunction().getParent(), Subtarget);
248 WebAssemblyMemIntrinsicResultsImpl Impl(MDT, LIS, LibInfo, LibCalls);
249 return Impl.runOnMachineFunction(MF);
250}
251
252PreservedAnalyses
257 const TargetLibraryInfo *LibInfo =
259 .getManager()
260 .getResult<TargetLibraryAnalysis>(MF.getFunction());
261 const WebAssemblySubtarget &Subtarget =
263 const LibcallLoweringInfo &LibCalls = getLibcallLowering(
265 .getCachedResult<LibcallLoweringModuleAnalysis>(
266 *MF.getFunction().getParent()),
267 Subtarget);
268 WebAssemblyMemIntrinsicResultsImpl Impl(MDT, LIS, LibInfo, LibCalls);
269 bool Changed = Impl.runOnMachineFunction(MF);
270 if (!Changed)
271 return PreservedAnalyses::all();
274 .preserve<LiveIntervalsAnalysis>()
275 .preserve<SlotIndexesAnalysis>();
276}
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.
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:278
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 or function.
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.
LibFunc getLibFunc(StringRef funcName) 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.
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 const LibcallLoweringInfo & getLibcallLowering(const ModuleLibcallLoweringInfo &ModuleInfo, const TargetSubtargetInfo &Subtarget)
Resolve the LibcallLoweringInfo for Subtarget from the module-level ModuleInfo, applying the subtarge...
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.