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