blob: 44efa5d0e8e6b78a99f369a43ff5ae8ca596e54a [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);
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +000082 void remapInstruction(Instruction *I);
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +000083 void remapFunction(Function &F);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +000084
85 /// Map metadata.
86 ///
87 /// Find the mapping for MD. Guarantees that the return will be resolved
88 /// (not an MDNode, or MDNode::isResolved() returns true).
89 Metadata *mapMetadata(const Metadata *MD);
90
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +000091 // Map LocalAsMetadata, which never gets memoized.
92 //
93 // If the referenced local is not mapped, the principled return is nullptr.
94 // However, optimization passes sometimes move metadata operands *before* the
95 // SSA values they reference. To prevent crashes in \a RemapInstruction(),
96 // return "!{}" when RF_IgnoreMissingLocals is not set.
97 //
98 // \note Adding a mapping for LocalAsMetadata is unsupported. Add a mapping
99 // to the value map for the SSA value in question instead.
100 //
101 // FIXME: Once we have a verifier check for forward references to SSA values
102 // through metadata operands, always return nullptr on unmapped locals.
103 Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
104
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000105private:
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000106 Value *mapBlockAddress(const BlockAddress &BA);
107
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000108 /// Map metadata that doesn't require visiting operands.
109 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
110
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000111 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
112 Metadata *mapToSelf(const Metadata *MD);
113};
114
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000115class MDNodeMapper {
116 Mapper &M;
117
118 struct Data {
119 bool HasChangedOps = false;
120 bool HasChangedAddress = false;
121 unsigned ID = ~0u;
122 TempMDNode Placeholder;
Duncan P. N. Exon Smithf880d352016-04-05 21:07:01 +0000123
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000124 Data() {}
125 Data(Data &&X)
126 : HasChangedOps(std::move(X.HasChangedOps)),
127 HasChangedAddress(std::move(X.HasChangedAddress)),
128 ID(std::move(X.ID)), Placeholder(std::move(X.Placeholder)) {}
129 Data &operator=(Data &&X) {
130 HasChangedOps = std::move(X.HasChangedOps);
131 HasChangedAddress = std::move(X.HasChangedAddress);
132 ID = std::move(X.ID);
133 Placeholder = std::move(X.Placeholder);
134 return *this;
135 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000136 };
137
138 SmallDenseMap<const Metadata *, Data, 32> Info;
139 SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
140 SmallVector<MDNode *, 16> POT;
141
142public:
143 MDNodeMapper(Mapper &M) : M(M) {}
144
145 /// Map a metadata node (and its transitive operands).
146 ///
147 /// This is the only entry point into MDNodeMapper. It works as follows:
148 ///
149 /// 1. \a createPOT(): use a worklist to perform a post-order traversal of
150 /// the transitively referenced unmapped nodes.
151 ///
152 /// 2. \a propagateChangedOperands(): track which nodes will change
153 /// operands, and which will have new addresses in the mapped scheme.
154 /// Propagate the changes through the POT until fixed point, to pick up
155 /// uniquing cycles that need to change.
156 ///
157 /// 3. \a mapDistinctNodes(): map all the distinct nodes without touching
158 /// their operands. If RF_MoveDistinctMetadata, they get mapped to
159 /// themselves; otherwise, they get mapped to clones.
160 ///
161 /// 4. \a mapUniquedNodes(): map the uniqued nodes (bottom-up), lazily
162 /// creating temporaries for forward references as needed.
163 ///
164 /// 5. \a remapDistinctOperands(): remap the operands of the distinct nodes.
165 Metadata *map(const MDNode &FirstN);
166
167private:
168 /// Return \c true as long as there's work to do.
169 bool hasWork() const { return !Worklist.empty(); }
170
171 /// Get the current node in the worklist.
172 MDNode &getCurrentNode() const { return *Worklist.back().first; }
173
174 /// Push a node onto the worklist.
175 ///
176 /// Adds \c N to \a Worklist and \a Info, unless it's already inserted. If
177 /// \c N.isDistinct(), \a Data::HasChangedAddress will be set based on \a
178 /// RF_MoveDistinctMDs.
179 ///
180 /// Returns the data for the node.
181 ///
182 /// \post Data::HasChangedAddress iff !RF_MoveDistinctMDs && N.isDistinct().
183 /// \post Worklist.back().first == &N.
184 /// \post Worklist.back().second == false.
185 Data &push(const MDNode &N);
186
187 /// Map a node operand, and return true if it changes.
188 ///
189 /// \post getMappedOp(Op) does not return None.
190 bool mapOperand(const Metadata *Op);
191
192 /// Get a previously mapped node.
193 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
194
195 /// Try to pop a node off the worklist and store it in POT.
196 ///
197 /// Returns \c true if it popped; \c false if its operands need to be
198 /// visited.
199 ///
200 /// \post If Worklist.back().second == false: Worklist.back().second == true.
201 /// \post Else: Worklist.back() has been popped off and added to \a POT.
202 bool tryToPop();
203
204 /// Get a forward reference to a node to use as an operand.
205 ///
206 /// Returns \c Op if it's not changing; otherwise, lazily creates a temporary
207 /// node and returns it.
208 Metadata &getFwdReference(const Data &D, MDNode &Op);
209
210 /// Create a post-order traversal from the given node.
211 ///
212 /// This traverses the metadata graph deeply enough to map \c FirstN. It
213 /// uses \a mapOperand() (indirectly, \a Mapper::mapSimplifiedNode()), so any
214 /// metadata that has already been mapped will not be part of the POT.
215 ///
216 /// \post \a POT is a post-order traversal ending with \c FirstN.
217 bool createPOT(const MDNode &FirstN);
218
219 /// Propagate changed operands through post-order traversal.
220 ///
221 /// Until fixed point, iteratively update:
222 ///
223 /// - \a Data::HasChangedOps based on \a Data::HasChangedAddress of operands;
224 /// - \a Data::HasChangedAddress based on Data::HasChangedOps.
225 ///
226 /// This algorithm never changes \a Data::HasChangedAddress for distinct
227 /// nodes.
228 ///
229 /// \post \a POT is a post-order traversal ending with \c FirstN.
230 void propagateChangedOperands();
231
232 /// Map all distinct nodes in POT.
233 ///
234 /// \post \a getMappedOp() returns the correct node for every distinct node.
235 void mapDistinctNodes();
236
237 /// Map all uniqued nodes in POT with the correct operands.
238 ///
239 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
240 /// \post \a getMappedOp() returns the correct node for every node.
241 /// \post \a MDNode::operands() is correct for every uniqued node.
242 /// \post \a MDNode::isResolved() returns true for every node.
243 void mapUniquedNodes();
244
245 /// Re-map the operands for distinct nodes in POT.
246 ///
247 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
248 /// \pre Uniqued nodes are mapped (\a mapUniquedNodes() has been called).
249 /// \post \a MDNode::operands() is correct for every distinct node.
250 void remapDistinctOperands();
251
252 /// Remap a node's operands.
253 ///
254 /// Iterate through operands and update them in place using \a getMappedOp()
255 /// and \a getFwdReference().
256 ///
257 /// \pre N.isDistinct() or N.isTemporary().
258 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
259 /// \pre If \c N is distinct, all uniqued nodes are already mapped.
260 void remapOperands(const Data &D, MDNode &N);
261};
262
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000263} // end namespace
264
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000265Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
James Molloyf6f121e2013-05-28 15:17:05 +0000266 ValueMapTypeRemapper *TypeMapper,
267 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000268 return Mapper(VM, Flags, TypeMapper, Materializer).mapValue(V);
269}
270
271Value *Mapper::mapValue(const Value *V) {
Chris Lattner43f8d162011-01-08 08:15:20 +0000272 ValueToValueMapTy::iterator I = VM.find(V);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000273
Chris Lattner43f8d162011-01-08 08:15:20 +0000274 // If the value already exists in the map, use it.
275 if (I != VM.end() && I->second) return I->second;
276
James Molloyf6f121e2013-05-28 15:17:05 +0000277 // If we have a materializer and it can materialize a value, use that.
278 if (Materializer) {
Rafael Espindola19b52382015-11-27 20:28:19 +0000279 if (Value *NewV =
280 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
281 VM[V] = NewV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000282 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000283 DelayedInits.push_back(
284 DelayedGlobalValueInit(cast<GlobalValue>(V), NewGV));
Rafael Espindola19b52382015-11-27 20:28:19 +0000285 return NewV;
286 }
James Molloyf6f121e2013-05-28 15:17:05 +0000287 }
288
Dan Gohmanca26f792010-08-26 15:41:53 +0000289 // Global values do not need to be seeded into the VM if they
290 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000291 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000292 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000293 return nullptr;
Chris Lattner43f8d162011-01-08 08:15:20 +0000294 return VM[V] = const_cast<Value*>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000295 }
296
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000297 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
298 // Inline asm may need *type* remapping.
299 FunctionType *NewTy = IA->getFunctionType();
300 if (TypeMapper) {
301 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
302
303 if (NewTy != IA->getFunctionType())
304 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
305 IA->hasSideEffects(), IA->isAlignStack());
306 }
307
308 return VM[V] = const_cast<Value*>(V);
309 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000310
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000311 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
312 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000313
314 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
315 // Look through to grab the local value.
316 if (Value *LV = mapValue(LAM->getValue())) {
317 if (V == LAM->getValue())
318 return const_cast<Value *>(V);
319 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
320 }
321
322 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
323 // ensures metadata operands only reference defined SSA values.
324 return (Flags & RF_IgnoreMissingLocals)
325 ? nullptr
326 : MetadataAsValue::get(V->getContext(),
327 MDTuple::get(V->getContext(), None));
328 }
329
Chris Lattner43f8d162011-01-08 08:15:20 +0000330 // If this is a module-level metadata and we know that nothing at the module
331 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000332 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000333 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000334
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000335 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000336 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000337 if (MD == MappedMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000338 return VM[V] = const_cast<Value *>(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000339 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000340 }
341
Chris Lattner43f8d162011-01-08 08:15:20 +0000342 // Okay, this either must be a constant (which may or may not be mappable) or
343 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000344 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000345 if (!C)
346 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000347
348 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
349 return mapBlockAddress(*BA);
350
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000351 // Otherwise, we have some other constant to remap. Start by checking to see
352 // if all operands have an identity remapping.
353 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000354 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000355 for (; OpNo != NumOperands; ++OpNo) {
356 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000357 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000358 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000359 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000360
361 // See if the type mapper wants to remap the type as well.
362 Type *NewTy = C->getType();
363 if (TypeMapper)
364 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000365
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000366 // If the result type and all operands match up, then just insert an identity
367 // mapping.
368 if (OpNo == NumOperands && NewTy == C->getType())
369 return VM[V] = C;
370
371 // Okay, we need to create a new constant. We've already processed some or
372 // all of the operands, set them all up now.
373 SmallVector<Constant*, 8> Ops;
374 Ops.reserve(NumOperands);
375 for (unsigned j = 0; j != OpNo; ++j)
376 Ops.push_back(cast<Constant>(C->getOperand(j)));
377
378 // If one of the operands mismatch, push it and the other mapped operands.
379 if (OpNo != NumOperands) {
380 Ops.push_back(cast<Constant>(Mapped));
381
382 // Map the rest of the operands that aren't processed yet.
383 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000384 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000385 }
David Blaikie88208842015-08-21 20:16:51 +0000386 Type *NewSrcTy = nullptr;
387 if (TypeMapper)
388 if (auto *GEPO = dyn_cast<GEPOperator>(C))
389 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
390
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000391 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
David Blaikie88208842015-08-21 20:16:51 +0000392 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000393 if (isa<ConstantArray>(C))
394 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
395 if (isa<ConstantStruct>(C))
396 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
397 if (isa<ConstantVector>(C))
398 return VM[V] = ConstantVector::get(Ops);
399 // If this is a no-operand constant, it must be because the type was remapped.
400 if (isa<UndefValue>(C))
401 return VM[V] = UndefValue::get(NewTy);
402 if (isa<ConstantAggregateZero>(C))
403 return VM[V] = ConstantAggregateZero::get(NewTy);
404 assert(isa<ConstantPointerNull>(C));
405 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000406}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000407
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000408Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
409 Function *F = cast<Function>(mapValue(BA.getFunction()));
410
411 // F may not have materialized its initializer. In that case, create a
412 // dummy basic block for now, and replace it once we've materialized all
413 // the initializers.
414 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000415 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000416 DelayedBBs.push_back(DelayedBasicBlock(BA));
417 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000418 } else {
419 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000420 }
421
422 return VM[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
423}
424
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000425Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000426 VM.MD()[Key].reset(Val);
427 return Val;
428}
429
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000430Metadata *Mapper::mapToSelf(const Metadata *MD) {
431 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000432}
433
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000434bool MDNodeMapper::mapOperand(const Metadata *Op) {
435 if (!Op)
436 return false;
437
438 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000439 assert((isa<MDString>(Op) || M.VM.getMappedMD(Op)) &&
440 "Expected result to be memoized");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000441 return *MappedOp != Op;
442 }
443
444 return push(*cast<MDNode>(Op)).HasChangedAddress;
445}
446
447Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000448 if (!Op)
449 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000450
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000451 if (Optional<Metadata *> MappedOp = M.VM.getMappedMD(Op))
452 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000453
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000454 if (isa<MDString>(Op))
455 return const_cast<Metadata *>(Op);
456
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000457 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000458}
459
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000460Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
461 auto Where = Info.find(&Op);
462 assert(Where != Info.end() && "Expected a valid reference");
463
464 auto &OpD = Where->second;
465 assert(OpD.ID > D.ID && "Expected a forward reference");
466
467 if (!OpD.HasChangedAddress)
468 return Op;
469
470 // Lazily construct a temporary node.
471 if (!OpD.Placeholder)
472 OpD.Placeholder = Op.clone();
473
474 return *OpD.Placeholder;
475}
476
477void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
478 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
479 Metadata *Old = N.getOperand(I);
480 Metadata *New;
481 if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
482 New = *MappedOp;
483 } else {
484 assert(!N.isDistinct() &&
485 "Expected all nodes to be pre-mapped for distinct operands");
486 MDNode &OldN = *cast<MDNode>(Old);
487 assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
488 New = &getFwdReference(D, OldN);
489 }
490
491 if (Old != New)
492 N.replaceOperandWith(I, New);
493 }
494}
495
496MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
497 auto Insertion = Info.insert(std::make_pair(&N, Data()));
498 auto &D = Insertion.first->second;
499 if (!Insertion.second)
500 return D;
501
502 // Add to the worklist; check for distinct nodes that are required to be
503 // copied.
504 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
505 D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
506 return D;
507}
508
509bool MDNodeMapper::tryToPop() {
510 if (!Worklist.back().second) {
511 Worklist.back().second = true;
512 return false;
513 }
514
515 MDNode *N = Worklist.pop_back_val().first;
516 Info[N].ID = POT.size();
517 POT.push_back(N);
518 return true;
519}
520
521bool MDNodeMapper::createPOT(const MDNode &FirstN) {
522 bool AnyChanges = false;
523
524 // Do a traversal of the unmapped subgraph, tracking whether operands change.
525 // In some cases, these changes will propagate naturally, but
526 // propagateChangedOperands() catches the general case.
527 AnyChanges |= push(FirstN).HasChangedAddress;
528 while (hasWork()) {
529 if (tryToPop())
530 continue;
531
532 MDNode &N = getCurrentNode();
533 bool LocalChanges = false;
534 for (const Metadata *Op : N.operands())
535 LocalChanges |= mapOperand(Op);
536
537 if (!LocalChanges)
538 continue;
539
540 AnyChanges = true;
541 auto &D = Info[&N];
542 D.HasChangedOps = true;
543
544 // Uniqued nodes change address when operands change.
545 if (!N.isDistinct())
546 D.HasChangedAddress = true;
547 }
548 return AnyChanges;
549}
550
551void MDNodeMapper::propagateChangedOperands() {
552 bool AnyChangedAddresses;
553 do {
554 AnyChangedAddresses = false;
555 for (MDNode *N : POT) {
556 auto &NI = Info[N];
557 if (NI.HasChangedOps)
558 continue;
559
560 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
561 auto Where = Info.find(Op);
562 return Where != Info.end() && Where->second.HasChangedAddress;
563 }))
564 continue;
565
566 NI.HasChangedOps = true;
567 if (!N->isDistinct()) {
568 NI.HasChangedAddress = true;
569 AnyChangedAddresses = true;
570 }
571 }
572 } while (AnyChangedAddresses);
573}
574
575void MDNodeMapper::mapDistinctNodes() {
576 // Map all the distinct nodes in POT.
577 for (MDNode *N : POT) {
578 if (!N->isDistinct())
579 continue;
580
581 if (M.Flags & RF_MoveDistinctMDs)
582 M.mapToSelf(N);
583 else
584 M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
585 }
586}
587
588void MDNodeMapper::mapUniquedNodes() {
589 // Construct uniqued nodes, building forward references as necessary.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000590 SmallVector<MDNode *, 16> CyclicNodes;
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000591 for (auto *N : POT) {
592 if (N->isDistinct())
593 continue;
594
595 auto &D = Info[N];
596 assert(D.HasChangedAddress == D.HasChangedOps &&
597 "Uniqued nodes should change address iff ops change");
598 if (!D.HasChangedAddress) {
599 M.mapToSelf(N);
600 continue;
601 }
602
603 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
604 remapOperands(D, *ClonedN);
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000605 CyclicNodes.push_back(MDNode::replaceWithUniqued(std::move(ClonedN)));
606 M.mapToMetadata(N, CyclicNodes.back());
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000607 }
608
609 // Resolve cycles.
Duncan P. N. Exon Smith11f60fd2016-04-13 22:54:01 +0000610 for (auto *N : CyclicNodes)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000611 if (!N->isResolved())
612 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000613}
614
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000615void MDNodeMapper::remapDistinctOperands() {
616 for (auto *N : POT) {
617 if (!N->isDistinct())
618 continue;
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000619
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000620 auto &D = Info[N];
621 if (!D.HasChangedOps)
622 continue;
Duncan P. N. Exon Smith8c9dcac2015-08-07 00:44:55 +0000623
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000624 assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
625 "Distinct nodes should change address iff they cannot be moved");
626 remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000627 }
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000628}
629
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000630Metadata *MDNodeMapper::map(const MDNode &FirstN) {
631 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
632 "MDNodeMapper::map assumes module-level changes");
633 assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000634
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000635 // Require resolved nodes whenever metadata might be remapped.
636 assert(FirstN.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000637
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000638 // Return early if nothing at all changed.
639 if (!createPOT(FirstN)) {
640 for (const MDNode *N : POT)
641 M.mapToSelf(N);
642 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000643 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000644
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000645 propagateChangedOperands();
646 mapDistinctNodes();
647 mapUniquedNodes();
648 remapDistinctOperands();
649
650 // Return the original node, remapped.
651 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000652}
653
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000654Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000655 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000656 if (Optional<Metadata *> NewMD = VM.getMappedMD(MD))
657 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000658
659 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000660 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000661
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000662 // This is a module-level metadata. If nothing at the module level is
663 // changing, use an identity mapping.
664 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +0000665 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000666
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000667 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000668 // Disallow recursion into metadata mapping through mapValue.
669 VM.disableMapMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000670 Value *MappedV = mapValue(CMD->getValue());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000671 VM.enableMapMetadata();
672
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000673 if (CMD->getValue() == MappedV)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000674 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000675
Duncan P. N. Exon Smith8e65f8d2016-04-04 04:59:56 +0000676 return mapToMetadata(MD, MappedV ? ValueAsMetadata::get(MappedV) : nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000677 }
678
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000679 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000680
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000681 return None;
682}
683
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000684Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
685 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
686 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000687 return Mapper(VM, Flags, TypeMapper, Materializer).mapMetadata(MD);
688}
689
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000690Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
691 // Lookup the mapping for the value itself, and return the appropriate
692 // metadata.
693 if (Value *V = mapValue(LAM.getValue())) {
694 if (V == LAM.getValue())
695 return const_cast<LocalAsMetadata *>(&LAM);
696 return ValueAsMetadata::get(V);
697 }
698
699 // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
700 // metadata operands only reference defined SSA values.
701 return (Flags & RF_IgnoreMissingLocals)
702 ? nullptr
703 : MDTuple::get(LAM.getContext(), None);
704}
705
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000706Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000707 assert(MD && "Expected valid metadata");
708 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
709
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000710 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
711 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000712
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000713 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000714}
715
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000716Mapper::~Mapper() {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000717 // Materialize global initializers.
718 while (!DelayedInits.empty()) {
719 auto Init = DelayedInits.pop_back_val();
720 Materializer->materializeInitFor(Init.New, Init.Old);
721 }
722
723 // Process block addresses delayed until global inits.
724 while (!DelayedBBs.empty()) {
725 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
726 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
727 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
728 }
729
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000730 // We don't expect these to grow after clearing.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000731 assert(DelayedInits.empty());
732 assert(DelayedBBs.empty());
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000733}
734
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000735MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
736 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
737 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000738 return cast_or_null<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM,
739 Flags, TypeMapper, Materializer));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000740}
741
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000742void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VM,
James Molloyf6f121e2013-05-28 15:17:05 +0000743 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000744 ValueMaterializer *Materializer) {
745 Mapper(VM, Flags, TypeMapper, Materializer).remapInstruction(I);
746}
747
748void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanca26f792010-08-26 15:41:53 +0000749 // Remap operands.
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000750 for (Use &Op : I->operands()) {
751 Value *V = mapValue(Op);
Chris Lattner43f8d162011-01-08 08:15:20 +0000752 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000753 if (V)
Davide Italiano96d2a1c2016-04-14 18:07:32 +0000754 Op = V;
Chris Lattner43f8d162011-01-08 08:15:20 +0000755 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000756 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000757 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000758 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000759
Jay Foad61ea0e42011-06-23 09:09:15 +0000760 // Remap phi nodes' incoming blocks.
761 if (PHINode *PN = dyn_cast<PHINode>(I)) {
762 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smithadcebdf2016-04-08 19:17:13 +0000763 Value *V = mapValue(PN->getIncomingBlock(i));
Jay Foad61ea0e42011-06-23 09:09:15 +0000764 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000765 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000766 PN->setIncomingBlock(i, cast<BasicBlock>(V));
767 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000768 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000769 "Referenced block not in value map!");
770 }
771 }
772
Devang Patelc0174042011-08-04 20:02:18 +0000773 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000774 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000775 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000776 for (const auto &MI : MDs) {
777 MDNode *Old = MI.second;
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000778 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanca26f792010-08-26 15:41:53 +0000779 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000780 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000781 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000782
David Blaikie348de692015-04-23 21:36:23 +0000783 if (!TypeMapper)
784 return;
785
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000786 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000787 if (auto CS = CallSite(I)) {
788 SmallVector<Type *, 3> Tys;
789 FunctionType *FTy = CS.getFunctionType();
790 Tys.reserve(FTy->getNumParams());
791 for (Type *Ty : FTy->params())
792 Tys.push_back(TypeMapper->remapType(Ty));
793 CS.mutateFunctionType(FunctionType::get(
794 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000795 return;
796 }
797 if (auto *AI = dyn_cast<AllocaInst>(I))
798 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000799 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000800 GEP->setSourceElementType(
801 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000802 GEP->setResultElementType(
803 TypeMapper->remapType(GEP->getResultElementType()));
804 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000805 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000806}
Duncan P. N. Exon Smithbb2c3e12016-04-08 19:26:32 +0000807
808void llvm::RemapFunction(Function &F, ValueToValueMapTy &VM, RemapFlags Flags,
809 ValueMapTypeRemapper *TypeMapper,
810 ValueMaterializer *Materializer) {
811 Mapper(VM, Flags, TypeMapper, Materializer).remapFunction(F);
812}
813
814void Mapper::remapFunction(Function &F) {
815 // Remap the operands.
816 for (Use &Op : F.operands())
817 if (Op)
818 Op = mapValue(Op);
819
820 // Remap the metadata attachments.
821 SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
822 F.getAllMetadata(MDs);
823 for (const auto &I : MDs)
824 F.setMetadata(I.first, cast_or_null<MDNode>(mapMetadata(I.second)));
825
826 // Remap the argument types.
827 if (TypeMapper)
828 for (Argument &A : F.args())
829 A.mutateType(TypeMapper->remapType(A.getType()));
830
831 // Remap the instructions.
832 for (BasicBlock &BB : F)
833 for (Instruction &I : BB)
834 remapInstruction(&I);
835}