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/CallSite.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Metadata.h"
24 // Out of line method to get vtable etc for class.
25 void ValueMapTypeRemapper::anchor() {}
26 void ValueMaterializer::anchor() {}
28 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
29 ValueMapTypeRemapper *TypeMapper,
30 ValueMaterializer *Materializer) {
31 ValueToValueMapTy::iterator I = VM.find(V);
33 // If the value already exists in the map, use it.
34 if (I != VM.end() && I->second) return I->second;
36 // If we have a materializer and it can materialize a value, use that.
38 if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
42 // Global values do not need to be seeded into the VM if they
43 // are using the identity mapping.
44 if (isa<GlobalValue>(V))
45 return VM[V] = const_cast<Value*>(V);
47 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
48 // Inline asm may need *type* remapping.
49 FunctionType *NewTy = IA->getFunctionType();
51 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
53 if (NewTy != IA->getFunctionType())
54 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
55 IA->hasSideEffects(), IA->isAlignStack());
58 return VM[V] = const_cast<Value*>(V);
61 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
62 const Metadata *MD = MDV->getMetadata();
63 // If this is a module-level metadata and we know that nothing at the module
64 // level is changing, then use an identity mapping.
65 if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
66 return VM[V] = const_cast<Value *>(V);
68 auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
69 if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
70 return VM[V] = const_cast<Value *>(V);
72 // FIXME: This assert crashes during bootstrap, but I think it should be
73 // correct. For now, just match behaviour from before the metadata/value
76 // assert(MappedMD && "Referenced metadata value not in value map");
77 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
80 // Okay, this either must be a constant (which may or may not be mappable) or
81 // is something that is not in the mapping table.
82 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
86 if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
88 cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
89 BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
90 Flags, TypeMapper, Materializer));
91 return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
94 // Otherwise, we have some other constant to remap. Start by checking to see
95 // if all operands have an identity remapping.
96 unsigned OpNo = 0, NumOperands = C->getNumOperands();
97 Value *Mapped = nullptr;
98 for (; OpNo != NumOperands; ++OpNo) {
99 Value *Op = C->getOperand(OpNo);
100 Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
101 if (Mapped != C) break;
104 // See if the type mapper wants to remap the type as well.
105 Type *NewTy = C->getType();
107 NewTy = TypeMapper->remapType(NewTy);
109 // If the result type and all operands match up, then just insert an identity
111 if (OpNo == NumOperands && NewTy == C->getType())
114 // Okay, we need to create a new constant. We've already processed some or
115 // all of the operands, set them all up now.
116 SmallVector<Constant*, 8> Ops;
117 Ops.reserve(NumOperands);
118 for (unsigned j = 0; j != OpNo; ++j)
119 Ops.push_back(cast<Constant>(C->getOperand(j)));
121 // If one of the operands mismatch, push it and the other mapped operands.
122 if (OpNo != NumOperands) {
123 Ops.push_back(cast<Constant>(Mapped));
125 // Map the rest of the operands that aren't processed yet.
126 for (++OpNo; OpNo != NumOperands; ++OpNo)
127 Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
128 Flags, TypeMapper, Materializer));
131 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
132 return VM[V] = CE->getWithOperands(Ops, NewTy);
133 if (isa<ConstantArray>(C))
134 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
135 if (isa<ConstantStruct>(C))
136 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
137 if (isa<ConstantVector>(C))
138 return VM[V] = ConstantVector::get(Ops);
139 // If this is a no-operand constant, it must be because the type was remapped.
140 if (isa<UndefValue>(C))
141 return VM[V] = UndefValue::get(NewTy);
142 if (isa<ConstantAggregateZero>(C))
143 return VM[V] = ConstantAggregateZero::get(NewTy);
144 assert(isa<ConstantPointerNull>(C));
145 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
148 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
150 VM.MD()[Key].reset(Val);
154 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
155 return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
158 static Metadata *MapMetadataImpl(const Metadata *MD,
159 SmallVectorImpl<TrackingMDNodeRef> &Cycles,
160 ValueToValueMapTy &VM, RemapFlags Flags,
161 ValueMapTypeRemapper *TypeMapper,
162 ValueMaterializer *Materializer);
164 static Metadata *mapMetadataOp(Metadata *Op,
165 SmallVectorImpl<TrackingMDNodeRef> &Cycles,
166 ValueToValueMapTy &VM, RemapFlags Flags,
167 ValueMapTypeRemapper *TypeMapper,
168 ValueMaterializer *Materializer) {
171 if (Metadata *MappedOp =
172 MapMetadataImpl(Op, Cycles, VM, Flags, TypeMapper, Materializer))
174 // Use identity map if MappedOp is null and we can ignore missing entries.
175 if (Flags & RF_IgnoreMissingEntries)
178 // FIXME: This assert crashes during bootstrap, but I think it should be
179 // correct. For now, just match behaviour from before the metadata/value
182 // llvm_unreachable("Referenced metadata not in value map!");
186 /// \brief Remap nodes.
188 /// Insert \c NewNode in the value map, and then remap \c OldNode's operands.
189 /// Assumes that \c NewNode is already a clone of \c OldNode.
191 /// \pre \c NewNode is a clone of \c OldNode.
192 static bool remap(const MDNode *OldNode, MDNode *NewNode,
193 SmallVectorImpl<TrackingMDNodeRef> &Cycles,
194 ValueToValueMapTy &VM, RemapFlags Flags,
195 ValueMapTypeRemapper *TypeMapper,
196 ValueMaterializer *Materializer) {
197 assert(OldNode->getNumOperands() == NewNode->getNumOperands() &&
198 "Expected nodes to match");
199 assert(OldNode->isResolved() && "Expected resolved node");
200 assert(!NewNode->isUniqued() && "Expected non-uniqued node");
202 // Map the node upfront so it's available for cyclic references.
203 mapToMetadata(VM, OldNode, NewNode);
204 bool AnyChanged = false;
205 for (unsigned I = 0, E = OldNode->getNumOperands(); I != E; ++I) {
206 Metadata *Old = OldNode->getOperand(I);
207 assert(NewNode->getOperand(I) == Old &&
208 "Expected old operands to already be in place");
211 mapMetadataOp(Old, Cycles, VM, Flags, TypeMapper, Materializer);
214 NewNode->replaceOperandWith(I, New);
221 /// Map a distinct MDNode.
223 /// Whether distinct nodes change is independent of their operands. If \a
224 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
225 /// place; effectively, they're moved from one graph to another. Otherwise,
226 /// they're cloned/duplicated, and the new copy's operands are remapped.
227 static Metadata *mapDistinctNode(const MDNode *Node,
228 SmallVectorImpl<TrackingMDNodeRef> &Cycles,
229 ValueToValueMapTy &VM, RemapFlags Flags,
230 ValueMapTypeRemapper *TypeMapper,
231 ValueMaterializer *Materializer) {
232 assert(Node->isDistinct() && "Expected distinct node");
235 if (Flags & RF_MoveDistinctMDs)
236 NewMD = const_cast<MDNode *>(Node);
238 NewMD = MDNode::replaceWithDistinct(Node->clone());
240 // Remap the operands. If any change, track those that could be involved in
242 if (remap(Node, NewMD, Cycles, VM, Flags, TypeMapper, Materializer))
243 for (Metadata *Op : NewMD->operands())
244 if (auto *Node = dyn_cast_or_null<MDNode>(Op))
245 if (!Node->isResolved())
246 Cycles.emplace_back(Node);
251 /// \brief Map a uniqued MDNode.
253 /// Uniqued nodes may not need to be recreated (they may map to themselves).
254 static Metadata *mapUniquedNode(const MDNode *Node,
255 SmallVectorImpl<TrackingMDNodeRef> &Cycles,
256 ValueToValueMapTy &VM, RemapFlags Flags,
257 ValueMapTypeRemapper *TypeMapper,
258 ValueMaterializer *Materializer) {
259 assert(Node->isUniqued() && "Expected uniqued node");
261 // Create a temporary node upfront in case we have a metadata cycle.
262 auto ClonedMD = Node->clone();
263 if (!remap(Node, ClonedMD.get(), Cycles, VM, Flags, TypeMapper,
265 // No operands changed, so use the identity mapping.
266 ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
267 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,
276 SmallVectorImpl<TrackingMDNodeRef> &Cycles,
277 ValueToValueMapTy &VM, RemapFlags Flags,
278 ValueMapTypeRemapper *TypeMapper,
279 ValueMaterializer *Materializer) {
280 // If the value already exists in the map, use it.
281 if (Metadata *NewMD = VM.MD().lookup(MD).get())
284 if (isa<MDString>(MD))
285 return mapToSelf(VM, MD);
287 if (isa<ConstantAsMetadata>(MD))
288 if ((Flags & RF_NoModuleLevelChanges))
289 return mapToSelf(VM, MD);
291 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
293 MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
294 if (VMD->getValue() == MappedV ||
295 (!MappedV && (Flags & RF_IgnoreMissingEntries)))
296 return mapToSelf(VM, MD);
298 // FIXME: This assert crashes during bootstrap, but I think it should be
299 // correct. For now, just match behaviour from before the metadata/value
302 // assert(MappedV && "Referenced metadata not in value map!");
304 return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
308 // Note: this cast precedes the Flags check so we always get its associated
310 const MDNode *Node = cast<MDNode>(MD);
312 // If this is a module-level metadata and we know that nothing at the
313 // module level is changing, then use an identity mapping.
314 if (Flags & RF_NoModuleLevelChanges)
315 return mapToSelf(VM, MD);
317 // Require resolved nodes whenever metadata might be remapped.
318 assert(Node->isResolved() && "Unexpected unresolved node");
320 if (Node->isDistinct())
321 return mapDistinctNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
323 return mapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
326 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
327 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
328 ValueMaterializer *Materializer) {
329 SmallVector<TrackingMDNodeRef, 8> Cycles;
331 MapMetadataImpl(MD, Cycles, VM, Flags, TypeMapper, Materializer);
333 if ((Flags & RF_NoModuleLevelChanges) ||
334 (MD == NewMD && !(Flags & RF_MoveDistinctMDs))) {
335 assert(Cycles.empty() && "Unresolved cycles without remapping anything?");
339 if (auto *N = dyn_cast<MDNode>(NewMD))
340 if (!N->isResolved())
343 // Resolve cycles underneath MD.
344 for (MDNode *N : Cycles)
345 if (!N->isResolved())
351 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
352 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
353 ValueMaterializer *Materializer) {
354 return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
355 TypeMapper, Materializer));
358 /// RemapInstruction - Convert the instruction operands from referencing the
359 /// current values into those specified by VMap.
361 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
362 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
363 ValueMaterializer *Materializer){
365 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
366 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
367 // If we aren't ignoring missing entries, assert that something happened.
371 assert((Flags & RF_IgnoreMissingEntries) &&
372 "Referenced value not in value map!");
375 // Remap phi nodes' incoming blocks.
376 if (PHINode *PN = dyn_cast<PHINode>(I)) {
377 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
378 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
379 // If we aren't ignoring missing entries, assert that something happened.
381 PN->setIncomingBlock(i, cast<BasicBlock>(V));
383 assert((Flags & RF_IgnoreMissingEntries) &&
384 "Referenced block not in value map!");
388 // Remap attached metadata.
389 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
390 I->getAllMetadata(MDs);
391 for (const auto &MI : MDs) {
392 MDNode *Old = MI.second;
393 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
395 I->setMetadata(MI.first, New);
401 // If the instruction's type is being remapped, do so now.
402 if (auto CS = CallSite(I)) {
403 SmallVector<Type *, 3> Tys;
404 FunctionType *FTy = CS.getFunctionType();
405 Tys.reserve(FTy->getNumParams());
406 for (Type *Ty : FTy->params())
407 Tys.push_back(TypeMapper->remapType(Ty));
408 CS.mutateFunctionType(FunctionType::get(
409 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
412 if (auto *AI = dyn_cast<AllocaInst>(I))
413 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
414 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
415 GEP->setSourceElementType(
416 TypeMapper->remapType(GEP->getSourceElementType()));
417 GEP->setResultElementType(
418 TypeMapper->remapType(GEP->getResultElementType()));
420 I->mutateType(TypeMapper->remapType(I->getType()));