blob: ffd3a274cdea3c04ac7b64c94e3dc06aa82acdd7 [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 Smith829dc872016-04-03 19:06:24 +000083
84 /// Map metadata.
85 ///
86 /// Find the mapping for MD. Guarantees that the return will be resolved
87 /// (not an MDNode, or MDNode::isResolved() returns true).
88 Metadata *mapMetadata(const Metadata *MD);
89
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +000090 // Map LocalAsMetadata, which never gets memoized.
91 //
92 // If the referenced local is not mapped, the principled return is nullptr.
93 // However, optimization passes sometimes move metadata operands *before* the
94 // SSA values they reference. To prevent crashes in \a RemapInstruction(),
95 // return "!{}" when RF_IgnoreMissingLocals is not set.
96 //
97 // \note Adding a mapping for LocalAsMetadata is unsupported. Add a mapping
98 // to the value map for the SSA value in question instead.
99 //
100 // FIXME: Once we have a verifier check for forward references to SSA values
101 // through metadata operands, always return nullptr on unmapped locals.
102 Metadata *mapLocalAsMetadata(const LocalAsMetadata &LAM);
103
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000104private:
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000105 Value *mapBlockAddress(const BlockAddress &BA);
106
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000107 /// Map metadata that doesn't require visiting operands.
108 Optional<Metadata *> mapSimpleMetadata(const Metadata *MD);
109
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000110 Metadata *mapToMetadata(const Metadata *Key, Metadata *Val);
111 Metadata *mapToSelf(const Metadata *MD);
112};
113
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000114class MDNodeMapper {
115 Mapper &M;
116
117 struct Data {
118 bool HasChangedOps = false;
119 bool HasChangedAddress = false;
120 unsigned ID = ~0u;
121 TempMDNode Placeholder;
Duncan P. N. Exon Smithf880d352016-04-05 21:07:01 +0000122
Duncan P. N. Exon Smith818e5f32016-04-05 21:25:33 +0000123 Data() {}
124 Data(Data &&X)
125 : HasChangedOps(std::move(X.HasChangedOps)),
126 HasChangedAddress(std::move(X.HasChangedAddress)),
127 ID(std::move(X.ID)), Placeholder(std::move(X.Placeholder)) {}
128 Data &operator=(Data &&X) {
129 HasChangedOps = std::move(X.HasChangedOps);
130 HasChangedAddress = std::move(X.HasChangedAddress);
131 ID = std::move(X.ID);
132 Placeholder = std::move(X.Placeholder);
133 return *this;
134 }
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000135 };
136
137 SmallDenseMap<const Metadata *, Data, 32> Info;
138 SmallVector<std::pair<MDNode *, bool>, 16> Worklist;
139 SmallVector<MDNode *, 16> POT;
140
141public:
142 MDNodeMapper(Mapper &M) : M(M) {}
143
144 /// Map a metadata node (and its transitive operands).
145 ///
146 /// This is the only entry point into MDNodeMapper. It works as follows:
147 ///
148 /// 1. \a createPOT(): use a worklist to perform a post-order traversal of
149 /// the transitively referenced unmapped nodes.
150 ///
151 /// 2. \a propagateChangedOperands(): track which nodes will change
152 /// operands, and which will have new addresses in the mapped scheme.
153 /// Propagate the changes through the POT until fixed point, to pick up
154 /// uniquing cycles that need to change.
155 ///
156 /// 3. \a mapDistinctNodes(): map all the distinct nodes without touching
157 /// their operands. If RF_MoveDistinctMetadata, they get mapped to
158 /// themselves; otherwise, they get mapped to clones.
159 ///
160 /// 4. \a mapUniquedNodes(): map the uniqued nodes (bottom-up), lazily
161 /// creating temporaries for forward references as needed.
162 ///
163 /// 5. \a remapDistinctOperands(): remap the operands of the distinct nodes.
164 Metadata *map(const MDNode &FirstN);
165
166private:
167 /// Return \c true as long as there's work to do.
168 bool hasWork() const { return !Worklist.empty(); }
169
170 /// Get the current node in the worklist.
171 MDNode &getCurrentNode() const { return *Worklist.back().first; }
172
173 /// Push a node onto the worklist.
174 ///
175 /// Adds \c N to \a Worklist and \a Info, unless it's already inserted. If
176 /// \c N.isDistinct(), \a Data::HasChangedAddress will be set based on \a
177 /// RF_MoveDistinctMDs.
178 ///
179 /// Returns the data for the node.
180 ///
181 /// \post Data::HasChangedAddress iff !RF_MoveDistinctMDs && N.isDistinct().
182 /// \post Worklist.back().first == &N.
183 /// \post Worklist.back().second == false.
184 Data &push(const MDNode &N);
185
186 /// Map a node operand, and return true if it changes.
187 ///
188 /// \post getMappedOp(Op) does not return None.
189 bool mapOperand(const Metadata *Op);
190
191 /// Get a previously mapped node.
192 Optional<Metadata *> getMappedOp(const Metadata *Op) const;
193
194 /// Try to pop a node off the worklist and store it in POT.
195 ///
196 /// Returns \c true if it popped; \c false if its operands need to be
197 /// visited.
198 ///
199 /// \post If Worklist.back().second == false: Worklist.back().second == true.
200 /// \post Else: Worklist.back() has been popped off and added to \a POT.
201 bool tryToPop();
202
203 /// Get a forward reference to a node to use as an operand.
204 ///
205 /// Returns \c Op if it's not changing; otherwise, lazily creates a temporary
206 /// node and returns it.
207 Metadata &getFwdReference(const Data &D, MDNode &Op);
208
209 /// Create a post-order traversal from the given node.
210 ///
211 /// This traverses the metadata graph deeply enough to map \c FirstN. It
212 /// uses \a mapOperand() (indirectly, \a Mapper::mapSimplifiedNode()), so any
213 /// metadata that has already been mapped will not be part of the POT.
214 ///
215 /// \post \a POT is a post-order traversal ending with \c FirstN.
216 bool createPOT(const MDNode &FirstN);
217
218 /// Propagate changed operands through post-order traversal.
219 ///
220 /// Until fixed point, iteratively update:
221 ///
222 /// - \a Data::HasChangedOps based on \a Data::HasChangedAddress of operands;
223 /// - \a Data::HasChangedAddress based on Data::HasChangedOps.
224 ///
225 /// This algorithm never changes \a Data::HasChangedAddress for distinct
226 /// nodes.
227 ///
228 /// \post \a POT is a post-order traversal ending with \c FirstN.
229 void propagateChangedOperands();
230
231 /// Map all distinct nodes in POT.
232 ///
233 /// \post \a getMappedOp() returns the correct node for every distinct node.
234 void mapDistinctNodes();
235
236 /// Map all uniqued nodes in POT with the correct operands.
237 ///
238 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
239 /// \post \a getMappedOp() returns the correct node for every node.
240 /// \post \a MDNode::operands() is correct for every uniqued node.
241 /// \post \a MDNode::isResolved() returns true for every node.
242 void mapUniquedNodes();
243
244 /// Re-map the operands for distinct nodes in POT.
245 ///
246 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
247 /// \pre Uniqued nodes are mapped (\a mapUniquedNodes() has been called).
248 /// \post \a MDNode::operands() is correct for every distinct node.
249 void remapDistinctOperands();
250
251 /// Remap a node's operands.
252 ///
253 /// Iterate through operands and update them in place using \a getMappedOp()
254 /// and \a getFwdReference().
255 ///
256 /// \pre N.isDistinct() or N.isTemporary().
257 /// \pre Distinct nodes are mapped (\a mapDistinctNodes() has been called).
258 /// \pre If \c N is distinct, all uniqued nodes are already mapped.
259 void remapOperands(const Data &D, MDNode &N);
260};
261
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000262} // end namespace
263
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000264Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
James Molloyf6f121e2013-05-28 15:17:05 +0000265 ValueMapTypeRemapper *TypeMapper,
266 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000267 return Mapper(VM, Flags, TypeMapper, Materializer).mapValue(V);
268}
269
270Value *Mapper::mapValue(const Value *V) {
Chris Lattner43f8d162011-01-08 08:15:20 +0000271 ValueToValueMapTy::iterator I = VM.find(V);
Chris Lattner1bfc7ab2007-02-03 00:08:31 +0000272
Chris Lattner43f8d162011-01-08 08:15:20 +0000273 // If the value already exists in the map, use it.
274 if (I != VM.end() && I->second) return I->second;
275
James Molloyf6f121e2013-05-28 15:17:05 +0000276 // If we have a materializer and it can materialize a value, use that.
277 if (Materializer) {
Rafael Espindola19b52382015-11-27 20:28:19 +0000278 if (Value *NewV =
279 Materializer->materializeDeclFor(const_cast<Value *>(V))) {
280 VM[V] = NewV;
Rafael Espindolabaa3bf82015-12-01 15:19:48 +0000281 if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000282 DelayedInits.push_back(
283 DelayedGlobalValueInit(cast<GlobalValue>(V), NewGV));
Rafael Espindola19b52382015-11-27 20:28:19 +0000284 return NewV;
285 }
James Molloyf6f121e2013-05-28 15:17:05 +0000286 }
287
Dan Gohmanca26f792010-08-26 15:41:53 +0000288 // Global values do not need to be seeded into the VM if they
289 // are using the identity mapping.
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000290 if (isa<GlobalValue>(V)) {
Duncan P. N. Exon Smithfdccad92016-04-07 01:22:45 +0000291 if (Flags & RF_NullMapMissingGlobalValues)
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000292 return nullptr;
Chris Lattner43f8d162011-01-08 08:15:20 +0000293 return VM[V] = const_cast<Value*>(V);
Teresa Johnson83d03dd2015-11-15 14:50:14 +0000294 }
295
Chris Lattner8b4cf5e2011-07-15 23:18:40 +0000296 if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
297 // Inline asm may need *type* remapping.
298 FunctionType *NewTy = IA->getFunctionType();
299 if (TypeMapper) {
300 NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
301
302 if (NewTy != IA->getFunctionType())
303 V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
304 IA->hasSideEffects(), IA->isAlignStack());
305 }
306
307 return VM[V] = const_cast<Value*>(V);
308 }
Chris Lattner6aa34b02003-10-06 15:23:43 +0000309
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000310 if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
311 const Metadata *MD = MDV->getMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000312
313 if (auto *LAM = dyn_cast<LocalAsMetadata>(MD)) {
314 // Look through to grab the local value.
315 if (Value *LV = mapValue(LAM->getValue())) {
316 if (V == LAM->getValue())
317 return const_cast<Value *>(V);
318 return MetadataAsValue::get(V->getContext(), ValueAsMetadata::get(LV));
319 }
320
321 // FIXME: always return nullptr once Verifier::verifyDominatesUse()
322 // ensures metadata operands only reference defined SSA values.
323 return (Flags & RF_IgnoreMissingLocals)
324 ? nullptr
325 : MetadataAsValue::get(V->getContext(),
326 MDTuple::get(V->getContext(), None));
327 }
328
Chris Lattner43f8d162011-01-08 08:15:20 +0000329 // If this is a module-level metadata and we know that nothing at the module
330 // level is changing, then use an identity mapping.
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000331 if (Flags & RF_NoModuleLevelChanges)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000332 return VM[V] = const_cast<Value *>(V);
Dan Gohmanca26f792010-08-26 15:41:53 +0000333
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000334 // Map the metadata and turn it into a value.
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000335 auto *MappedMD = mapMetadata(MD);
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000336 if (MD == MappedMD)
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000337 return VM[V] = const_cast<Value *>(V);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000338 return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
Victor Hernandez5fa88d42010-01-20 05:49:59 +0000339 }
340
Chris Lattner43f8d162011-01-08 08:15:20 +0000341 // Okay, this either must be a constant (which may or may not be mappable) or
342 // is something that is not in the mapping table.
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000343 Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
Craig Topperf40110f2014-04-25 05:29:35 +0000344 if (!C)
345 return nullptr;
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000346
347 if (BlockAddress *BA = dyn_cast<BlockAddress>(C))
348 return mapBlockAddress(*BA);
349
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000350 // Otherwise, we have some other constant to remap. Start by checking to see
351 // if all operands have an identity remapping.
352 unsigned OpNo = 0, NumOperands = C->getNumOperands();
Craig Topperf40110f2014-04-25 05:29:35 +0000353 Value *Mapped = nullptr;
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000354 for (; OpNo != NumOperands; ++OpNo) {
355 Value *Op = C->getOperand(OpNo);
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000356 Mapped = mapValue(Op);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000357 if (Mapped != C) break;
Chris Lattnercf5a47d2009-10-29 00:28:30 +0000358 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000359
360 // See if the type mapper wants to remap the type as well.
361 Type *NewTy = C->getType();
362 if (TypeMapper)
363 NewTy = TypeMapper->remapType(NewTy);
Chris Lattner43f8d162011-01-08 08:15:20 +0000364
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000365 // If the result type and all operands match up, then just insert an identity
366 // mapping.
367 if (OpNo == NumOperands && NewTy == C->getType())
368 return VM[V] = C;
369
370 // Okay, we need to create a new constant. We've already processed some or
371 // all of the operands, set them all up now.
372 SmallVector<Constant*, 8> Ops;
373 Ops.reserve(NumOperands);
374 for (unsigned j = 0; j != OpNo; ++j)
375 Ops.push_back(cast<Constant>(C->getOperand(j)));
376
377 // If one of the operands mismatch, push it and the other mapped operands.
378 if (OpNo != NumOperands) {
379 Ops.push_back(cast<Constant>(Mapped));
380
381 // Map the rest of the operands that aren't processed yet.
382 for (++OpNo; OpNo != NumOperands; ++OpNo)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000383 Ops.push_back(cast<Constant>(mapValue(C->getOperand(OpNo))));
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000384 }
David Blaikie88208842015-08-21 20:16:51 +0000385 Type *NewSrcTy = nullptr;
386 if (TypeMapper)
387 if (auto *GEPO = dyn_cast<GEPOperator>(C))
388 NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
389
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000390 if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
David Blaikie88208842015-08-21 20:16:51 +0000391 return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000392 if (isa<ConstantArray>(C))
393 return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
394 if (isa<ConstantStruct>(C))
395 return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
396 if (isa<ConstantVector>(C))
397 return VM[V] = ConstantVector::get(Ops);
398 // If this is a no-operand constant, it must be because the type was remapped.
399 if (isa<UndefValue>(C))
400 return VM[V] = UndefValue::get(NewTy);
401 if (isa<ConstantAggregateZero>(C))
402 return VM[V] = ConstantAggregateZero::get(NewTy);
403 assert(isa<ConstantPointerNull>(C));
404 return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
Chris Lattnere4dbb1a2002-11-20 20:47:41 +0000405}
Brian Gaeke6182acf2004-05-19 09:08:12 +0000406
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000407Value *Mapper::mapBlockAddress(const BlockAddress &BA) {
408 Function *F = cast<Function>(mapValue(BA.getFunction()));
409
410 // F may not have materialized its initializer. In that case, create a
411 // dummy basic block for now, and replace it once we've materialized all
412 // the initializers.
413 BasicBlock *BB;
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000414 if (F->empty()) {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000415 DelayedBBs.push_back(DelayedBasicBlock(BA));
416 BB = DelayedBBs.back().TempBB.get();
Duncan P. N. Exon Smith6f2e3742016-04-06 02:25:12 +0000417 } else {
418 BB = cast_or_null<BasicBlock>(mapValue(BA.getBasicBlock()));
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000419 }
420
421 return VM[&BA] = BlockAddress::get(F, BB ? BB : BA.getBasicBlock());
422}
423
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000424Metadata *Mapper::mapToMetadata(const Metadata *Key, Metadata *Val) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000425 VM.MD()[Key].reset(Val);
426 return Val;
427}
428
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000429Metadata *Mapper::mapToSelf(const Metadata *MD) {
430 return mapToMetadata(MD, const_cast<Metadata *>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000431}
432
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000433bool MDNodeMapper::mapOperand(const Metadata *Op) {
434 if (!Op)
435 return false;
436
437 if (Optional<Metadata *> MappedOp = M.mapSimpleMetadata(Op)) {
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000438 assert((isa<MDString>(Op) || M.VM.getMappedMD(Op)) &&
439 "Expected result to be memoized");
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000440 return *MappedOp != Op;
441 }
442
443 return push(*cast<MDNode>(Op)).HasChangedAddress;
444}
445
446Optional<Metadata *> MDNodeMapper::getMappedOp(const Metadata *Op) const {
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000447 if (!Op)
448 return nullptr;
Teresa Johnson0e7c82c2015-12-18 17:51:37 +0000449
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000450 if (Optional<Metadata *> MappedOp = M.VM.getMappedMD(Op))
451 return *MappedOp;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000452
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000453 if (isa<MDString>(Op))
454 return const_cast<Metadata *>(Op);
455
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000456 return None;
Duncan P. N. Exon Smith077affd2015-01-14 01:01:19 +0000457}
458
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000459Metadata &MDNodeMapper::getFwdReference(const Data &D, MDNode &Op) {
460 auto Where = Info.find(&Op);
461 assert(Where != Info.end() && "Expected a valid reference");
462
463 auto &OpD = Where->second;
464 assert(OpD.ID > D.ID && "Expected a forward reference");
465
466 if (!OpD.HasChangedAddress)
467 return Op;
468
469 // Lazily construct a temporary node.
470 if (!OpD.Placeholder)
471 OpD.Placeholder = Op.clone();
472
473 return *OpD.Placeholder;
474}
475
476void MDNodeMapper::remapOperands(const Data &D, MDNode &N) {
477 for (unsigned I = 0, E = N.getNumOperands(); I != E; ++I) {
478 Metadata *Old = N.getOperand(I);
479 Metadata *New;
480 if (Optional<Metadata *> MappedOp = getMappedOp(Old)){
481 New = *MappedOp;
482 } else {
483 assert(!N.isDistinct() &&
484 "Expected all nodes to be pre-mapped for distinct operands");
485 MDNode &OldN = *cast<MDNode>(Old);
486 assert(!OldN.isDistinct() && "Expected distinct nodes to be pre-mapped");
487 New = &getFwdReference(D, OldN);
488 }
489
490 if (Old != New)
491 N.replaceOperandWith(I, New);
492 }
493}
494
495MDNodeMapper::Data &MDNodeMapper::push(const MDNode &N) {
496 auto Insertion = Info.insert(std::make_pair(&N, Data()));
497 auto &D = Insertion.first->second;
498 if (!Insertion.second)
499 return D;
500
501 // Add to the worklist; check for distinct nodes that are required to be
502 // copied.
503 Worklist.push_back(std::make_pair(&const_cast<MDNode &>(N), false));
504 D.HasChangedAddress = !(M.Flags & RF_MoveDistinctMDs) && N.isDistinct();
505 return D;
506}
507
508bool MDNodeMapper::tryToPop() {
509 if (!Worklist.back().second) {
510 Worklist.back().second = true;
511 return false;
512 }
513
514 MDNode *N = Worklist.pop_back_val().first;
515 Info[N].ID = POT.size();
516 POT.push_back(N);
517 return true;
518}
519
520bool MDNodeMapper::createPOT(const MDNode &FirstN) {
521 bool AnyChanges = false;
522
523 // Do a traversal of the unmapped subgraph, tracking whether operands change.
524 // In some cases, these changes will propagate naturally, but
525 // propagateChangedOperands() catches the general case.
526 AnyChanges |= push(FirstN).HasChangedAddress;
527 while (hasWork()) {
528 if (tryToPop())
529 continue;
530
531 MDNode &N = getCurrentNode();
532 bool LocalChanges = false;
533 for (const Metadata *Op : N.operands())
534 LocalChanges |= mapOperand(Op);
535
536 if (!LocalChanges)
537 continue;
538
539 AnyChanges = true;
540 auto &D = Info[&N];
541 D.HasChangedOps = true;
542
543 // Uniqued nodes change address when operands change.
544 if (!N.isDistinct())
545 D.HasChangedAddress = true;
546 }
547 return AnyChanges;
548}
549
550void MDNodeMapper::propagateChangedOperands() {
551 bool AnyChangedAddresses;
552 do {
553 AnyChangedAddresses = false;
554 for (MDNode *N : POT) {
555 auto &NI = Info[N];
556 if (NI.HasChangedOps)
557 continue;
558
559 if (!llvm::any_of(N->operands(), [&](const Metadata *Op) {
560 auto Where = Info.find(Op);
561 return Where != Info.end() && Where->second.HasChangedAddress;
562 }))
563 continue;
564
565 NI.HasChangedOps = true;
566 if (!N->isDistinct()) {
567 NI.HasChangedAddress = true;
568 AnyChangedAddresses = true;
569 }
570 }
571 } while (AnyChangedAddresses);
572}
573
574void MDNodeMapper::mapDistinctNodes() {
575 // Map all the distinct nodes in POT.
576 for (MDNode *N : POT) {
577 if (!N->isDistinct())
578 continue;
579
580 if (M.Flags & RF_MoveDistinctMDs)
581 M.mapToSelf(N);
582 else
583 M.mapToMetadata(N, MDNode::replaceWithDistinct(N->clone()));
584 }
585}
586
587void MDNodeMapper::mapUniquedNodes() {
588 // Construct uniqued nodes, building forward references as necessary.
589 for (auto *N : POT) {
590 if (N->isDistinct())
591 continue;
592
593 auto &D = Info[N];
594 assert(D.HasChangedAddress == D.HasChangedOps &&
595 "Uniqued nodes should change address iff ops change");
596 if (!D.HasChangedAddress) {
597 M.mapToSelf(N);
598 continue;
599 }
600
601 TempMDNode ClonedN = D.Placeholder ? std::move(D.Placeholder) : N->clone();
602 remapOperands(D, *ClonedN);
603 M.mapToMetadata(N, MDNode::replaceWithUniqued(std::move(ClonedN)));
604 }
605
606 // Resolve cycles.
607 for (auto *N : POT)
Teresa Johnsonb703c772016-03-29 18:24:19 +0000608 if (!N->isResolved())
609 N->resolveCycles();
Duncan P. N. Exon Smithc9fdbdb2015-08-07 00:39:26 +0000610}
611
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000612void MDNodeMapper::remapDistinctOperands() {
613 for (auto *N : POT) {
614 if (!N->isDistinct())
615 continue;
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000616
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000617 auto &D = Info[N];
618 if (!D.HasChangedOps)
619 continue;
Duncan P. N. Exon Smith8c9dcac2015-08-07 00:44:55 +0000620
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000621 assert(D.HasChangedAddress == !bool(M.Flags & RF_MoveDistinctMDs) &&
622 "Distinct nodes should change address iff they cannot be moved");
623 remapOperands(D, D.HasChangedAddress ? *cast<MDNode>(*getMappedOp(N)) : *N);
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000624 }
Duncan P. N. Exon Smith6dc22bf2015-01-19 22:44:32 +0000625}
626
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000627Metadata *MDNodeMapper::map(const MDNode &FirstN) {
628 assert(!(M.Flags & RF_NoModuleLevelChanges) &&
629 "MDNodeMapper::map assumes module-level changes");
630 assert(POT.empty() && "MDNodeMapper::map is not re-entrant");
Duncan P. N. Exon Smith14cc94c2015-01-14 01:03:05 +0000631
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000632 // Require resolved nodes whenever metadata might be remapped.
633 assert(FirstN.isResolved() && "Unexpected unresolved node");
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000634
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000635 // Return early if nothing at all changed.
636 if (!createPOT(FirstN)) {
637 for (const MDNode *N : POT)
638 M.mapToSelf(N);
639 return &const_cast<MDNode &>(FirstN);
Duncan P. N. Exon Smith706f37e2015-08-04 06:42:31 +0000640 }
Duncan P. N. Exon Smith0dcffe22015-01-19 22:39:07 +0000641
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000642 propagateChangedOperands();
643 mapDistinctNodes();
644 mapUniquedNodes();
645 remapDistinctOperands();
646
647 // Return the original node, remapped.
648 return *getMappedOp(&FirstN);
Duncan P. N. Exon Smithb5579892015-01-14 01:06:21 +0000649}
650
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000651Optional<Metadata *> Mapper::mapSimpleMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000652 // If the value already exists in the map, use it.
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000653 if (Optional<Metadata *> NewMD = VM.getMappedMD(MD))
654 return *NewMD;
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000655
656 if (isa<MDString>(MD))
Duncan P. N. Exon Smithe05ff7c2016-04-08 18:47:02 +0000657 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000658
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000659 // This is a module-level metadata. If nothing at the module level is
660 // changing, use an identity mapping.
661 if ((Flags & RF_NoModuleLevelChanges))
Duncan P. N. Exon Smith69341e62016-04-08 18:49:36 +0000662 return const_cast<Metadata *>(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000663
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000664 if (auto *CMD = dyn_cast<ConstantAsMetadata>(MD)) {
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000665 // Disallow recursion into metadata mapping through mapValue.
666 VM.disableMapMetadata();
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000667 Value *MappedV = mapValue(CMD->getValue());
Duncan P. N. Exon Smith756e1c32016-04-03 20:54:51 +0000668 VM.enableMapMetadata();
669
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000670 if (CMD->getValue() == MappedV)
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000671 return mapToSelf(MD);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000672
Duncan P. N. Exon Smith8e65f8d2016-04-04 04:59:56 +0000673 return mapToMetadata(MD, MappedV ? ValueAsMetadata::get(MappedV) : nullptr);
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000674 }
675
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000676 assert(isa<MDNode>(MD) && "Expected a metadata node");
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000677
Duncan P. N. Exon Smithae8bd4b2016-04-03 19:31:01 +0000678 return None;
679}
680
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000681Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
682 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
683 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000684 return Mapper(VM, Flags, TypeMapper, Materializer).mapMetadata(MD);
685}
686
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000687Metadata *Mapper::mapLocalAsMetadata(const LocalAsMetadata &LAM) {
688 // Lookup the mapping for the value itself, and return the appropriate
689 // metadata.
690 if (Value *V = mapValue(LAM.getValue())) {
691 if (V == LAM.getValue())
692 return const_cast<LocalAsMetadata *>(&LAM);
693 return ValueAsMetadata::get(V);
694 }
695
696 // FIXME: always return nullptr once Verifier::verifyDominatesUse() ensures
697 // metadata operands only reference defined SSA values.
698 return (Flags & RF_IgnoreMissingLocals)
699 ? nullptr
700 : MDTuple::get(LAM.getContext(), None);
701}
702
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000703Metadata *Mapper::mapMetadata(const Metadata *MD) {
Duncan P. N. Exon Smith4ec55f82016-04-08 03:13:22 +0000704 assert(MD && "Expected valid metadata");
705 assert(!isa<LocalAsMetadata>(MD) && "Unexpected local metadata");
706
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000707 if (Optional<Metadata *> NewMD = mapSimpleMetadata(MD))
708 return *NewMD;
Duncan P. N. Exon Smith920df5c2015-02-04 19:44:34 +0000709
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000710 return MDNodeMapper(*this).map(*cast<MDNode>(MD));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000711}
712
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000713Mapper::~Mapper() {
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000714 // Materialize global initializers.
715 while (!DelayedInits.empty()) {
716 auto Init = DelayedInits.pop_back_val();
717 Materializer->materializeInitFor(Init.New, Init.Old);
718 }
719
720 // Process block addresses delayed until global inits.
721 while (!DelayedBBs.empty()) {
722 DelayedBasicBlock DBB = DelayedBBs.pop_back_val();
723 BasicBlock *BB = cast_or_null<BasicBlock>(mapValue(DBB.OldBB));
724 DBB.TempBB->replaceAllUsesWith(BB ? BB : DBB.OldBB);
725 }
726
Duncan P. N. Exon Smithea7df772016-04-05 20:23:21 +0000727 // We don't expect these to grow after clearing.
Duncan P. N. Exon Smithc6065e32016-04-03 20:17:45 +0000728 assert(DelayedInits.empty());
729 assert(DelayedBBs.empty());
Duncan P. N. Exon Smith829dc872016-04-03 19:06:24 +0000730}
731
Duncan P. N. Exon Smith46d7af52014-12-19 06:06:18 +0000732MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
733 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
734 ValueMaterializer *Materializer) {
Duncan P. N. Exon Smithda4a56d2016-04-02 17:04:38 +0000735 return cast_or_null<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM,
736 Flags, TypeMapper, Materializer));
Duncan P. N. Exon Smith5bf8fef2014-12-09 18:38:53 +0000737}
738
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000739void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VM,
James Molloyf6f121e2013-05-28 15:17:05 +0000740 RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000741 ValueMaterializer *Materializer) {
742 Mapper(VM, Flags, TypeMapper, Materializer).remapInstruction(I);
743}
744
745void Mapper::remapInstruction(Instruction *I) {
Dan Gohmanca26f792010-08-26 15:41:53 +0000746 // Remap operands.
Gabor Greif5df43262008-05-30 21:24:22 +0000747 for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000748 Value *V = mapValue(*op);
Chris Lattner43f8d162011-01-08 08:15:20 +0000749 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000750 if (V)
Chris Lattner43f8d162011-01-08 08:15:20 +0000751 *op = V;
752 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000753 assert((Flags & RF_IgnoreMissingLocals) &&
Chris Lattner43f8d162011-01-08 08:15:20 +0000754 "Referenced value not in value map!");
Brian Gaeke6182acf2004-05-19 09:08:12 +0000755 }
Daniel Dunbar95fe13c2010-08-26 03:48:08 +0000756
Jay Foad61ea0e42011-06-23 09:09:15 +0000757 // Remap phi nodes' incoming blocks.
758 if (PHINode *PN = dyn_cast<PHINode>(I)) {
759 for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000760 // FIXME: Use Mapper::mapValue (but note the missing Materializer flag).
761 Value *V = MapValue(PN->getIncomingBlock(i), VM, Flags);
Jay Foad61ea0e42011-06-23 09:09:15 +0000762 // If we aren't ignoring missing entries, assert that something happened.
Craig Topperf40110f2014-04-25 05:29:35 +0000763 if (V)
Jay Foad61ea0e42011-06-23 09:09:15 +0000764 PN->setIncomingBlock(i, cast<BasicBlock>(V));
765 else
Duncan P. N. Exon Smithda68cbc2016-04-07 00:26:43 +0000766 assert((Flags & RF_IgnoreMissingLocals) &&
Jay Foad61ea0e42011-06-23 09:09:15 +0000767 "Referenced block not in value map!");
768 }
769 }
770
Devang Patelc0174042011-08-04 20:02:18 +0000771 // Remap attached metadata.
Duncan P. N. Exon Smithde36e802014-11-11 21:30:22 +0000772 SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
Devang Patelc0174042011-08-04 20:02:18 +0000773 I->getAllMetadata(MDs);
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000774 for (const auto &MI : MDs) {
775 MDNode *Old = MI.second;
Duncan P. N. Exon Smitha574e7a2016-04-08 19:09:34 +0000776 MDNode *New = cast_or_null<MDNode>(mapMetadata(Old));
Dan Gohmanca26f792010-08-26 15:41:53 +0000777 if (New != Old)
Duncan P. N. Exon Smithe08bcbf2015-08-03 03:27:12 +0000778 I->setMetadata(MI.first, New);
Dan Gohmanca26f792010-08-26 15:41:53 +0000779 }
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000780
David Blaikie348de692015-04-23 21:36:23 +0000781 if (!TypeMapper)
782 return;
783
Chris Lattnerb1ed91f2011-07-09 17:41:24 +0000784 // If the instruction's type is being remapped, do so now.
David Blaikie348de692015-04-23 21:36:23 +0000785 if (auto CS = CallSite(I)) {
786 SmallVector<Type *, 3> Tys;
787 FunctionType *FTy = CS.getFunctionType();
788 Tys.reserve(FTy->getNumParams());
789 for (Type *Ty : FTy->params())
790 Tys.push_back(TypeMapper->remapType(Ty));
791 CS.mutateFunctionType(FunctionType::get(
792 TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
David Blaikiebf0a42a2015-04-29 23:00:35 +0000793 return;
794 }
795 if (auto *AI = dyn_cast<AllocaInst>(I))
796 AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000797 if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
David Blaikie73cf8722015-05-05 18:03:48 +0000798 GEP->setSourceElementType(
799 TypeMapper->remapType(GEP->getSourceElementType()));
David Blaikief5147ef2015-06-01 03:09:34 +0000800 GEP->setResultElementType(
801 TypeMapper->remapType(GEP->getResultElementType()));
802 }
David Blaikiebf0a42a2015-04-29 23:00:35 +0000803 I->mutateType(TypeMapper->remapType(I->getType()));
Dan Gohmanca26f792010-08-26 15:41:53 +0000804}