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.
106static bool replaceDominatedUses(MachineInstr &MI, unsigned FromReg,
107 unsigned ToReg, const MachineRegisterInfo &MRI,
109 LiveIntervals &LIS) {
110 bool Changed = false;
111
112 LiveInterval *FromLI = &LIS.getInterval(FromReg);
113 LiveInterval *ToLI = &LIS.getInterval(ToReg);
114
116 VNInfo *FromVNI = FromLI->getVNInfoAt(FromIdx);
117
119
120 for (MachineOperand &O :
122 MachineInstr *Where = O.getParent();
123
124 // Check that MI dominates the instruction in the normal way.
125 if (&MI == Where || !MDT.dominates(&MI, Where))
126 continue;
127
128 // If this use gets a different value, skip it.
129 SlotIndex WhereIdx = LIS.getInstructionIndex(*Where);
130 VNInfo *WhereVNI = FromLI->getVNInfoAt(WhereIdx);
131 if (WhereVNI && WhereVNI != FromVNI)
132 continue;
133
134 // Make sure ToReg isn't clobbered before it gets there.
135 VNInfo *ToVNI = ToLI->getVNInfoAt(WhereIdx);
136 if (ToVNI && ToVNI != FromVNI)
137 continue;
138
139 Changed = true;
140 LLVM_DEBUG(dbgs() << "Setting operand " << O << " in " << *Where << " from "
141 << MI << "\n");
142 O.setReg(ToReg);
143
144 // If the store's def was previously dead, it is no longer.
145 if (!O.isUndef()) {
146 MI.getOperand(0).setIsDead(false);
147
148 Indices.push_back(WhereIdx.getRegSlot());
149 }
150 }
151
152 if (Changed) {
153 // Extend ToReg's liveness.
154 LIS.extendToIndices(*ToLI, Indices);
155
156 // Shrink FromReg's liveness.
157 LIS.shrinkToUses(FromLI);
158 }
159
160 return Changed;
161}
162
163bool WebAssemblyMemIntrinsicResultsImpl::optimizeCall(
165 const MachineRegisterInfo &MRI) const {
166 MachineOperand &Op1 = MI.getOperand(1);
167 if (!Op1.isSymbol())
168 return false;
169
170 StringRef Name(Op1.getSymbolName());
171
172 // TODO: Could generalize by parsing to LibcallImpl and checking signature
173 // attributes
174 bool CallReturnsInput =
175 Name == MemcpyName || Name == MemmoveName || Name == MemsetName;
176 if (!CallReturnsInput)
177 return false;
178
179 if (LibInfo->getLibFunc(Name) == NotLibFunc)
180 return false;
181
182 Register FromReg = MI.getOperand(2).getReg();
183 Register ToReg = MI.getOperand(0).getReg();
184 if (MRI.getRegClass(FromReg) != MRI.getRegClass(ToReg))
185 report_fatal_error("Memory Intrinsic results: call to builtin function "
186 "with wrong signature, from/to mismatch");
187 return replaceDominatedUses(MI, FromReg, ToReg, MRI, *MDT, *LIS);
188}
189
190bool WebAssemblyMemIntrinsicResultsImpl::runOnMachineFunction(
191 MachineFunction &MF) {
192 LLVM_DEBUG({
193 dbgs() << "********** Memory Intrinsic Results **********\n"
194 << "********** Function: " << MF.getName() << '\n';
195 });
196
197 MachineRegisterInfo &MRI = MF.getRegInfo();
198
200 LibCalls.getLibcallImpl(RTLIB::MEMCPY));
202 LibCalls.getLibcallImpl(RTLIB::MEMMOVE));
204 LibCalls.getLibcallImpl(RTLIB::MEMSET));
205
206 bool Changed = false;
207
208 // We don't preserve SSA form.
209 MRI.leaveSSA();
210
211 assert(MRI.tracksLiveness() &&
212 "MemIntrinsicResults expects liveness tracking");
213
214 for (auto &MBB : MF) {
215 LLVM_DEBUG(dbgs() << "Basic Block: " << MBB.getName() << '\n');
216 for (auto &MI : MBB)
217 switch (MI.getOpcode()) {
218 default:
219 break;
220 case WebAssembly::CALL:
221 Changed |= optimizeCall(MBB, MI, MRI);
222 break;
223 }
224 }
225
226 return Changed;
227}
228
229bool WebAssemblyMemIntrinsicResultsLegacy::runOnMachineFunction(
230 MachineFunction &MF) {
231 MachineDominatorTree *MDT =
232 &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree();
233 LiveIntervals *LIS = &getAnalysis<LiveIntervalsWrapperPass>().getLIS();
234 const TargetLibraryInfo *LibInfo =
235 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(MF.getFunction());
236 const WebAssemblySubtarget &Subtarget =
237 MF.getSubtarget<WebAssemblySubtarget>();
238 const LibcallLoweringInfo &LibCalls =
239 getAnalysis<LibcallLoweringInfoWrapper>().getLibcallLowering(
240 *MF.getFunction().getParent(), Subtarget);
241 WebAssemblyMemIntrinsicResultsImpl Impl(MDT, LIS, LibInfo, LibCalls);
242 return Impl.runOnMachineFunction(MF);
243}
244
245PreservedAnalyses
250 const TargetLibraryInfo *LibInfo =
252 .getManager()
253 .getResult<TargetLibraryAnalysis>(MF.getFunction());
254 const WebAssemblySubtarget &Subtarget =
256 const LibcallLoweringInfo &LibCalls = getLibcallLowering(
258 .getCachedResult<LibcallLoweringModuleAnalysis>(
259 *MF.getFunction().getParent()),
260 Subtarget);
261 WebAssemblyMemIntrinsicResultsImpl Impl(MDT, LIS, LibInfo, LibCalls);
262 bool Changed = Impl.runOnMachineFunction(MF);
263 if (!Changed)
264 return PreservedAnalyses::all();
267 .preserve<LiveIntervalsAnalysis>()
268 .preserve<SlotIndexesAnalysis>();
269}
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(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:280
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:312
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.
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:70
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)
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:649
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.