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"
22 #include "llvm/IR/Operator.h"
25 // Out of line method to get vtable etc for class.
26 void ValueMapTypeRemapper::anchor() {}
27 void ValueMaterializer::anchor() {}
28 void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
31 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
32 ValueMapTypeRemapper *TypeMapper,
33 ValueMaterializer *Materializer) {
34 ValueToValueMapTy::iterator I = VM.find(V);
36 // If the value already exists in the map, use it.
37 if (I != VM.end() && I->second) return I->second;
39 // If we have a materializer and it can materialize a value, use that.
42 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
44 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
45 Materializer->materializeInitFor(
46 NewGV, const_cast<GlobalValue *>(cast<GlobalValue>(V)));
51 // Global values do not need to be seeded into the VM if they
52 // are using the identity mapping.
53 if (isa<GlobalValue>(V)) {
54 if (Flags & RF_NullMapMissingGlobalValues) {
55 assert(!(Flags & RF_IgnoreMissingEntries) &&
56 "Illegal to specify both RF_NullMapMissingGlobalValues and "
57 "RF_IgnoreMissingEntries");
60 return VM[V] = const_cast<Value*>(V);
63 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
64 // Inline asm may need *type* remapping.
65 FunctionType *NewTy = IA->getFunctionType();
67 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
69 if (NewTy != IA->getFunctionType())
70 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
71 IA->hasSideEffects(), IA->isAlignStack());
74 return VM[V] = const_cast<Value*>(V);
77 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
78 const Metadata *MD = MDV->getMetadata();
79 // If this is a module-level metadata and we know that nothing at the module
80 // level is changing, then use an identity mapping.
81 if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
82 return VM[V] = const_cast<Value *>(V);
84 auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
85 if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
86 return VM[V] = const_cast<Value *>(V);
88 // FIXME: This assert crashes during bootstrap, but I think it should be
89 // correct. For now, just match behaviour from before the metadata/value
92 // assert((MappedMD || (Flags & RF_NullMapMissingGlobalValues)) &&
93 // "Referenced metadata value not in value map");
94 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
97 // Okay, this either must be a constant (which may or may not be mappable) or
98 // is something that is not in the mapping table.
99 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
103 if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
105 cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
106 BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
107 Flags, TypeMapper, Materializer));
108 return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
111 // Otherwise, we have some other constant to remap. Start by checking to see
112 // if all operands have an identity remapping.
113 unsigned OpNo = 0, NumOperands = C->getNumOperands();
114 Value *Mapped = nullptr;
115 for (; OpNo != NumOperands; ++OpNo) {
116 Value *Op = C->getOperand(OpNo);
117 Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
118 if (Mapped != C) break;
121 // See if the type mapper wants to remap the type as well.
122 Type *NewTy = C->getType();
124 NewTy = TypeMapper->remapType(NewTy);
126 // If the result type and all operands match up, then just insert an identity
128 if (OpNo == NumOperands && NewTy == C->getType())
131 // Okay, we need to create a new constant. We've already processed some or
132 // all of the operands, set them all up now.
133 SmallVector<Constant*, 8> Ops;
134 Ops.reserve(NumOperands);
135 for (unsigned j = 0; j != OpNo; ++j)
136 Ops.push_back(cast<Constant>(C->getOperand(j)));
138 // If one of the operands mismatch, push it and the other mapped operands.
139 if (OpNo != NumOperands) {
140 Ops.push_back(cast<Constant>(Mapped));
142 // Map the rest of the operands that aren't processed yet.
143 for (++OpNo; OpNo != NumOperands; ++OpNo)
144 Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
145 Flags, TypeMapper, Materializer));
147 Type *NewSrcTy = nullptr;
149 if (auto *GEPO = dyn_cast<GEPOperator>(C))
150 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
152 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
153 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
154 if (isa<ConstantArray>(C))
155 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
156 if (isa<ConstantStruct>(C))
157 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
158 if (isa<ConstantVector>(C))
159 return VM[V] = ConstantVector::get(Ops);
160 // If this is a no-operand constant, it must be because the type was remapped.
161 if (isa<UndefValue>(C))
162 return VM[V] = UndefValue::get(NewTy);
163 if (isa<ConstantAggregateZero>(C))
164 return VM[V] = ConstantAggregateZero::get(NewTy);
165 assert(isa<ConstantPointerNull>(C));
166 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
169 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
170 Metadata *Val, ValueMaterializer *Materializer,
172 VM.MD()[Key].reset(Val);
173 if (Materializer && !(Flags & RF_HaveUnmaterializedMetadata)) {
174 auto *N = dyn_cast_or_null<MDNode>(Val);
175 // Need to invoke this once we have non-temporary MD.
176 if (!N || !N->isTemporary())
177 Materializer->replaceTemporaryMetadata(Key, Val);
182 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD,
183 ValueMaterializer *Materializer, RemapFlags Flags) {
184 return mapToMetadata(VM, MD, const_cast<Metadata *>(MD), Materializer, Flags);
187 static Metadata *MapMetadataImpl(const Metadata *MD,
188 SmallVectorImpl<MDNode *> &DistinctWorklist,
189 ValueToValueMapTy &VM, RemapFlags Flags,
190 ValueMapTypeRemapper *TypeMapper,
191 ValueMaterializer *Materializer);
193 static Metadata *mapMetadataOp(Metadata *Op,
194 SmallVectorImpl<MDNode *> &DistinctWorklist,
195 ValueToValueMapTy &VM, RemapFlags Flags,
196 ValueMapTypeRemapper *TypeMapper,
197 ValueMaterializer *Materializer) {
201 if (Materializer && !Materializer->isMetadataNeeded(Op))
204 if (Metadata *MappedOp = MapMetadataImpl(Op, DistinctWorklist, VM, Flags,
205 TypeMapper, Materializer))
207 // Use identity map if MappedOp is null and we can ignore missing entries.
208 if (Flags & RF_IgnoreMissingEntries)
211 // FIXME: This assert crashes during bootstrap, but I think it should be
212 // correct. For now, just match behaviour from before the metadata/value
215 // assert((Flags & RF_NullMapMissingGlobalValues) &&
216 // "Referenced metadata not in value map!");
220 /// Resolve uniquing cycles involving the given metadata.
221 static void resolveCycles(Metadata *MD, bool AllowTemps) {
222 if (auto *N = dyn_cast_or_null<MDNode>(MD)) {
223 if (AllowTemps && N->isTemporary())
225 if (!N->isResolved()) {
227 // Note that this will drop RAUW support on any temporaries, which
228 // blocks uniquing. If this ends up being an issue, in the future
229 // we can experiment with delaying resolving these nodes until
230 // after metadata is fully materialized (i.e. when linking metadata
231 // as a postpass after function importing).
232 N->resolveNonTemporaries();
239 /// Remap the operands of an MDNode.
241 /// If \c Node is temporary, uniquing cycles are ignored. If \c Node is
242 /// distinct, uniquing cycles are resolved as they're found.
244 /// \pre \c Node.isDistinct() or \c Node.isTemporary().
245 static bool remapOperands(MDNode &Node,
246 SmallVectorImpl<MDNode *> &DistinctWorklist,
247 ValueToValueMapTy &VM, RemapFlags Flags,
248 ValueMapTypeRemapper *TypeMapper,
249 ValueMaterializer *Materializer) {
250 assert(!Node.isUniqued() && "Expected temporary or distinct node");
251 const bool IsDistinct = Node.isDistinct();
253 bool AnyChanged = false;
254 for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) {
255 Metadata *Old = Node.getOperand(I);
256 Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper,
260 Node.replaceOperandWith(I, New);
262 // Resolve uniquing cycles underneath distinct nodes on the fly so they
263 // don't infect later operands.
265 resolveCycles(New, Flags & RF_HaveUnmaterializedMetadata);
272 /// Map a distinct MDNode.
274 /// Whether distinct nodes change is independent of their operands. If \a
275 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
276 /// place; effectively, they're moved from one graph to another. Otherwise,
277 /// they're cloned/duplicated, and the new copy's operands are remapped.
278 static Metadata *mapDistinctNode(const MDNode *Node,
279 SmallVectorImpl<MDNode *> &DistinctWorklist,
280 ValueToValueMapTy &VM, RemapFlags Flags,
281 ValueMapTypeRemapper *TypeMapper,
282 ValueMaterializer *Materializer) {
283 assert(Node->isDistinct() && "Expected distinct node");
286 if (Flags & RF_MoveDistinctMDs)
287 NewMD = const_cast<MDNode *>(Node);
289 NewMD = MDNode::replaceWithDistinct(Node->clone());
291 // Remap operands later.
292 DistinctWorklist.push_back(NewMD);
293 return mapToMetadata(VM, Node, NewMD, Materializer, Flags);
296 /// \brief Map a uniqued MDNode.
298 /// Uniqued nodes may not need to be recreated (they may map to themselves).
299 static Metadata *mapUniquedNode(const MDNode *Node,
300 SmallVectorImpl<MDNode *> &DistinctWorklist,
301 ValueToValueMapTy &VM, RemapFlags Flags,
302 ValueMapTypeRemapper *TypeMapper,
303 ValueMaterializer *Materializer) {
304 assert(((Flags & RF_HaveUnmaterializedMetadata) || Node->isUniqued()) &&
305 "Expected uniqued node");
307 // Create a temporary node and map it upfront in case we have a uniquing
308 // cycle. If necessary, this mapping will get updated by RAUW logic before
310 auto ClonedMD = Node->clone();
311 mapToMetadata(VM, Node, ClonedMD.get(), Materializer, Flags);
312 if (!remapOperands(*ClonedMD, DistinctWorklist, VM, Flags, TypeMapper,
314 // No operands changed, so use the original.
315 ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
316 // Even though replaceAllUsesWith would have replaced the value map
317 // entry, we need to explictly map with the final non-temporary node
318 // to replace any temporary metadata via the callback.
319 return mapToSelf(VM, Node, Materializer, Flags);
322 // Uniquify the cloned node. Explicitly map it with the final non-temporary
323 // node so that replacement of temporary metadata via the callback occurs.
324 return mapToMetadata(VM, Node,
325 MDNode::replaceWithUniqued(std::move(ClonedMD)),
326 Materializer, Flags);
329 static Metadata *MapMetadataImpl(const Metadata *MD,
330 SmallVectorImpl<MDNode *> &DistinctWorklist,
331 ValueToValueMapTy &VM, RemapFlags Flags,
332 ValueMapTypeRemapper *TypeMapper,
333 ValueMaterializer *Materializer) {
334 // If the value already exists in the map, use it.
335 if (Metadata *NewMD = VM.MD().lookup(MD).get())
338 if (isa<MDString>(MD))
339 return mapToSelf(VM, MD, Materializer, Flags);
341 if (isa<ConstantAsMetadata>(MD))
342 if ((Flags & RF_NoModuleLevelChanges))
343 return mapToSelf(VM, MD, Materializer, Flags);
345 if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
347 MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
348 if (VMD->getValue() == MappedV ||
349 (!MappedV && (Flags & RF_IgnoreMissingEntries)))
350 return mapToSelf(VM, MD, Materializer, Flags);
352 // FIXME: This assert crashes during bootstrap, but I think it should be
353 // correct. For now, just match behaviour from before the metadata/value
356 // assert((MappedV || (Flags & RF_NullMapMissingGlobalValues)) &&
357 // "Referenced metadata not in value map!");
359 return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV), Materializer,
364 // Note: this cast precedes the Flags check so we always get its associated
366 const MDNode *Node = cast<MDNode>(MD);
368 // If this is a module-level metadata and we know that nothing at the
369 // module level is changing, then use an identity mapping.
370 if (Flags & RF_NoModuleLevelChanges)
371 return mapToSelf(VM, MD, Materializer, Flags);
373 // Require resolved nodes whenever metadata might be remapped.
374 assert(((Flags & RF_HaveUnmaterializedMetadata) || Node->isResolved()) &&
375 "Unexpected unresolved node");
377 if (Materializer && Node->isTemporary()) {
378 assert(Flags & RF_HaveUnmaterializedMetadata);
380 Materializer->mapTemporaryMetadata(const_cast<Metadata *>(MD));
381 // If the above callback returned an existing temporary node, use it
382 // instead of the current temporary node. This happens when earlier
383 // function importing passes already created and saved a temporary
384 // metadata node for the same value id.
386 mapToMetadata(VM, MD, TempMD, Materializer, Flags);
391 if (Node->isDistinct())
392 return mapDistinctNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
395 return mapUniquedNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
399 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
400 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
401 ValueMaterializer *Materializer) {
402 SmallVector<MDNode *, 8> DistinctWorklist;
403 Metadata *NewMD = MapMetadataImpl(MD, DistinctWorklist, VM, Flags, TypeMapper,
406 // When there are no module-level changes, it's possible that the metadata
407 // graph has temporaries. Skip the logic to resolve cycles, since it's
408 // unnecessary (and invalid) in that case.
409 if (Flags & RF_NoModuleLevelChanges)
412 // Resolve cycles involving the entry metadata.
413 resolveCycles(NewMD, Flags & RF_HaveUnmaterializedMetadata);
415 // Remap the operands of distinct MDNodes.
416 while (!DistinctWorklist.empty())
417 remapOperands(*DistinctWorklist.pop_back_val(), DistinctWorklist, VM, Flags,
418 TypeMapper, Materializer);
423 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
424 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
425 ValueMaterializer *Materializer) {
426 return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
427 TypeMapper, Materializer));
430 /// RemapInstruction - Convert the instruction operands from referencing the
431 /// current values into those specified by VMap.
433 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
434 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
435 ValueMaterializer *Materializer){
437 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
438 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
439 // If we aren't ignoring missing entries, assert that something happened.
443 assert((Flags & RF_IgnoreMissingEntries) &&
444 "Referenced value not in value map!");
447 // Remap phi nodes' incoming blocks.
448 if (PHINode *PN = dyn_cast<PHINode>(I)) {
449 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
450 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
451 // If we aren't ignoring missing entries, assert that something happened.
453 PN->setIncomingBlock(i, cast<BasicBlock>(V));
455 assert((Flags & RF_IgnoreMissingEntries) &&
456 "Referenced block not in value map!");
460 // Remap attached metadata.
461 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
462 I->getAllMetadata(MDs);
463 for (const auto &MI : MDs) {
464 MDNode *Old = MI.second;
465 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
467 I->setMetadata(MI.first, New);
473 // If the instruction's type is being remapped, do so now.
474 if (auto CS = CallSite(I)) {
475 SmallVector<Type *, 3> Tys;
476 FunctionType *FTy = CS.getFunctionType();
477 Tys.reserve(FTy->getNumParams());
478 for (Type *Ty : FTy->params())
479 Tys.push_back(TypeMapper->remapType(Ty));
480 CS.mutateFunctionType(FunctionType::get(
481 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
484 if (auto *AI = dyn_cast<AllocaInst>(I))
485 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
486 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
487 GEP->setSourceElementType(
488 TypeMapper->remapType(GEP->getSourceElementType()));
489 GEP->setResultElementType(
490 TypeMapper->remapType(GEP->getResultElementType()));
492 I->mutateType(TypeMapper->remapType(I->getType()));