blob: 472c2cab26d958015ad95da6e5d56555c0776afa [file] [log] [blame]
Chris Lattnere4dbb1a2002-11-20 20:47:41 +00001//===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
Misha Brukmanb1c93172005-04-21 23:48:37 +00002//
John Criswell482202a2003-10-20 19:43:21 +00003// The LLVM Compiler Infrastructure
4//
Chris Lattnerf3ebc3f2007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Misha Brukmanb1c93172005-04-21 23:48:37 +00007//
John Criswell482202a2003-10-20 19:43:21 +00008//===----------------------------------------------------------------------===//
Chris Lattnere4dbb1a2002-11-20 20:47:41 +00009//
10// This file defines the MapValue function, which is shared by various parts of
11// the lib/Transforms/Utils library.
12//
13//===----------------------------------------------------------------------===//
14
Dan Gohmana2095032010-08-24 18:50:07 +000015#include "llvm/Transforms/Utils/ValueMapper.h"
David Blaikie348de692015-04-23 21:36:23 +000016#include "llvm/IR/CallSite.h"
Chandler Carruth9fb823b2013-01-02 11:36:10 +000017#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"
David Blaikie88208842015-08-21 20:16:51 +000022#include "llvm/IR/Operator.h"
Chris Lattnerdf3c3422004-01-09 06:12:26 +000023using namespace llvm;
Chris Lattnere4dbb1a2002-11-20 20:47:41 +000024
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000025// Out of line method to get vtable etc for class.
Craig Topper2a6a08b2012-09-26 06:36:36 +000026void ValueMapTypeRemapper::anchor() {}
James Molloyf6f121e2013-05-28 15:17:05 +000027void ValueMaterializer::anchor() {}
Rafael Espindola19b52382015-11-27 20:28:19 +000028void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
29}
Chris Lattnerb1ed91f2011-07-09 17:41:24 +000030
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000031namespace {
32
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000033/// A GlobalValue whose initializer needs to be materialized.
34struct DelayedGlobalValueInit {
35 GlobalValue *Old;
36 GlobalValue *New;
37 DelayedGlobalValueInit(const GlobalValue *Old, GlobalValue *New)
38 : Old(const_cast<GlobalValue *>(Old)), New(New) {}
39};
40
41/// A basic block used in a BlockAddress whose function body is not yet
42/// materialized.
43struct DelayedBasicBlock {
44 BasicBlock *OldBB;
45 std::unique_ptr<BasicBlock> TempBB;
Duncan P. N. Exon Smitha9978562016-04-03 20:42:21 +000046
47 // Explicit move for MSVC.
48 DelayedBasicBlock(DelayedBasicBlock &&X)
49 : OldBB(std::move(X.OldBB)), TempBB(std::move(X.TempBB)) {}
50 DelayedBasicBlock &operator=(DelayedBasicBlock &&X) {
51 OldBB = std::move(X.OldBB);
52 TempBB = std::move(X.TempBB);
53 return *this;
54 }
55
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000056 DelayedBasicBlock(const BlockAddress &Old)
57 : OldBB(Old.getBasicBlock()),
58 TempBB(BasicBlock::Create(Old.getContext())) {}
59};
60
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000061class MDNodeMapper;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000062class Mapper {
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +000063 friend class MDNodeMapper;
64
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000065 ValueToValueMapTy &VM;
66 RemapFlags Flags;
67 ValueMapTypeRemapper *TypeMapper;
68 ValueMaterializer *Materializer;
69
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +000070 SmallVector<DelayedGlobalValueInit, 8> DelayedInits;
71 SmallVector<DelayedBasicBlock, 1> DelayedBBs;
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000072
73public:
74 Mapper(ValueToValueMapTy &VM, RemapFlags Flags,
75 ValueMapTypeRemapper *TypeMapper, ValueMaterializer *Materializer)
76 : VM(VM), Flags(Flags), TypeMapper(TypeMapper),
77 Materializer(Materializer) {}
78
79 ~Mapper();
80
81 Value *mapValue(const Value *V);
82
83 /// Map metadata.
84 ///
85 /// Find the mapping for MD. Guarantees that the return will be resolved
86 /// (not an MDNode, or MDNode::isResolved() returns true).
87 Metadata *mapMetadata(const Metadata *MD);
88
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +000089 // Map LocalAsMetadata, which never gets memoized.
90 //
91 // If the referenced local is not mapped, the principled return is nullptr.
92 // However, optimization passes sometimes move metadata operands *before* the
93 // SSA values they reference. To prevent crashes in \a RemapInstruction(),
94 // return "!{}" when RF_IgnoreMissingLocals is not set.
95 //
96 // \note Adding a mapping for LocalAsMetadata is unsupported. Add a mapping
97 // to the value map for the SSA value in question instead.
98 //
99 // FIXME: Once we have a verifier check for forward references to SSA values
100 // through metadata operands, always return nullptr on unmapped locals.
101 Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
102
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000103private:
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000104 Value *mapBlockAddress(const BlockAddress &BA);
105
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000106 /// Map metadata that doesn't require visiting operands.
107 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
108
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000109 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
110 Metadata *mapToSelf(const Metadata *MD);
111};
112
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000113class MDNodeMapper {
114 Mapper &M;
115
116 struct Data {
117 bool HasChangedOps = false;
118 bool HasChangedAddress = false;
119 unsigned ID = ~0u;
120 TempMDNode Placeholder;
Duncan P. N. Exon Smithf880d352016-04-05 21:07:01 +0000121
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000122 Data() {}
123 Data(Data &&X)
124 : HasChangedOps(std::move(X.HasChangedOps)),
125 HasChangedAddress(std::move(X.HasChangedAddress)),
126 ID(std::move(X.ID)), Placeholder(std::move(X.Placeholder)) {}
127 Data &operator=(Data &&X) {
128 HasChangedOps = std::move(X.HasChangedOps);
129 HasChangedAddress = std::move(X.HasChangedAddress);
130 ID = std::move(X.ID);
131 Placeholder = std::move(X.Placeholder);
132 return *this;
133 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000134 };
135
136 SmallDenseMap<const Metadata *, Data, 32> Info;
137 SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
138 SmallVector<MDNode *, 16> POT;
139
140public:
141 MDNodeMapper(Mapper &M) : M(M) {}
142
143 /// Map a metadata node (and its transitive operands).
144 ///
145 /// This is the only entry point into MDNodeMapper. It works as follows:
146 ///
147 /// 1. \a createPOT(): use a worklist to perform a post-order traversal of
148 /// the transitively referenced unmapped nodes.
149 ///
150 /// 2. \a propagateChangedOperands(): track which nodes will change
151 /// operands, and which will have new addresses in the mapped scheme.
152 /// Propagate the changes through the POT until fixed point, to pick up
153 /// uniquing cycles that need to change.
154 ///
155 /// 3. \a mapDistinctNodes(): map all the distinct nodes without touching
156 /// their operands. If RF_MoveDistinctMetadata, they get mapped to
157 /// themselves; otherwise, they get mapped to clones.
158 ///
159 /// 4. \a mapUniquedNodes(): map the uniqued nodes (bottom-up), lazily
160 /// creating temporaries for forward references as needed.
161 ///
162 /// 5. \a remapDistinctOperands(): remap the operands of the distinct nodes.
163 Metadata *map(const MDNode &FirstN);
164
165private:
166 /// Return \c true as long as there's work to do.
167 bool hasWork() const { return !Worklist.empty(); }
168
169 /// Get the current node in the worklist.
170 MDNode &getCurrentNode() const { return *Worklist.back().first; }
171
172 /// Push a node onto the worklist.
173 ///
174 /// Adds \c N to \a Worklist and \a Info, unless it's already inserted. If
175 /// \c N.isDistinct(), \a Data::HasChangedAddress will be set based on \a
176 /// RF_MoveDistinctMDs.
177 ///
178 /// Returns the data for the node.
179 ///
180 /// \post Data::HasChangedAddress iff !RF_MoveDistinctMDs && N.isDistinct().
181 /// \post Worklist.back().first == &N.
182 /// \post Worklist.back().second == false.
183 Data &push(const MDNode &N);
184
185 /// Map a node operand, and return true if it changes.
186 ///
187 /// \post getMappedOp(Op) does not return None.
188 bool mapOperand(const Metadata *Op);
189
190 /// Get a previously mapped node.
191 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
192
193 /// Try to pop a node off the worklist and store it in POT.
194 ///
195 /// Returns \c true if it popped; \c false if its operands need to be
196 /// visited.
197 ///
198 /// \post If Worklist.back().second == false: Worklist.back().second == true.
199 /// \post Else: Worklist.back() has been popped off and added to \a POT.
200 bool tryToPop();
201
202 /// Get a forward reference to a node to use as an operand.
203 ///
204 /// Returns \c Op if it's not changing; otherwise, lazily creates a temporary
205 /// node and returns it.
206 Metadata &getFwdReference(const Data &D, MDNode &Op);
207
208 /// Create a post-order traversal from the given node.
209 ///
210 /// This traverses the metadata graph deeply enough to map \c FirstN. It
211 /// uses \a mapOperand() (indirectly, \a Mapper::mapSimplifiedNode()), so any
212 /// metadata that has already been mapped will not be part of the POT.
213 ///
214 /// \post \a POT is a post-order traversal ending with \c FirstN.
215 bool createPOT(const MDNode &FirstN);
216
217 /// Propagate changed operands through post-order traversal.
218 ///
219 /// Until fixed point, iteratively update:
220 ///
221 /// - \a Data::HasChangedOps based on \a Data::HasChangedAddress of operands;
222 /// - \a Data::HasChangedAddress based on Data::HasChangedOps.
223 ///
224 /// This algorithm never changes \a Data::HasChangedAddress for distinct
225 /// nodes.
226 ///
227 /// \post \a POT is a post-order traversal ending with \c FirstN.
228 void propagateChangedOperands();
229
230 /// Map all distinct nodes in POT.
231 ///
232 /// \post \a getMappedOp() returns the correct node for every distinct node.
233 void mapDistinctNodes();
234
235 /// Map all uniqued nodes in POT with the correct operands.
236 ///
237 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
238 /// \post \a getMappedOp() returns the correct node for every node.
239 /// \post \a MDNode::operands() is correct for every uniqued node.
240 /// \post \a MDNode::isResolved() returns true for every node.
241 void mapUniquedNodes();
242
243 /// Re-map the operands for distinct nodes in POT.
244 ///
245 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
246 /// \pre Uniqued nodes are mapped (\a mapUniquedNodes() has been called).
247 /// \post \a MDNode::operands() is correct for every distinct node.
248 void remapDistinctOperands();
249
250 /// Remap a node's operands.
251 ///
252 /// Iterate through operands and update them in place using \a getMappedOp()
253 /// and \a getFwdReference().
254 ///
255 /// \pre N.isDistinct() or N.isTemporary().
256 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
257 /// \pre If \c N is distinct, all uniqued nodes are already mapped.
258 void remapOperands(const Data &D, MDNode &N);
259};
260
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000261} // end namespace
262
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000263Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
James Molloyf6f121e2013-05-28 15:17:05 +0000264 ValueMapTypeRemapper *TypeMapper,
265 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000266 return Mapper(VM, Flags, TypeMapper, Materializer).mapValue(V);
267}
268
269Value *Mapper::mapValue(const Value *V) {
Chris Lattner43f8d162011-01-08 08:15:20 +0000270 ValueToValueMapTy::iterator I = VM.find(V);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000271
Chris Lattner43f8d162011-01-08 08:15:20 +0000272 // If the value already exists in the map, use it.
273 if (I != VM.end() && I->second) return I->second;
274
James Molloyf6f121e2013-05-28 15:17:05 +0000275 // If we have a materializer and it can materialize a value, use that.
276 if (Materializer) {
Rafael Espindola19b52382015-11-27 20:28:19 +0000277 if (Value *NewV =
278 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
279 VM[V] = NewV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000280 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000281 DelayedInits.push_back(
282 DelayedGlobalValueInit(cast<GlobalValue>(V), NewGV));
Rafael Espindola19b52382015-11-27 20:28:19 +0000283 return NewV;
284 }
James Molloyf6f121e2013-05-28 15:17:05 +0000285 }
286
Dan Gohmanca26f792010-08-26 15:41:53 +0000287 // Global values do not need to be seeded into the VM if they
288 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000289 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000290 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000291 return nullptr;
Chris Lattner43f8d162011-01-08 08:15:20 +0000292 return VM[V] = const_cast<Value*>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000293 }
294
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000295 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
296 // Inline asm may need *type* remapping.
297 FunctionType *NewTy = IA->getFunctionType();
298 if (TypeMapper) {
299 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
300
301 if (NewTy != IA->getFunctionType())
302 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
303 IA->hasSideEffects(), IA->isAlignStack());
304 }
305
306 return VM[V] = const_cast<Value*>(V);
307 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000308
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000309 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
310 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000311
312 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
313 // Look through to grab the local value.
314 if (Value *LV = mapValue(LAM->getValue())) {
315 if (V == LAM->getValue())
316 return const_cast<Value *>(V);
317 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
318 }
319
320 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
321 // ensures metadata operands only reference defined SSA values.
322 return (Flags & RF_IgnoreMissingLocals)
323 ? nullptr
324 : MetadataAsValue::get(V->getContext(),
325 MDTuple::get(V->getContext(), None));
326 }
327
Chris Lattner43f8d162011-01-08 08:15:20 +0000328 // If this is a module-level metadata and we know that nothing at the module
329 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000330 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000331 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000332
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000333 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000334 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000335 if (MD == MappedMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000336 return VM[V] = const_cast<Value *>(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000337 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000338 }
339
Chris Lattner43f8d162011-01-08 08:15:20 +0000340 // Okay, this either must be a constant (which may or may not be mappable) or
341 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000342 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000343 if (!C)
344 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000345
346 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
347 return mapBlockAddress(*BA);
348
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000349 // Otherwise, we have some other constant to remap. Start by checking to see
350 // if all operands have an identity remapping.
351 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000352 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000353 for (; OpNo != NumOperands; ++OpNo) {
354 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000355 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000356 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000357 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358
359 // See if the type mapper wants to remap the type as well.
360 Type *NewTy = C->getType();
361 if (TypeMapper)
362 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000363
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000364 // If the result type and all operands match up, then just insert an identity
365 // mapping.
366 if (OpNo == NumOperands && NewTy == C->getType())
367 return VM[V] = C;
368
369 // Okay, we need to create a new constant. We've already processed some or
370 // all of the operands, set them all up now.
371 SmallVector<Constant*, 8> Ops;
372 Ops.reserve(NumOperands);
373 for (unsigned j = 0; j != OpNo; ++j)
374 Ops.push_back(cast<Constant>(C->getOperand(j)));
375
376 // If one of the operands mismatch, push it and the other mapped operands.
377 if (OpNo != NumOperands) {
378 Ops.push_back(cast<Constant>(Mapped));
379
380 // Map the rest of the operands that aren't processed yet.
381 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000382 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000383 }
David Blaikie88208842015-08-21 20:16:51 +0000384 Type *NewSrcTy = nullptr;
385 if (TypeMapper)
386 if (auto *GEPO = dyn_cast<GEPOperator>(C))
387 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
388
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000389 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
David Blaikie88208842015-08-21 20:16:51 +0000390 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000391 if (isa<ConstantArray>(C))
392 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
393 if (isa<ConstantStruct>(C))
394 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
395 if (isa<ConstantVector>(C))
396 return VM[V] = ConstantVector::get(Ops);
397 // If this is a no-operand constant, it must be because the type was remapped.
398 if (isa<UndefValue>(C))
399 return VM[V] = UndefValue::get(NewTy);
400 if (isa<ConstantAggregateZero>(C))
401 return VM[V] = ConstantAggregateZero::get(NewTy);
402 assert(isa<ConstantPointerNull>(C));
403 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000404}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000405
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000406Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
407 Function *F = cast<Function>(mapValue(BA.getFunction()));
408
409 // F may not have materialized its initializer. In that case, create a
410 // dummy basic block for now, and replace it once we've materialized all
411 // the initializers.
412 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000413 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000414 DelayedBBs.push_back(DelayedBasicBlock(BA));
415 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000416 } else {
417 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000418 }
419
420 return VM[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
421}
422
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000423Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000424 VM.MD()[Key].reset(Val);
425 return Val;
426}
427
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000428Metadata *Mapper::mapToSelf(const Metadata *MD) {
429 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000430}
431
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000432bool MDNodeMapper::mapOperand(const Metadata *Op) {
433 if (!Op)
434 return false;
435
436 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000437 assert((isa<MDString>(Op) || M.VM.getMappedMD(Op)) &&
438 "Expected result to be memoized");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000439 return *MappedOp != Op;
440 }
441
442 return push(*cast<MDNode>(Op)).HasChangedAddress;
443}
444
445Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000446 if (!Op)
447 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000448
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000449 if (Optional<Metadata *> MappedOp = M.VM.getMappedMD(Op))
450 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000451
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000452 if (isa<MDString>(Op))
453 return const_cast<Metadata *>(Op);
454
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000455 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000456}
457
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000458Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
459 auto Where = Info.find(&Op);
460 assert(Where != Info.end() && "Expected a valid reference");
461
462 auto &OpD = Where->second;
463 assert(OpD.ID > D.ID && "Expected a forward reference");
464
465 if (!OpD.HasChangedAddress)
466 return Op;
467
468 // Lazily construct a temporary node.
469 if (!OpD.Placeholder)
470 OpD.Placeholder = Op.clone();
471
472 return *OpD.Placeholder;
473}
474
475void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
476 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
477 Metadata *Old = N.getOperand(I);
478 Metadata *New;
479 if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
480 New = *MappedOp;
481 } else {
482 assert(!N.isDistinct() &&
483 "Expected all nodes to be pre-mapped for distinct operands");
484 MDNode &OldN = *cast<MDNode>(Old);
485 assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
486 New = &getFwdReference(D, OldN);
487 }
488
489 if (Old != New)
490 N.replaceOperandWith(I, New);
491 }
492}
493
494MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
495 auto Insertion = Info.insert(std::make_pair(&N, Data()));
496 auto &D = Insertion.first->second;
497 if (!Insertion.second)
498 return D;
499
500 // Add to the worklist; check for distinct nodes that are required to be
501 // copied.
502 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
503 D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
504 return D;
505}
506
507bool MDNodeMapper::tryToPop() {
508 if (!Worklist.back().second) {
509 Worklist.back().second = true;
510 return false;
511 }
512
513 MDNode *N = Worklist.pop_back_val().first;
514 Info[N].ID = POT.size();
515 POT.push_back(N);
516 return true;
517}
518
519bool MDNodeMapper::createPOT(const MDNode &FirstN) {
520 bool AnyChanges = false;
521
522 // Do a traversal of the unmapped subgraph, tracking whether operands change.
523 // In some cases, these changes will propagate naturally, but
524 // propagateChangedOperands() catches the general case.
525 AnyChanges |= push(FirstN).HasChangedAddress;
526 while (hasWork()) {
527 if (tryToPop())
528 continue;
529
530 MDNode &N = getCurrentNode();
531 bool LocalChanges = false;
532 for (const Metadata *Op : N.operands())
533 LocalChanges |= mapOperand(Op);
534
535 if (!LocalChanges)
536 continue;
537
538 AnyChanges = true;
539 auto &D = Info[&N];
540 D.HasChangedOps = true;
541
542 // Uniqued nodes change address when operands change.
543 if (!N.isDistinct())
544 D.HasChangedAddress = true;
545 }
546 return AnyChanges;
547}
548
549void MDNodeMapper::propagateChangedOperands() {
550 bool AnyChangedAddresses;
551 do {
552 AnyChangedAddresses = false;
553 for (MDNode *N : POT) {
554 auto &NI = Info[N];
555 if (NI.HasChangedOps)
556 continue;
557
558 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
559 auto Where = Info.find(Op);
560 return Where != Info.end() && Where->second.HasChangedAddress;
561 }))
562 continue;
563
564 NI.HasChangedOps = true;
565 if (!N->isDistinct()) {
566 NI.HasChangedAddress = true;
567 AnyChangedAddresses = true;
568 }
569 }
570 } while (AnyChangedAddresses);
571}
572
573void MDNodeMapper::mapDistinctNodes() {
574 // Map all the distinct nodes in POT.
575 for (MDNode *N : POT) {
576 if (!N->isDistinct())
577 continue;
578
579 if (M.Flags & RF_MoveDistinctMDs)
580 M.mapToSelf(N);
581 else
582 M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
583 }
584}
585
586void MDNodeMapper::mapUniquedNodes() {
587 // Construct uniqued nodes, building forward references as necessary.
588 for (auto *N : POT) {
589 if (N->isDistinct())
590 continue;
591
592 auto &D = Info[N];
593 assert(D.HasChangedAddress == D.HasChangedOps &&
594 "Uniqued nodes should change address iff ops change");
595 if (!D.HasChangedAddress) {
596 M.mapToSelf(N);
597 continue;
598 }
599
600 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
601 remapOperands(D, *ClonedN);
602 M.mapToMetadata(N, MDNode::replaceWithUniqued(std::move(ClonedN)));
603 }
604
605 // Resolve cycles.
606 for (auto *N : POT)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000607 if (!N->isResolved())
608 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000609}
610
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000611void MDNodeMapper::remapDistinctOperands() {
612 for (auto *N : POT) {
613 if (!N->isDistinct())
614 continue;
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000615
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000616 auto &D = Info[N];
617 if (!D.HasChangedOps)
618 continue;
Duncan P. N. Exon Smith8c9dcac2015-08-07 00:44:55 +0000619
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000620 assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
621 "Distinct nodes should change address iff they cannot be moved");
622 remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000623 }
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000624}
625
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000626Metadata *MDNodeMapper::map(const MDNode &FirstN) {
627 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
628 "MDNodeMapper::map assumes module-level changes");
629 assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000630
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000631 // Require resolved nodes whenever metadata might be remapped.
632 assert(FirstN.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000633
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000634 // Return early if nothing at all changed.
635 if (!createPOT(FirstN)) {
636 for (const MDNode *N : POT)
637 M.mapToSelf(N);
638 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000639 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000640
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000641 propagateChangedOperands();
642 mapDistinctNodes();
643 mapUniquedNodes();
644 remapDistinctOperands();
645
646 // Return the original node, remapped.
647 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000648}
649
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000650Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000651 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000652 if (Optional<Metadata *> NewMD = VM.getMappedMD(MD))
653 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000654
655 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000656 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000657
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000658 // This is a module-level metadata. If nothing at the module level is
659 // changing, use an identity mapping.
660 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +0000661 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000662
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000663 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000664 // Disallow recursion into metadata mapping through mapValue.
665 VM.disableMapMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000666 Value *MappedV = mapValue(CMD->getValue());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000667 VM.enableMapMetadata();
668
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000669 if (CMD->getValue() == MappedV)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000670 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000671
Duncan P. N. Exon Smith8e65f8d2016-04-04 04:59:56 +0000672 return mapToMetadata(MD, MappedV ? ValueAsMetadata::get(MappedV) : nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000673 }
674
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000675 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000676
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000677 return None;
678}
679
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000680Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
681 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
682 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000683 return Mapper(VM, Flags, TypeMapper, Materializer).mapMetadata(MD);
684}
685
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000686Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
687 // Lookup the mapping for the value itself, and return the appropriate
688 // metadata.
689 if (Value *V = mapValue(LAM.getValue())) {
690 if (V == LAM.getValue())
691 return const_cast<LocalAsMetadata *>(&LAM);
692 return ValueAsMetadata::get(V);
693 }
694
695 // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
696 // metadata operands only reference defined SSA values.
697 return (Flags & RF_IgnoreMissingLocals)
698 ? nullptr
699 : MDTuple::get(LAM.getContext(), None);
700}
701
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000702Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000703 assert(MD && "Expected valid metadata");
704 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
705
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000706 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
707 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000708
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000709 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000710}
711
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000712Mapper::~Mapper() {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000713 // Materialize global initializers.
714 while (!DelayedInits.empty()) {
715 auto Init = DelayedInits.pop_back_val();
716 Materializer->materializeInitFor(Init.New, Init.Old);
717 }
718
719 // Process block addresses delayed until global inits.
720 while (!DelayedBBs.empty()) {
721 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
722 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
723 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
724 }
725
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000726 // We don't expect these to grow after clearing.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000727 assert(DelayedInits.empty());
728 assert(DelayedBBs.empty());
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000729}
730
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000731MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
732 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
733 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000734 return cast_or_null<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM,
735 Flags, TypeMapper, Materializer));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000736}
737
Brian Gaeke6182acf2004-05-19 09:08:12 +0000738/// RemapInstruction - Convert the instruction operands from referencing the
Devang Patelb8f11de2010-06-23 23:55:51 +0000739/// current values into those specified by VMap.
Brian Gaeke6182acf2004-05-19 09:08:12 +0000740///
Dan Gohmanca26f792010-08-26 15:41:53 +0000741void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
James Molloyf6f121e2013-05-28 15:17:05 +0000742 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
743 ValueMaterializer *Materializer){
Dan Gohmanca26f792010-08-26 15:41:53 +0000744 // Remap operands.
Gabor Greif5df43262008-05-30 21:24:22 +0000745 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
James Molloyf6f121e2013-05-28 15:17:05 +0000746 Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
Chris Lattner43f8d162011-01-08 08:15:20 +0000747 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000748 if (V)
Chris Lattner43f8d162011-01-08 08:15:20 +0000749 *op = V;
750 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000751 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000752 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000753 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000754
Jay Foad61ea0e42011-06-23 09:09:15 +0000755 // Remap phi nodes' incoming blocks.
756 if (PHINode *PN = dyn_cast<PHINode>(I)) {
757 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
758 Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
759 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000760 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000761 PN->setIncomingBlock(i, cast<BasicBlock>(V));
762 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000763 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000764 "Referenced block not in value map!");
765 }
766 }
767
Devang Patelc0174042011-08-04 20:02:18 +0000768 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000769 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000770 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000771 for (const auto &MI : MDs) {
772 MDNode *Old = MI.second;
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000773 MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
Dan Gohmanca26f792010-08-26 15:41:53 +0000774 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000775 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000776 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000777
David Blaikie348de692015-04-23 21:36:23 +0000778 if (!TypeMapper)
779 return;
780
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000781 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000782 if (auto CS = CallSite(I)) {
783 SmallVector<Type *, 3> Tys;
784 FunctionType *FTy = CS.getFunctionType();
785 Tys.reserve(FTy->getNumParams());
786 for (Type *Ty : FTy->params())
787 Tys.push_back(TypeMapper->remapType(Ty));
788 CS.mutateFunctionType(FunctionType::get(
789 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000790 return;
791 }
792 if (auto *AI = dyn_cast<AllocaInst>(I))
793 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000794 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000795 GEP->setSourceElementType(
796 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000797 GEP->setResultElementType(
798 TypeMapper->remapType(GEP->getResultElementType()));
799 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000800 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000801}