1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the MapValue function, which is shared by various parts of
11 // the lib/Transforms/Utils library.
13 //===----------------------------------------------------------------------===//
15 #include "llvm/Transforms/Utils/ValueMapper.h"
16 #include "llvm/IR/Constants.h"
17 #include "llvm/IR/Function.h"
18 #include "llvm/IR/InlineAsm.h"
19 #include "llvm/IR/Instructions.h"
20 #include "llvm/IR/Metadata.h"
23 // Out of line method to get vtable etc for class.
24 void ValueMapTypeRemapper::anchor() {}
25 void ValueMaterializer::anchor() {}
27 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
28 ValueMapTypeRemapper *TypeMapper,
29 ValueMaterializer *Materializer) {
30 ValueToValueMapTy::iterator I = VM.find(V);
32 // If the value already exists in the map, use it.
33 if (I != VM.end() && I->second) return I->second;
35 // If we have a materializer and it can materialize a value, use that.
37 if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
41 // Global values do not need to be seeded into the VM if they
42 // are using the identity mapping.
43 if (isa<GlobalValue>(V))
44 return VM[V] = const_cast<Value*>(V);
46 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
47 // Inline asm may need *type* remapping.
48 FunctionType *NewTy = IA->getFunctionType();
50 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
52 if (NewTy != IA->getFunctionType())
53 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
54 IA->hasSideEffects(), IA->isAlignStack());
57 return VM[V] = const_cast<Value*>(V);
60 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
61 const Metadata *MD = MDV->getMetadata();
62 // If this is a module-level metadata and we know that nothing at the module
63 // level is changing, then use an identity mapping.
64 if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
65 return VM[V] = const_cast<Value *>(V);
67 auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
68 if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
69 return VM[V] = const_cast<Value *>(V);
71 // FIXME: This assert crashes during bootstrap, but I think it should be
72 // correct. For now, just match behaviour from before the metadata/value
75 // assert(MappedMD && "Referenced metadata value not in value map");
76 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
79 // Okay, this either must be a constant (which may or may not be mappable) or
80 // is something that is not in the mapping table.
81 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
85 if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
87 cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
88 BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
89 Flags, TypeMapper, Materializer));
90 return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
93 // Otherwise, we have some other constant to remap. Start by checking to see
94 // if all operands have an identity remapping.
95 unsigned OpNo = 0, NumOperands = C->getNumOperands();
96 Value *Mapped = nullptr;
97 for (; OpNo != NumOperands; ++OpNo) {
98 Value *Op = C->getOperand(OpNo);
99 Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
100 if (Mapped != C) break;
103 // See if the type mapper wants to remap the type as well.
104 Type *NewTy = C->getType();
106 NewTy = TypeMapper->remapType(NewTy);
108 // If the result type and all operands match up, then just insert an identity
110 if (OpNo == NumOperands && NewTy == C->getType())
113 // Okay, we need to create a new constant. We've already processed some or
114 // all of the operands, set them all up now.
115 SmallVector<Constant*, 8> Ops;
116 Ops.reserve(NumOperands);
117 for (unsigned j = 0; j != OpNo; ++j)
118 Ops.push_back(cast<Constant>(C->getOperand(j)));
120 // If one of the operands mismatch, push it and the other mapped operands.
121 if (OpNo != NumOperands) {
122 Ops.push_back(cast<Constant>(Mapped));
124 // Map the rest of the operands that aren't processed yet.
125 for (++OpNo; OpNo != NumOperands; ++OpNo)
126 Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
127 Flags, TypeMapper, Materializer));
130 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
131 return VM[V] = CE->getWithOperands(Ops, NewTy);
132 if (isa<ConstantArray>(C))
133 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
134 if (isa<ConstantStruct>(C))
135 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
136 if (isa<ConstantVector>(C))
137 return VM[V] = ConstantVector::get(Ops);
138 // If this is a no-operand constant, it must be because the type was remapped.
139 if (isa<UndefValue>(C))
140 return VM[V] = UndefValue::get(NewTy);
141 if (isa<ConstantAggregateZero>(C))
142 return VM[V] = ConstantAggregateZero::get(NewTy);
143 assert(isa<ConstantPointerNull>(C));
144 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
147 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
149 VM.MD()[Key].reset(Val);
153 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
154 return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
157 static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
159 ValueMapTypeRemapper *TypeMapper,
160 ValueMaterializer *Materializer);
162 static Metadata *mapMetadataOp(Metadata *Op, ValueToValueMapTy &VM,
164 ValueMapTypeRemapper *TypeMapper,
165 ValueMaterializer *Materializer) {
168 if (Metadata *MappedOp =
169 MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
171 // Use identity map if MappedOp is null and we can ignore missing entries.
172 if (Flags & RF_IgnoreMissingEntries)
175 // FIXME: This assert crashes during bootstrap, but I think it should be
176 // correct. For now, just match behaviour from before the metadata/value
179 // llvm_unreachable("Referenced metadata not in value map!");
183 static TempMDTuple cloneMDTuple(const MDTuple *Node) {
184 SmallVector<Metadata *, 4> Elts;
185 Elts.append(Node->op_begin(), Node->op_end());
186 return MDTuple::getTemporary(Node->getContext(), Elts);
189 static TempMDLocation cloneMDLocation(const MDLocation *Node) {
190 return MDLocation::getTemporary(Node->getContext(), Node->getLine(),
191 Node->getColumn(), Node->getScope(),
192 Node->getInlinedAt());
195 static TempUniquableMDNode cloneMDNode(const UniquableMDNode *Node) {
196 switch (Node->getMetadataID()) {
198 llvm_unreachable("Invalid UniquableMDNode subclass");
199 #define HANDLE_UNIQUABLE_LEAF(CLASS) \
200 case Metadata::CLASS##Kind: \
201 return clone##CLASS(cast<CLASS>(Node));
202 #include "llvm/IR/Metadata.def"
206 /// \brief Remap nodes.
208 /// Insert \c NewNode in the value map, and then remap \c OldNode's operands.
209 /// Assumes that \c NewNode is already a clone of \c OldNode.
211 /// \pre \c NewNode is a clone of \c OldNode.
212 static bool remap(const UniquableMDNode *OldNode, UniquableMDNode *NewNode,
213 ValueToValueMapTy &VM, RemapFlags Flags,
214 ValueMapTypeRemapper *TypeMapper,
215 ValueMaterializer *Materializer) {
216 assert(OldNode->getNumOperands() == NewNode->getNumOperands() &&
217 "Expected nodes to match");
218 assert(OldNode->isResolved() && "Expected resolved node");
219 assert(!NewNode->isUniqued() && "Expected non-uniqued node");
221 // Map the node upfront so it's available for cyclic references.
222 mapToMetadata(VM, OldNode, NewNode);
223 bool AnyChanged = false;
224 for (unsigned I = 0, E = OldNode->getNumOperands(); I != E; ++I) {
225 Metadata *Old = OldNode->getOperand(I);
226 assert(NewNode->getOperand(I) == Old &&
227 "Expected old operands to already be in place");
229 Metadata *New = mapMetadataOp(OldNode->getOperand(I), VM, Flags, TypeMapper,
233 NewNode->replaceOperandWith(I, New);
240 /// \brief Map a distinct MDNode.
242 /// Distinct nodes are not uniqued, so they must always recreated.
243 static Metadata *mapDistinctNode(const UniquableMDNode *Node,
244 ValueToValueMapTy &VM, RemapFlags Flags,
245 ValueMapTypeRemapper *TypeMapper,
246 ValueMaterializer *Materializer) {
247 assert(Node->isDistinct() && "Expected distinct node");
249 UniquableMDNode *NewMD = MDNode::replaceWithDistinct(cloneMDNode(Node));
250 remap(Node, NewMD, VM, Flags, TypeMapper, Materializer);
254 /// \brief Map a uniqued MDNode.
256 /// Uniqued nodes may not need to be recreated (they may map to themselves).
257 static Metadata *mapUniquedNode(const UniquableMDNode *Node,
258 ValueToValueMapTy &VM, RemapFlags Flags,
259 ValueMapTypeRemapper *TypeMapper,
260 ValueMaterializer *Materializer) {
261 assert(Node->isUniqued() && "Expected uniqued node");
263 // Create a temporary node upfront in case we have a metadata cycle.
264 auto ClonedMD = cloneMDNode(Node);
266 if (!remap(Node, ClonedMD.get(), VM, Flags, TypeMapper, Materializer))
267 // No operands changed, so use the identity mapping.
268 return mapToSelf(VM, Node);
270 // At least one operand has changed, so uniquify the cloned node.
271 return mapToMetadata(VM, Node,
272 MDNode::replaceWithUniqued(std::move(ClonedMD)));
275 static Metadata *MapMetadataImpl(const Metadata *MD, ValueToValueMapTy &VM,
277 ValueMapTypeRemapper *TypeMapper,
278 ValueMaterializer *Materializer) {
279 // If the value already exists in the map, use it.
280 if (Metadata *NewMD = VM.MD().lookup(MD).get())
283 if (isa<MDString>(MD))
284 return mapToSelf(VM, MD);
286 if (isa<ConstantAsMetadata>(MD))
287 if ((Flags & RF_NoModuleLevelChanges))
288 return mapToSelf(VM, MD);
290 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
292 MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
293 if (VMD->getValue() == MappedV ||
294 (!MappedV && (Flags & RF_IgnoreMissingEntries)))
295 return mapToSelf(VM, MD);
297 // FIXME: This assert crashes during bootstrap, but I think it should be
298 // correct. For now, just match behaviour from before the metadata/value
301 // assert(MappedV && "Referenced metadata not in value map!");
303 return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
307 const UniquableMDNode *Node = cast<UniquableMDNode>(MD);
308 assert(Node->isResolved() && "Unexpected unresolved node");
310 // If this is a module-level metadata and we know that nothing at the
311 // module level is changing, then use an identity mapping.
312 if (Flags & RF_NoModuleLevelChanges)
313 return mapToSelf(VM, MD);
315 if (Node->isDistinct())
316 return mapDistinctNode(Node, VM, Flags, TypeMapper, Materializer);
318 return mapUniquedNode(Node, VM, Flags, TypeMapper, Materializer);
321 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
322 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
323 ValueMaterializer *Materializer) {
324 Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
325 if (NewMD && NewMD != MD)
326 if (auto *N = dyn_cast<UniquableMDNode>(NewMD))
331 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
332 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
333 ValueMaterializer *Materializer) {
334 return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
335 TypeMapper, Materializer));
338 /// RemapInstruction - Convert the instruction operands from referencing the
339 /// current values into those specified by VMap.
341 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
342 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
343 ValueMaterializer *Materializer){
345 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
346 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
347 // If we aren't ignoring missing entries, assert that something happened.
351 assert((Flags & RF_IgnoreMissingEntries) &&
352 "Referenced value not in value map!");
355 // Remap phi nodes' incoming blocks.
356 if (PHINode *PN = dyn_cast<PHINode>(I)) {
357 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
358 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
359 // If we aren't ignoring missing entries, assert that something happened.
361 PN->setIncomingBlock(i, cast<BasicBlock>(V));
363 assert((Flags & RF_IgnoreMissingEntries) &&
364 "Referenced block not in value map!");
368 // Remap attached metadata.
369 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
370 I->getAllMetadata(MDs);
371 for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
375 MDNode *Old = MI->second;
376 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
378 I->setMetadata(MI->first, New);
381 // If the instruction's type is being remapped, do so now.
383 I->mutateType(TypeMapper->remapType(I->getType()));