LLVM 24.0.0git
CSEInfo.cpp
Go to the documentation of this file.
1//===- CSEInfo.cpp ------------------------------===//
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//
10//===----------------------------------------------------------------------===//
14#include "llvm/Support/Error.h"
15
16#define DEBUG_TYPE "cseinfo"
17
18using namespace llvm;
23 "Analysis containing CSE Info", false, true)
24
25/// -------- UniqueMachineInstr -------------//
26
28 GISelInstProfileBuilder(ID, MI->getMF()->getRegInfo()).addNodeID(MI);
29}
30/// -----------------------------------------
31
32/// --------- CSEConfigFull ---------- ///
34 switch (Opc) {
35 default:
36 break;
37 case TargetOpcode::G_ADD:
38 case TargetOpcode::G_AND:
39 case TargetOpcode::G_ASHR:
40 case TargetOpcode::G_LSHR:
41 case TargetOpcode::G_MUL:
42 case TargetOpcode::G_OR:
43 case TargetOpcode::G_SHL:
44 case TargetOpcode::G_SUB:
45 case TargetOpcode::G_XOR:
46 case TargetOpcode::G_UDIV:
47 case TargetOpcode::G_SDIV:
48 case TargetOpcode::G_UREM:
49 case TargetOpcode::G_SREM:
50 case TargetOpcode::G_CONSTANT:
51 case TargetOpcode::G_FCONSTANT:
52 case TargetOpcode::G_IMPLICIT_DEF:
53 case TargetOpcode::G_ZEXT:
54 case TargetOpcode::G_SEXT:
55 case TargetOpcode::G_ANYEXT:
56 case TargetOpcode::G_UNMERGE_VALUES:
57 case TargetOpcode::G_TRUNC:
58 case TargetOpcode::G_PTR_ADD:
59 case TargetOpcode::G_EXTRACT:
60 case TargetOpcode::G_SELECT:
61 case TargetOpcode::G_BUILD_VECTOR:
62 case TargetOpcode::G_BUILD_VECTOR_TRUNC:
63 case TargetOpcode::G_SEXT_INREG:
64 case TargetOpcode::G_FADD:
65 case TargetOpcode::G_FSUB:
66 case TargetOpcode::G_FMUL:
67 case TargetOpcode::G_FDIV:
68 case TargetOpcode::G_FABS:
69 // TODO: support G_FNEG.
70 case TargetOpcode::G_FMAXNUM:
71 case TargetOpcode::G_FMINNUM:
72 case TargetOpcode::G_FMAXNUM_IEEE:
73 case TargetOpcode::G_FMINNUM_IEEE:
74 return true;
75 }
76 return false;
77}
78
80 return Opc == TargetOpcode::G_CONSTANT || Opc == TargetOpcode::G_FCONSTANT ||
81 Opc == TargetOpcode::G_IMPLICIT_DEF;
82}
83
84std::unique_ptr<CSEConfigBase>
86 std::unique_ptr<CSEConfigBase> Config;
87 if (Level == CodeGenOptLevel::None)
88 Config = std::make_unique<CSEConfigConstantOnly>();
89 else
90 Config = std::make_unique<CSEConfigFull>();
91 return Config;
92}
93
94/// -----------------------------------------
95
96/// -------- GISelCSEInfo -------------//
97void GISelCSEInfo::setMF(MachineFunction &MF) { this->MRI = &MF.getRegInfo(); }
98
100
101bool GISelCSEInfo::isUniqueMachineInstValid(
102 const UniqueMachineInstr &UMI) const {
103 // Should we check here and assert that the instruction has been fully
104 // constructed?
105 // FIXME: Any other checks required to be done here? Remove this method if
106 // none.
107 return true;
108}
109
110void GISelCSEInfo::invalidateUniqueMachineInstr(UniqueMachineInstr *UMI) {
111 bool Removed = CSEMap.erase(UMI);
112 (void)Removed;
113 assert(Removed && "Invalidation called on invalid UMI");
114 // FIXME: Should UMI be deallocated/destroyed?
115}
116
118GISelCSEInfo::getNodeIfExists(FoldingSetNodeID &ID, MachineBasicBlock *MBB,
119 FoldingSetInsertToken &Token) {
120 auto *Node = CSEMap.lookup(ID, Token);
121 if (Node) {
122 if (!isUniqueMachineInstValid(*Node)) {
123 invalidateUniqueMachineInstr(Node);
124 return nullptr;
125 }
126
127 if (Node->MI->getParent() != MBB)
128 return nullptr;
129 }
130 return Node;
131}
132
133void GISelCSEInfo::insertNode(UniqueMachineInstr *UMI,
134 FoldingSetInsertToken Token) {
136 assert(UMI);
137 UniqueMachineInstr *MaybeNewNode = UMI;
138 if (Token)
139 CSEMap.insert(UMI, Token);
140 else
141 MaybeNewNode = CSEMap.getOrInsert(UMI);
142 if (MaybeNewNode != UMI) {
143 // A similar node exists in the folding set. Let's ignore this one.
144 return;
145 }
146 assert(InstrMapping.count(UMI->MI) == 0 &&
147 "This instruction should not be in the map");
148 InstrMapping[UMI->MI] = MaybeNewNode;
149}
150
151UniqueMachineInstr *GISelCSEInfo::getUniqueInstrForMI(const MachineInstr *MI) {
152 assert(shouldCSE(MI->getOpcode()) && "Trying to CSE an unsupported Node");
153 auto *Node = new (UniqueInstrAllocator) UniqueMachineInstr(MI);
154 return Node;
155}
156
157void GISelCSEInfo::insertInstr(MachineInstr *MI, FoldingSetInsertToken Token) {
158 assert(MI);
159 // If it exists in temporary insts, remove it.
160 TemporaryInsts.remove(MI);
161 auto *Node = getUniqueInstrForMI(MI);
162 insertNode(Node, Token);
163}
164
166GISelCSEInfo::getMachineInstrIfExists(FoldingSetNodeID &ID,
168 FoldingSetInsertToken &Token) {
170 if (auto *Inst = getNodeIfExists(ID, MBB, Token)) {
171 LLVM_DEBUG(dbgs() << "CSEInfo::Found Instr " << *Inst->MI);
172 return const_cast<MachineInstr *>(Inst->MI);
173 }
174 return nullptr;
175}
176
178#ifndef NDEBUG
179 ++OpcodeHitTable[Opc];
180#endif
181 // Else do nothing.
182}
183
185 if (shouldCSE(MI->getOpcode())) {
186 TemporaryInsts.insert(MI);
187 LLVM_DEBUG(dbgs() << "CSEInfo::Recording new MI " << *MI);
188 }
189}
190
192 assert(shouldCSE(MI->getOpcode()) && "Invalid instruction for CSE");
193 auto *UMI = InstrMapping.lookup(MI);
194 LLVM_DEBUG(dbgs() << "CSEInfo::Handling recorded MI " << *MI);
195 if (UMI) {
196 // Invalidate this MI.
197 invalidateUniqueMachineInstr(UMI);
198 InstrMapping.erase(MI);
199 }
200 /// Now insert the new instruction.
201 if (UMI) {
202 /// We'll reuse the same UniqueMachineInstr to avoid the new
203 /// allocation.
204 *UMI = UniqueMachineInstr(MI);
205 insertNode(UMI);
206 } else {
207 /// This is a new instruction. Allocate a new UniqueMachineInstr and
208 /// Insert.
209 insertInstr(MI);
210 }
211}
212
214 if (auto *UMI = InstrMapping.lookup(MI)) {
215 invalidateUniqueMachineInstr(UMI);
216 InstrMapping.erase(MI);
217 }
218 TemporaryInsts.remove(MI);
219}
220
222 if (HandlingRecordedInstrs)
223 return;
224 HandlingRecordedInstrs = true;
225 while (!TemporaryInsts.empty()) {
226 auto *MI = TemporaryInsts.pop_back_val();
228 }
229 HandlingRecordedInstrs = false;
230}
231
232bool GISelCSEInfo::shouldCSE(unsigned Opc) const {
233 assert(CSEOpt.get() && "CSEConfig not set");
234 return CSEOpt->shouldCSEOpc(Opc);
235}
236
240 // For now, perform erase, followed by insert.
243}
245
247 setMF(MF);
248 for (auto &MBB : MF) {
249 for (MachineInstr &MI : MBB) {
250 if (!shouldCSE(MI.getOpcode()))
251 continue;
252 LLVM_DEBUG(dbgs() << "CSEInfo::Add MI: " << MI);
253 insertInstr(&MI);
254 }
255 }
256}
257
259 print();
260 CSEMap.clear();
261 InstrMapping.clear();
262 UniqueInstrAllocator.Reset();
263 TemporaryInsts.clear();
264 CSEOpt.reset();
265 MRI = nullptr;
266#ifndef NDEBUG
267 OpcodeHitTable.clear();
268#endif
269}
270
271#ifndef NDEBUG
272static const char *stringify(const MachineInstr *MI, std::string &S) {
273 raw_string_ostream OS(S);
274 OS << *MI;
275 return OS.str().c_str();
276}
277#endif
278
280#ifndef NDEBUG
281 std::string S1, S2;
283 // For each instruction in map from MI -> UMI,
284 // Profile(MI) and make sure UMI is found for that profile.
285 for (auto &It : InstrMapping) {
286 FoldingSetNodeID TmpID;
287 GISelInstProfileBuilder(TmpID, *MRI).addNodeID(It.first);
289 UniqueMachineInstr *FoundNode = CSEMap.lookup(TmpID, Token);
290 if (FoundNode != It.second)
291 return createStringError(std::errc::not_supported,
292 "CSEMap mismatch, InstrMapping has MIs without "
293 "corresponding Nodes in CSEMap:\n%s",
294 stringify(It.second->MI, S1));
295 }
296
297 // For every node in the CSEMap, make sure that the InstrMapping
298 // points to it.
299 for (const UniqueMachineInstr &UMI : CSEMap) {
300 if (!InstrMapping.count(UMI.MI))
301 return createStringError(std::errc::not_supported,
302 "Node in CSE without InstrMapping:\n%s",
303 stringify(UMI.MI, S1));
304
305 if (InstrMapping[UMI.MI] != &UMI)
306 return createStringError(std::make_error_code(std::errc::not_supported),
307 "Mismatch in CSE mapping:\n%s\n%s",
308 stringify(InstrMapping[UMI.MI]->MI, S1),
309 stringify(UMI.MI, S2));
310 }
311#endif
312 return Error::success();
313}
314
316 LLVM_DEBUG({
317 for (auto &It : OpcodeHitTable)
318 dbgs() << "CSEInfo::CSE Hit for Opc " << It.first << " : " << It.second
319 << "\n";
320 });
321}
322/// -----------------------------------------
323// ---- Profiling methods for FoldingSetNode --- //
326 addNodeIDMBB(MI->getParent());
327 addNodeIDOpcode(MI->getOpcode());
328 for (const auto &Op : MI->operands())
330 addNodeIDFlag(MI->getFlags());
331 return *this;
332}
333
336 ID.AddInteger(Opc);
337 return *this;
338}
339
342 uint64_t Val = Ty.getUniqueRAWLLTData();
343 ID.AddInteger(Val);
344 return *this;
345}
346
349 ID.AddPointer(RC);
350 return *this;
351}
352
355 ID.AddPointer(RB);
356 return *this;
357}
358
360 MachineRegisterInfo::VRegAttrs Attrs) const {
361 addNodeIDRegType(Attrs.Ty);
362
363 const RegClassOrRegBank &RCOrRB = Attrs.RCOrRB;
364 if (RCOrRB) {
365 if (const auto *RB = dyn_cast_if_present<const RegisterBank *>(RCOrRB))
367 else
369 }
370 return *this;
371}
372
375 ID.AddInteger(Imm);
376 return *this;
377}
378
381 ID.AddInteger(Reg.id());
382 return *this;
383}
384
390
393 ID.AddPointer(MBB);
394 return *this;
395}
396
399 if (Flag)
400 ID.AddInteger(Flag);
401 return *this;
402}
403
406 addNodeIDRegType(MRI.getVRegAttrs(Reg));
407 return *this;
408}
409
411 const MachineOperand &MO) const {
412 if (MO.isReg()) {
413 Register Reg = MO.getReg();
414 if (!MO.isDef())
415 addNodeIDRegNum(Reg);
416
417 // Profile the register properties.
418 addNodeIDReg(Reg);
419 assert(!MO.isImplicit() && "Unhandled case");
420 } else if (MO.isImm())
421 ID.AddInteger(MO.getImm());
422 else if (MO.isCImm())
423 ID.AddPointer(MO.getCImm());
424 else if (MO.isFPImm())
425 ID.AddPointer(MO.getFPImm());
426 else if (MO.isPredicate())
427 ID.AddInteger(MO.getPredicate());
428 else
429 llvm_unreachable("Unhandled operand type");
430 // Handle other types
431 return *this;
432}
433
435GISelCSEAnalysisWrapper::get(std::unique_ptr<CSEConfigBase> CSEOpt) {
436 if (!AlreadyComputed) {
437 Info.releaseMemory();
438 Info.setCSEConfig(std::move(CSEOpt));
439 Info.analyze(*MF);
440 AlreadyComputed = true;
441 }
442 return Info;
443}
444
445AnalysisKey GISelCSEAnalysis::Key;
446
450 std::unique_ptr<GISelCSEInfo> Info = std::make_unique<GISelCSEInfo>();
451 if (CSEConfigBase *Config = TM->createCSEConfig())
452 Info->setCSEConfig(std::unique_ptr<CSEConfigBase>(Config));
453 else
454 Info->setCSEConfig(getStandardCSEConfigForOpt(TM->getOptLevel()));
455 Info->analyze(MF);
456 return Info;
457}
458
463
466 Wrapper.setMF(MF);
467 return false;
468}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t Imm
constexpr LLT S1
MachineBasicBlock & MBB
static const char * stringify(const MachineInstr *MI, std::string &S)
Definition CSEInfo.cpp:272
Provides analysis for continuously CSEing during GISel passes.
#define DEBUG_TYPE
IRTranslator LLVM IR MI
Load MIR Sample Profile
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
Definition PassSupport.h:56
#define LLVM_DEBUG(...)
Definition Debug.h:119
Represent the analysis usage information of a pass.
void setPreservesAll()
Set by analyses that do not transform their input at all.
bool shouldCSEOpc(unsigned Opc) override
Definition CSEInfo.cpp:79
bool shouldCSEOpc(unsigned Opc) override
------— CSEConfigFull -------— ///
Definition CSEInfo.cpp:33
Lightweight error class with error context and mandatory checking.
Definition Error.h:159
static ErrorSuccess success()
Create a success value.
Definition Error.h:336
Insertion token: a failed lookup fills it in, the matching insert consumes it.
Definition FoldingSet.h:284
This class is used to gather all the unique data bits of a node.
Definition FoldingSet.h:162
The actual analysis pass wrapper.
Definition CSEInfo.h:243
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
Definition CSEInfo.h:257
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Definition CSEInfo.cpp:459
bool runOnMachineFunction(MachineFunction &MF) override
runOnMachineFunction - This method must be overloaded to perform the desired machine code transformat...
Definition CSEInfo.cpp:464
LLVM_ABI GISelCSEInfo & get(std::unique_ptr< CSEConfigBase > CSEOpt)
Takes a CSEConfigBase object that defines what opcodes get CSEd.
Definition CSEInfo.cpp:435
LLVM_ABI Result run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
Definition CSEInfo.cpp:448
std::unique_ptr< GISelCSEInfo > Result
Definition CSEInfo.h:235
The CSE Analysis object.
Definition CSEInfo.h:72
bool shouldCSE(unsigned Opc) const
Definition CSEInfo.cpp:232
~GISelCSEInfo() override
void changingInstr(MachineInstr &MI) override
This instruction is about to be mutated in some way.
Definition CSEInfo.cpp:239
void analyze(MachineFunction &MF)
Definition CSEInfo.cpp:246
void changedInstr(MachineInstr &MI) override
This instruction was mutated in some way.
Definition CSEInfo.cpp:244
void recordNewInstruction(MachineInstr *MI)
Records a newly created inst in a list and lazily insert it to the CSEMap.
Definition CSEInfo.cpp:184
void setMF(MachineFunction &MF)
-----— GISelCSEInfo ----------—//
Definition CSEInfo.cpp:97
void erasingInstr(MachineInstr &MI) override
An instruction is about to be erased.
Definition CSEInfo.cpp:237
void countOpcodeHit(unsigned Opc)
Definition CSEInfo.cpp:177
void handleRecordedInsts()
Use this callback to insert all the recorded instructions.
Definition CSEInfo.cpp:221
void handleRecordedInst(MachineInstr *MI)
Use this callback to inform CSE about a newly fully created instruction.
Definition CSEInfo.cpp:191
void handleRemoveInst(MachineInstr *MI)
Remove this inst from the CSE map.
Definition CSEInfo.cpp:213
void createdInstr(MachineInstr &MI) override
An instruction has been created and inserted into the function.
Definition CSEInfo.cpp:238
LLVM_ABI const GISelInstProfileBuilder & addNodeIDOpcode(unsigned Opc) const
Definition CSEInfo.cpp:335
LLVM_ABI const GISelInstProfileBuilder & addNodeIDRegNum(Register Reg) const
Definition CSEInfo.cpp:380
LLVM_ABI const GISelInstProfileBuilder & addNodeIDFlag(unsigned Flag) const
Definition CSEInfo.cpp:398
LLVM_ABI const GISelInstProfileBuilder & addNodeIDImmediate(int64_t Imm) const
Definition CSEInfo.cpp:374
LLVM_ABI const GISelInstProfileBuilder & addNodeIDReg(Register Reg) const
Definition CSEInfo.cpp:405
LLVM_ABI const GISelInstProfileBuilder & addNodeID(const MachineInstr *MI) const
Definition CSEInfo.cpp:325
LLVM_ABI const GISelInstProfileBuilder & addNodeIDMBB(const MachineBasicBlock *MBB) const
Definition CSEInfo.cpp:392
GISelInstProfileBuilder(FoldingSetNodeID &ID, const MachineRegisterInfo &MRI)
Definition CSEInfo.h:178
LLVM_ABI const GISelInstProfileBuilder & addNodeIDRegType(const LLT Ty) const
Definition CSEInfo.cpp:341
LLVM_ABI const GISelInstProfileBuilder & addNodeIDMachineOperand(const MachineOperand &MO) const
Definition CSEInfo.cpp:410
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
MachineOperand class - Representation of each machine instruction operand.
const ConstantInt * getCImm() const
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
int64_t getImm() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
Register getReg() const
getReg - Returns the register number.
const ConstantFP * getFPImm() const
unsigned getPredicate() const
static MachineOperand CreateReg(Register Reg, bool isDef, bool isImp=false, bool isKill=false, bool isDead=false, bool isUndef=false, bool isEarlyClobber=false, unsigned SubReg=0, bool isDebug=false, bool isInternalRead=false, bool isRenamable=false)
bool isFPImm() const
isFPImm - Tests if this is a MO_FPImmediate operand.
This class implements the register bank concept.
Wrapper class representing virtual and physical registers.
Definition Register.h:20
A class that wraps MachineInstrs and derives from FoldingSetNode in order to be uniqued in a CSEMap.
Definition CSEInfo.h:32
A raw_ostream that writes to an std::string.
std::string & str()
Returns the string's reference.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
NodeAddr< NodeBase * > Node
Definition RDFGraph.h:381
This is an optimization pass for GlobalISel generic memory operations.
PointerUnion< const TargetRegisterClass *, const RegisterBank * > RegClassOrRegBank
Convenient type to represent either a register class or a register bank.
auto dyn_cast_if_present(const Y &Val)
dyn_cast_if_present<X> - Functionally identical to dyn_cast, except that a null (or none in the case ...
Definition Casting.h:732
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition Error.h:1321
LLVM_ABI std::unique_ptr< CSEConfigBase > getStandardCSEConfigForOpt(CodeGenOptLevel Level)
Definition CSEInfo.cpp:85
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition Debug.cpp:209
CodeGenOptLevel
Code generation optimization level.
Definition CodeGen.h:280
DWARFExpression::Operation Op
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
MCRegisterClass TargetRegisterClass
Definition FastISel.h:58
A special type used by analysis passes to provide an address that identifies that particular analysis...
Definition Analysis.h:29
All attributes(register class or bank and low-level type) a virtual register can have.