LLVM 20.0.0git
MachineStableHash.cpp
Go to the documentation of this file.
1//===- lib/CodeGen/MachineStableHash.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// Stable hashing for MachineInstr and MachineOperand. Useful or getting a
10// hash across runs, modules, etc.
11//
12//===----------------------------------------------------------------------===//
13
15#include "llvm/ADT/APFloat.h"
16#include "llvm/ADT/APInt.h"
17#include "llvm/ADT/STLExtras.h"
20#include "llvm/ADT/Statistic.h"
28#include "llvm/Config/llvm-config.h"
29#include "llvm/IR/Constants.h"
32#include "llvm/MC/MCSymbol.h"
35
36#define DEBUG_TYPE "machine-stable-hash"
37
38using namespace llvm;
39
40STATISTIC(StableHashBailingMachineBasicBlock,
41 "Number of encountered unsupported MachineOperands that were "
42 "MachineBasicBlocks while computing stable hashes");
43STATISTIC(StableHashBailingConstantPoolIndex,
44 "Number of encountered unsupported MachineOperands that were "
45 "ConstantPoolIndex while computing stable hashes");
46STATISTIC(StableHashBailingTargetIndexNoName,
47 "Number of encountered unsupported MachineOperands that were "
48 "TargetIndex with no name");
49STATISTIC(StableHashBailingGlobalAddress,
50 "Number of encountered unsupported MachineOperands that were "
51 "GlobalAddress while computing stable hashes");
52STATISTIC(StableHashBailingBlockAddress,
53 "Number of encountered unsupported MachineOperands that were "
54 "BlockAddress while computing stable hashes");
55STATISTIC(StableHashBailingMetadataUnsupported,
56 "Number of encountered unsupported MachineOperands that were "
57 "Metadata of an unsupported kind while computing stable hashes");
58
60 switch (MO.getType()) {
62 if (MO.getReg().isVirtual()) {
64 SmallVector<stable_hash> DefOpcodes;
65 for (auto &Def : MRI.def_instructions(MO.getReg()))
66 DefOpcodes.push_back(Def.getOpcode());
67 return stable_hash_combine(DefOpcodes);
68 }
69
70 // Register operands don't have target flags.
71 return stable_hash_combine(MO.getType(), MO.getReg(), MO.getSubReg(),
72 MO.isDef());
74 return stable_hash_combine(MO.getType(), MO.getTargetFlags(), MO.getImm());
77 auto Val = MO.isCImm() ? MO.getCImm()->getValue()
79 auto ValHash = stable_hash_combine(
80 ArrayRef<stable_hash>(Val.getRawData(), Val.getNumWords()));
81 return stable_hash_combine(MO.getType(), MO.getTargetFlags(), ValHash);
82 }
83
85 ++StableHashBailingMachineBasicBlock;
86 return 0;
88 ++StableHashBailingConstantPoolIndex;
89 return 0;
91 ++StableHashBailingBlockAddress;
92 return 0;
94 ++StableHashBailingMetadataUnsupported;
95 return 0;
97 const GlobalValue *GV = MO.getGlobal();
98 stable_hash GVHash = 0;
99 if (auto *GVar = dyn_cast<GlobalVariable>(GV))
100 GVHash = StructuralHash(*GVar);
101 if (!GVHash) {
102 if (!GV->hasName()) {
103 ++StableHashBailingGlobalAddress;
104 return 0;
105 }
106 GVHash = stable_hash_name(GV->getName());
107 }
108
109 return stable_hash_combine(MO.getType(), MO.getTargetFlags(), GVHash,
110 MO.getOffset());
111 }
112
114 if (const char *Name = MO.getTargetIndexName())
117 ++StableHashBailingTargetIndexNoName;
118 return 0;
119 }
120
124 MO.getIndex());
125
128 MO.getOffset(),
130
133 if (const MachineInstr *MI = MO.getParent()) {
134 if (const MachineBasicBlock *MBB = MI->getParent()) {
135 if (const MachineFunction *MF = MBB->getParent()) {
136 const TargetRegisterInfo *TRI = MF->getSubtarget().getRegisterInfo();
137 unsigned RegMaskSize =
138 MachineOperand::getRegMaskSize(TRI->getNumRegs());
139 const uint32_t *RegMask = MO.getRegMask();
140 std::vector<llvm::stable_hash> RegMaskHashes(RegMask,
141 RegMask + RegMaskSize);
143 stable_hash_combine(RegMaskHashes));
144 }
145 }
146 }
147
148 assert(0 && "MachineOperand not associated with any MachineFunction");
149 return stable_hash_combine(MO.getType(), MO.getTargetFlags());
150 }
151
153 std::vector<llvm::stable_hash> ShuffleMaskHashes;
154
156 MO.getShuffleMask(), std::back_inserter(ShuffleMaskHashes),
157 [](int S) -> llvm::stable_hash { return llvm::stable_hash(S); });
158
160 stable_hash_combine(ShuffleMaskHashes));
161 }
163 auto SymbolName = MO.getMCSymbol()->getName();
165 stable_hash_name(SymbolName));
166 }
169 MO.getCFIIndex());
172 MO.getIntrinsicID());
175 MO.getPredicate());
178 MO.getInstrRefOpIndex());
179 }
180 llvm_unreachable("Invalid machine operand type");
181}
182
183/// A stable hash value for machine instructions.
184/// Returns 0 if no stable hash could be computed.
185/// The hashing and equality testing functions ignore definitions so this is
186/// useful for CSE, etc.
188 bool HashConstantPoolIndices,
189 bool HashMemOperands) {
190 // Build up a buffer of hash code components.
191 SmallVector<stable_hash, 16> HashComponents;
192 HashComponents.reserve(MI.getNumOperands() + MI.getNumMemOperands() + 2);
193 HashComponents.push_back(MI.getOpcode());
194 HashComponents.push_back(MI.getFlags());
195 for (const MachineOperand &MO : MI.operands()) {
196 if (!HashVRegs && MO.isReg() && MO.isDef() && MO.getReg().isVirtual())
197 continue; // Skip virtual register defs.
198
199 if (MO.isCPI()) {
200 HashComponents.push_back(stable_hash_combine(
201 MO.getType(), MO.getTargetFlags(), MO.getIndex()));
202 continue;
203 }
204
205 stable_hash StableHash = stableHashValue(MO);
206 if (!StableHash)
207 return 0;
208 HashComponents.push_back(StableHash);
209 }
210
211 for (const auto *Op : MI.memoperands()) {
212 if (!HashMemOperands)
213 break;
214 HashComponents.push_back(static_cast<unsigned>(Op->getSize().getValue()));
215 HashComponents.push_back(static_cast<unsigned>(Op->getFlags()));
216 HashComponents.push_back(static_cast<unsigned>(Op->getOffset()));
217 HashComponents.push_back(static_cast<unsigned>(Op->getSuccessOrdering()));
218 HashComponents.push_back(static_cast<unsigned>(Op->getAddrSpace()));
219 HashComponents.push_back(static_cast<unsigned>(Op->getSyncScopeID()));
220 HashComponents.push_back(static_cast<unsigned>(Op->getBaseAlign().value()));
221 HashComponents.push_back(static_cast<unsigned>(Op->getFailureOrdering()));
222 }
223
224 return stable_hash_combine(HashComponents);
225}
226
228 SmallVector<stable_hash> HashComponents;
229 // TODO: Hash more stuff like block alignment and branch probabilities.
230 for (const auto &MI : MBB)
231 HashComponents.push_back(stableHashValue(MI));
232 return stable_hash_combine(HashComponents);
233}
234
236 SmallVector<stable_hash> HashComponents;
237 // TODO: Hash lots more stuff like function alignment and stack objects.
238 for (const auto &MBB : MF)
239 HashComponents.push_back(stableHashValue(MBB));
240 return stable_hash_combine(HashComponents);
241}
unsigned const MachineRegisterInfo * MRI
This file declares a class to represent arbitrary precision floating point values and provide a varie...
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock & MBB
This file contains the declarations for the subclasses of Constant, which represent the different fla...
std::string Name
IRTranslator LLVM IR MI
unsigned const TargetRegisterInfo * TRI
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
Definition: Statistic.h:166
APInt bitcastToAPInt() const
Definition: APFloat.h:1346
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
const APFloat & getValueAPF() const
Definition: Constants.h:314
const APInt & getValue() const
Return the constant as an APInt value reference.
Definition: Constants.h:148
This class represents an Operation in the Expression.
StringRef getName() const
getName - Get the symbol name.
Definition: MCSymbol.h:205
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Representation of each machine instruction.
Definition: MachineInstr.h:69
const MachineFunction * getMF() const
Return the function that contains the basic block that this instruction belongs to.
MachineOperand class - Representation of each machine instruction operand.
unsigned getSubReg() const
unsigned getInstrRefOpIndex() const
const GlobalValue * getGlobal() const
const ConstantInt * getCImm() const
const char * getTargetIndexName() const
getTargetIndexName - If this MachineOperand is a TargetIndex that has a name, attempt to get the name...
bool isCImm() const
isCImm - Test if this is a MO_CImmediate operand.
int64_t getImm() const
unsigned getInstrRefInstrIndex() const
ArrayRef< int > getShuffleMask() const
unsigned getCFIIndex() const
MachineInstr * getParent()
getParent - Return the instruction that this operand belongs to.
static unsigned getRegMaskSize(unsigned NumRegs)
Returns number of elements needed for a regmask array.
unsigned getTargetFlags() const
MachineOperandType getType() const
getType - Returns the MachineOperandType for this operand.
const char * getSymbolName() const
Register getReg() const
getReg - Returns the register number.
Intrinsic::ID getIntrinsicID() const
const uint32_t * getRegMask() const
getRegMask - Returns a bit mask of registers preserved by this RegMask operand.
const ConstantFP * getFPImm() const
unsigned getPredicate() const
MCSymbol * getMCSymbol() const
@ MO_CFIIndex
MCCFIInstruction index.
@ MO_Immediate
Immediate operand.
@ MO_ConstantPoolIndex
Address of indexed Constant in Constant Pool.
@ MO_MCSymbol
MCSymbol reference (for debug/eh info)
@ MO_Predicate
Generic predicate for ISel.
@ MO_GlobalAddress
Address of a global value.
@ MO_RegisterMask
Mask of preserved registers.
@ MO_ShuffleMask
Other IR Constant for ISel (shuffle masks)
@ MO_CImmediate
Immediate >64bit operand.
@ MO_BlockAddress
Address of a basic block.
@ MO_DbgInstrRef
Integer indices referring to an instruction+operand.
@ MO_MachineBasicBlock
MachineBasicBlock reference.
@ MO_FrameIndex
Abstract Stack Frame Index.
@ MO_Register
Register operand.
@ MO_ExternalSymbol
Name of external global symbol.
@ MO_IntrinsicID
Intrinsic ID for ISel.
@ MO_JumpTableIndex
Address of indexed Jump Table for switch.
@ MO_TargetIndex
Target-dependent index+offset operand.
@ MO_Metadata
Metadata reference (for debug info)
@ MO_FPImmediate
Floating-point immediate operand.
@ MO_RegisterLiveOut
Mask of live-out registers.
int64_t getOffset() const
Return the offset from the symbol in this operand.
MachineRegisterInfo - Keep track of information for virtual and physical registers,...
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:91
void reserve(size_type N)
Definition: SmallVector.h:663
void push_back(const T &Elt)
Definition: SmallVector.h:413
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
bool hasName() const
Definition: Value.h:261
StringRef getName() const
Return a constant reference to the value's name.
Definition: Value.cpp:309
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
OutputIt transform(R &&Range, OutputIt d_first, UnaryFunction F)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere.
Definition: STLExtras.h:1952
stable_hash stableHashValue(const MachineOperand &MO)
stable_hash stable_hash_name(StringRef Name)
Definition: StableHashing.h:72
stable_hash stable_hash_combine(ArrayRef< stable_hash > Buffer)
Definition: StableHashing.h:30
stable_hash StructuralHash(const Function &F, bool DetailedHash=false)
Returns a hash of the function F.