LLVM 24.0.0git
ValueMapper.h
Go to the documentation of this file.
1//===- ValueMapper.h - Remapping for constants and metadata -----*- C++ -*-===//
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// This file defines the MapValue interface which is used by various parts of
10// the Transforms/Utils library to implement cloning and linking facilities.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
15#define LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
16
17#include "llvm/ADT/ArrayRef.h"
20#include "llvm/IR/ValueHandle.h"
21#include "llvm/IR/ValueMap.h"
23
24namespace llvm {
25
26class Constant;
27class DbgRecord;
28class Function;
29class GlobalVariable;
30class Instruction;
31class MDNode;
32class Metadata;
33class Module;
34class Type;
35class Value;
36
40using MetadataPredicate = std::function<bool(const Metadata *)>;
41
42/// This is a class that can be implemented by clients to remap types when
43/// cloning constants and instructions.
45 virtual void anchor(); // Out of line method.
46
47public:
48 virtual ~ValueMapTypeRemapper() = default;
49
50 /// The client should implement this method if they want to remap types while
51 /// mapping values.
52 virtual Type *remapType(Type *SrcTy) = 0;
53};
54
55/// This is a class that can be implemented by clients to materialize Values on
56/// demand.
58 virtual void anchor(); // Out of line method.
59
60protected:
61 ValueMaterializer() = default;
64 ~ValueMaterializer() = default;
65
66public:
67 /// This method can be implemented to generate a mapped Value on demand. For
68 /// example, if linking lazily. Returns null if the value is not materialized.
69 virtual Value *materialize(Value *V) = 0;
70};
71
72/// These are flags that the value mapping APIs allow.
75
76 /// If this flag is set, the remapper knows that only local values within a
77 /// function (such as an instruction or argument) are mapped, not global
78 /// values like functions and global metadata.
80
81 /// If this flag is set, the remapper ignores missing function-local entries
82 /// (Argument, Instruction, BasicBlock) that are not in the value map. If it
83 /// is unset, it aborts if an operand is asked to be remapped which doesn't
84 /// exist in the mapping.
85 ///
86 /// There are no such assertions in MapValue(), whose results are almost
87 /// unchanged by this flag. This flag mainly changes the assertion behaviour
88 /// in RemapInstruction().
89 ///
90 /// Since an Instruction's metadata operands (even that point to SSA values)
91 /// aren't guaranteed to be dominated by their definitions, MapMetadata will
92 /// return "!{}" instead of "null" for \a LocalAsMetadata instances whose SSA
93 /// values are unmapped when this flag is set. Otherwise, \a MapValue()
94 /// completely ignores this flag.
95 ///
96 /// \a MapMetadata() always ignores this flag.
98
99 /// Instruct the remapper to reuse and mutate distinct metadata (remapping
100 /// them in place) instead of cloning remapped copies. This flag has no
101 /// effect when RF_NoModuleLevelChanges, since that implies an identity
102 /// mapping.
104
105 /// Any global values not in value map are mapped to null instead of mapping
106 /// to self. Illegal if RF_IgnoreMissingLocals is also set.
108
109 /// Do not remap source location atoms. Only safe if to do this if the cloned
110 /// instructions being remapped are inserted into a new function, or an
111 /// existing function where the inlined-at fields are updated. If in doubt,
112 /// don't use this flag. It's used when remapping is known to be un-necessary
113 /// to save some compile-time.
115
116 /// Indicate that we are importing functions, specifically in the context of
117 /// ThinLTO. There is some ad-hoc behavior required in this mode.
119};
120
122 return RemapFlags(unsigned(LHS) | unsigned(RHS));
123}
124
125/// Context for (re-)mapping values (and metadata).
126///
127/// A shared context used for mapping and remapping of Value and Metadata
128/// instances using \a ValueToValueMapTy, \a RemapFlags, \a
129/// ValueMapTypeRemapper, \a ValueMaterializer, and \a IdentityMD.
130///
131/// There are a number of top-level entry points:
132/// - \a mapValue() (and \a mapConstant());
133/// - \a mapMetadata() (and \a mapMDNode());
134/// - \a remapInstruction();
135/// - \a remapFunction(); and
136/// - \a remapGlobalObjectMetadata().
137///
138/// The \a ValueMaterializer can be used as a callback, but cannot invoke any
139/// of these top-level functions recursively. Instead, callbacks should use
140/// one of the following to schedule work lazily in the \a ValueMapper
141/// instance:
142/// - \a scheduleMapGlobalInitializer()
143/// - \a scheduleMapAppendingVariable()
144/// - \a scheduleMapGlobalAlias()
145/// - \a scheduleMapGlobalIFunc()
146/// - \a scheduleRemapFunction()
147///
148/// Sometimes a callback needs a different mapping context. Such a context can
149/// be registered using \a registerAlternateMappingContext(), which takes an
150/// alternate \a ValueToValueMapTy and \a ValueMaterializer and returns a ID to
151/// pass into the schedule*() functions.
152///
153/// If an \a IdentityMD predicate is optionally provided, \a Metadata for which
154/// the predicate returns true will be mapped onto itself in \a VM on first use.
155///
156/// TODO: lib/Linker really doesn't need the \a ValueHandle in the \a
157/// ValueToValueMapTy. We should template \a ValueMapper (and its
158/// implementation classes), and explicitly instantiate on two concrete
159/// instances of \a ValueMap (one as \a ValueToValueMap, and one with raw \a
160/// Value pointers). It may be viable to do away with \a TrackingMDRef in the
161/// \a Metadata side map for the lib/Linker case as well, in which case we'll
162/// need a new template parameter on \a ValueMap.
163///
164/// TODO: Update callers of \a RemapInstruction() and \a MapValue() (etc.) to
165/// use \a ValueMapper directly.
167 void *pImpl;
168
169public:
171 ValueMapTypeRemapper *TypeMapper = nullptr,
172 ValueMaterializer *Materializer = nullptr,
173 const MetadataPredicate *IdentityMD = nullptr);
175 ValueMapper(const ValueMapper &) = delete;
179
180 /// Register an alternate mapping context.
181 ///
182 /// Returns a MappingContextID that can be used with the various schedule*()
183 /// API to switch in a different value map on-the-fly.
184 LLVM_ABI unsigned
186 ValueMaterializer *Materializer = nullptr);
187
188 /// Add to the current \a RemapFlags.
189 ///
190 /// \note Like the top-level mapping functions, \a addFlags() must be called
191 /// at the top level, not during a callback in a \a ValueMaterializer.
192 LLVM_ABI void addFlags(RemapFlags Flags);
193
196
197 LLVM_ABI Value *mapValue(const Value &V);
199
206
208 unsigned MappingContextID = 0);
210 GlobalVariable *OldGV,
211 bool IsOldCtorDtor,
212 ArrayRef<Constant *> NewMembers,
213 unsigned MappingContextID = 0);
215 unsigned MappingContextID = 0);
217 unsigned MappingContextID = 0);
219 unsigned MappingContextID = 0);
220};
221
222/// Look up or compute a value in the value map.
223///
224/// Return a mapped value for a function-local value (Argument, Instruction,
225/// BasicBlock), or compute and memoize a value for a Constant.
226///
227/// 1. If \c V is in VM, return the result.
228/// 2. Else if \c V can be materialized with \c Materializer, do so, memoize
229/// it in \c VM, and return it.
230/// 3. Else if \c V is a function-local value, return nullptr.
231/// 4. Else if \c V is a \a GlobalValue, return \c nullptr or \c V depending
232/// on \a RF_NullMapMissingGlobalValues.
233/// 5. Else if \c V is a \a MetadataAsValue wrapping a LocalAsMetadata,
234/// recurse on the local SSA value, and return nullptr or "metadata !{}" on
235/// missing depending on RF_IgnoreMissingValues.
236/// 6. Else if \c V is a \a MetadataAsValue, rewrap the return of \a
237/// MapMetadata().
238/// 7. Else, compute the equivalent constant, and return it.
240 RemapFlags Flags = RF_None,
241 ValueMapTypeRemapper *TypeMapper = nullptr,
242 ValueMaterializer *Materializer = nullptr,
243 const MetadataPredicate *IdentityMD = nullptr) {
244 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
245 .mapValue(*V);
246}
247
248/// Lookup or compute a mapping for a piece of metadata.
249///
250/// Compute and memoize a mapping for \c MD.
251///
252/// 1. If \c MD is mapped, return it.
253/// 2. Else if \a RF_NoModuleLevelChanges or \c MD is an \a MDString, return
254/// \c MD.
255/// 3. Else if \c MD is a \a ConstantAsMetadata, call \a MapValue() and
256/// re-wrap its return (returning nullptr on nullptr).
257/// 4. Else if \c IdentityMD predicate returns true for \c MD then add an
258/// identity mapping for it and return it.
259/// 5. Else, \c MD is an \a MDNode. These are remapped, along with their
260/// transitive operands. Distinct nodes are duplicated or moved depending
261/// on \a RF_MoveDistinctNodes. Uniqued nodes are remapped like constants.
262///
263/// \note \a LocalAsMetadata is completely unsupported by \a MapMetadata.
264/// Instead, use \a MapValue() with its wrapping \a MetadataAsValue instance.
266 RemapFlags Flags = RF_None,
267 ValueMapTypeRemapper *TypeMapper = nullptr,
268 ValueMaterializer *Materializer = nullptr,
269 const MetadataPredicate *IdentityMD = nullptr) {
270 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
271 .mapMetadata(*MD);
272}
273
274/// Version of MapMetadata with type safety for MDNode.
276 RemapFlags Flags = RF_None,
277 ValueMapTypeRemapper *TypeMapper = nullptr,
278 ValueMaterializer *Materializer = nullptr,
279 const MetadataPredicate *IdentityMD = nullptr) {
280 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
281 .mapMDNode(*MD);
282}
283
284/// Convert the instruction operands from referencing the current values into
285/// those specified by VM.
286///
287/// If \a RF_IgnoreMissingLocals is set and an operand can't be found via \a
288/// MapValue(), use the old value. Otherwise assert that this doesn't happen.
289///
290/// Note that \a MapValue() only returns \c nullptr for SSA values missing from
291/// \c VM.
293 RemapFlags Flags = RF_None,
294 ValueMapTypeRemapper *TypeMapper = nullptr,
295 ValueMaterializer *Materializer = nullptr,
296 const MetadataPredicate *IdentityMD = nullptr) {
297 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
299}
300
301/// Remap source location atom. Called by RemapInstruction. This updates the
302/// instruction's atom group number if it has been mapped (e.g. with
303/// llvm::mapAtomInstance), which is necessary to distinguish source code
304/// atoms on duplicated code paths.
305LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM);
306
307/// Remap the Values used in the DbgRecord \a DR using the value map \a
308/// VM.
310 RemapFlags Flags = RF_None,
311 ValueMapTypeRemapper *TypeMapper = nullptr,
312 ValueMaterializer *Materializer = nullptr,
313 const MetadataPredicate *IdentityMD = nullptr) {
314 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
315 .remapDbgRecord(M, *DR);
316}
317
318/// Remap the Values used in the DbgRecords \a Range using the value map \a
319/// VM.
323 RemapFlags Flags = RF_None,
324 ValueMapTypeRemapper *TypeMapper = nullptr,
325 ValueMaterializer *Materializer = nullptr,
326 const MetadataPredicate *IdentityMD = nullptr) {
327 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
329}
330
331/// Remap the operands, metadata, arguments, and instructions of a function.
332///
333/// Calls \a MapValue() on prefix data, prologue data, and personality
334/// function; calls \a MapMetadata() on each attached MDNode; remaps the
335/// argument types using the provided \c TypeMapper; and calls \a
336/// RemapInstruction() on every instruction.
338 RemapFlags Flags = RF_None,
339 ValueMapTypeRemapper *TypeMapper = nullptr,
340 ValueMaterializer *Materializer = nullptr,
341 const MetadataPredicate *IdentityMD = nullptr) {
342 ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD).remapFunction(F);
343}
344
345/// Version of MapValue with type safety for Constant.
347 RemapFlags Flags = RF_None,
348 ValueMapTypeRemapper *TypeMapper = nullptr,
349 ValueMaterializer *Materializer = nullptr,
350 const MetadataPredicate *IdentityMD = nullptr) {
351 return ValueMapper(VM, Flags, TypeMapper, Materializer, IdentityMD)
352 .mapConstant(*V);
353}
354
355} // end namespace llvm
356
357#endif // LLVM_TRANSFORMS_UTILS_VALUEMAPPER_H
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
#define F(x, y, z)
Definition MD5.cpp:54
#define I(x, y, z)
Definition MD5.cpp:57
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
This file defines the SmallPtrSet class.
Value * RHS
Value * LHS
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
This is an important base class in LLVM.
Definition Constant.h:44
Base class for non-instruction debug metadata records that have positions within IR.
Metadata node.
Definition Metadata.h:1087
Root of the metadata hierarchy.
Definition Metadata.h:65
A Module instance is used to store all the information related to an LLVM module.
Definition Module.h:68
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition Record.h:2295
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
This is a class that can be implemented by clients to remap types when cloning constants and instruct...
Definition ValueMapper.h:44
virtual ~ValueMapTypeRemapper()=default
virtual Type * remapType(Type *SrcTy)=0
The client should implement this method if they want to remap types while mapping values.
See the file comment.
Definition ValueMap.h:84
Context for (re-)mapping values (and metadata).
LLVM_ABI void remapDbgRecord(Module *M, DbgRecord &V)
LLVM_ABI ~ValueMapper()
LLVM_ABI void remapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range)
LLVM_ABI MDNode * mapMDNode(const MDNode &N)
LLVM_ABI Metadata * mapMetadata(const Metadata &MD)
ValueMapper & operator=(const ValueMapper &)=delete
LLVM_ABI void remapInstruction(Instruction &I)
ValueMapper(ValueMapper &&)=delete
LLVM_ABI void scheduleMapGlobalInitializer(GlobalVariable &GV, Constant &Init, unsigned MappingContextID=0)
LLVM_ABI void scheduleRemapFunction(Function &F, unsigned MappingContextID=0)
LLVM_ABI ValueMapper(ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
LLVM_ABI void scheduleMapGlobalIFunc(GlobalIFunc &GI, Constant &Resolver, unsigned MappingContextID=0)
LLVM_ABI unsigned registerAlternateMappingContext(ValueToValueMapTy &VM, ValueMaterializer *Materializer=nullptr)
Register an alternate mapping context.
ValueMapper(const ValueMapper &)=delete
LLVM_ABI void remapFunction(Function &F)
LLVM_ABI Constant * mapConstant(const Constant &C)
ValueMapper & operator=(ValueMapper &&)=delete
LLVM_ABI void scheduleMapGlobalAlias(GlobalAlias &GA, Constant &Aliasee, unsigned MappingContextID=0)
LLVM_ABI void remapGlobalObjectMetadata(GlobalObject &GO)
LLVM_ABI Value * mapValue(const Value &V)
LLVM_ABI void scheduleMapAppendingVariable(GlobalVariable &GV, GlobalVariable *OldGV, bool IsOldCtorDtor, ArrayRef< Constant * > NewMembers, unsigned MappingContextID=0)
LLVM_ABI void addFlags(RemapFlags Flags)
Add to the current RemapFlags.
This is a class that can be implemented by clients to materialize Values on demand.
Definition ValueMapper.h:57
ValueMaterializer & operator=(const ValueMaterializer &)=default
virtual Value * materialize(Value *V)=0
This method can be implemented to generate a mapped Value on demand.
ValueMaterializer(const ValueMaterializer &)=default
LLVM Value Representation.
Definition Value.h:75
A range adaptor for a pair of iterators.
ilist_select_iterator_type< OptionsT, false, false > iterator
This is an optimization pass for GlobalISel generic memory operations.
std::function< bool(const Metadata *)> MetadataPredicate
Definition ValueMapper.h:40
void RemapDbgRecordRange(Module *M, iterator_range< DbgRecordIterator > Range, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecords Range using the value map VM.
RemapFlags
These are flags that the value mapping APIs allow.
Definition ValueMapper.h:73
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
Definition ValueMapper.h:97
@ RF_NullMapMissingGlobalValues
Any global values not in value map are mapped to null instead of mapping to self.
@ RF_None
Definition ValueMapper.h:74
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
Definition ValueMapper.h:79
@ RF_DoNotRemapAtoms
Do not remap source location atoms.
@ RF_Importing
Indicate that we are importing functions, specifically in the context of ThinLTO.
@ RF_ReuseAndMutateDistinctMDs
Instruct the remapper to reuse and mutate distinct metadata (remapping them in place) instead of clon...
SmallPtrSet< const Metadata *, 16 > MetadataSetTy
Definition ValueMapper.h:39
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
void RemapDbgRecord(Module *M, DbgRecord *DR, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the Values used in the DbgRecord DR using the value map VM.
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Look up or compute a value in the value map.
void RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Remap the operands, metadata, arguments, and instructions of a function.
simple_ilist< DbgRecord >::iterator DbgRecordIterator
Definition ValueMapper.h:38
APInt operator|(APInt a, const APInt &b)
Definition APInt.h:2169
LLVM_ABI void RemapSourceAtom(Instruction *I, ValueToValueMapTy &VM)
Remap source location atom.
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Lookup or compute a mapping for a piece of metadata.
#define N