414d4eaa68dedeb499c25e76336a244e3d2fab3a
[oota-llvm.git] / lib / Transforms / Utils / ValueMapper.cpp
1 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the MapValue function, which is shared by various parts of
11 // the lib/Transforms/Utils library.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm/Transforms/Utils/ValueMapper.h"
16 #include "llvm/IR/CallSite.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/Function.h"
19 #include "llvm/IR/InlineAsm.h"
20 #include "llvm/IR/Instructions.h"
21 #include "llvm/IR/Metadata.h"
22 #include "llvm/IR/Operator.h"
23 using namespace llvm;
24
25 // Out of line method to get vtable etc for class.
26 void ValueMapTypeRemapper::anchor() {}
27 void ValueMaterializer::anchor() {}
28
29 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
30                       ValueMapTypeRemapper *TypeMapper,
31                       ValueMaterializer *Materializer) {
32   ValueToValueMapTy::iterator I = VM.find(V);
33   
34   // If the value already exists in the map, use it.
35   if (I != VM.end() && I->second) return I->second;
36   
37   // If we have a materializer and it can materialize a value, use that.
38   if (Materializer) {
39     if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
40       return VM[V] = NewV;
41   }
42
43   // Global values do not need to be seeded into the VM if they
44   // are using the identity mapping.
45   if (isa<GlobalValue>(V))
46     return VM[V] = const_cast<Value*>(V);
47   
48   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
49     // Inline asm may need *type* remapping.
50     FunctionType *NewTy = IA->getFunctionType();
51     if (TypeMapper) {
52       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
53
54       if (NewTy != IA->getFunctionType())
55         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
56                            IA->hasSideEffects(), IA->isAlignStack());
57     }
58     
59     return VM[V] = const_cast<Value*>(V);
60   }
61
62   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
63     const Metadata *MD = MDV->getMetadata();
64     // If this is a module-level metadata and we know that nothing at the module
65     // level is changing, then use an identity mapping.
66     if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
67       return VM[V] = const_cast<Value *>(V);
68
69     auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
70     if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
71       return VM[V] = const_cast<Value *>(V);
72
73     // FIXME: This assert crashes during bootstrap, but I think it should be
74     // correct.  For now, just match behaviour from before the metadata/value
75     // split.
76     //
77     //    assert(MappedMD && "Referenced metadata value not in value map");
78     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
79   }
80
81   // Okay, this either must be a constant (which may or may not be mappable) or
82   // is something that is not in the mapping table.
83   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
84   if (!C)
85     return nullptr;
86   
87   if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
88     Function *F = 
89       cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
90     BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
91                                                        Flags, TypeMapper, Materializer));
92     return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
93   }
94   
95   // Otherwise, we have some other constant to remap.  Start by checking to see
96   // if all operands have an identity remapping.
97   unsigned OpNo = 0, NumOperands = C->getNumOperands();
98   Value *Mapped = nullptr;
99   for (; OpNo != NumOperands; ++OpNo) {
100     Value *Op = C->getOperand(OpNo);
101     Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
102     if (Mapped != C) break;
103   }
104   
105   // See if the type mapper wants to remap the type as well.
106   Type *NewTy = C->getType();
107   if (TypeMapper)
108     NewTy = TypeMapper->remapType(NewTy);
109
110   // If the result type and all operands match up, then just insert an identity
111   // mapping.
112   if (OpNo == NumOperands && NewTy == C->getType())
113     return VM[V] = C;
114   
115   // Okay, we need to create a new constant.  We've already processed some or
116   // all of the operands, set them all up now.
117   SmallVector<Constant*, 8> Ops;
118   Ops.reserve(NumOperands);
119   for (unsigned j = 0; j != OpNo; ++j)
120     Ops.push_back(cast<Constant>(C->getOperand(j)));
121   
122   // If one of the operands mismatch, push it and the other mapped operands.
123   if (OpNo != NumOperands) {
124     Ops.push_back(cast<Constant>(Mapped));
125   
126     // Map the rest of the operands that aren't processed yet.
127     for (++OpNo; OpNo != NumOperands; ++OpNo)
128       Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
129                              Flags, TypeMapper, Materializer));
130   }
131   Type *NewSrcTy = nullptr;
132   if (TypeMapper)
133     if (auto *GEPO = dyn_cast<GEPOperator>(C))
134       NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
135
136   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
137     return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
138   if (isa<ConstantArray>(C))
139     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
140   if (isa<ConstantStruct>(C))
141     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
142   if (isa<ConstantVector>(C))
143     return VM[V] = ConstantVector::get(Ops);
144   // If this is a no-operand constant, it must be because the type was remapped.
145   if (isa<UndefValue>(C))
146     return VM[V] = UndefValue::get(NewTy);
147   if (isa<ConstantAggregateZero>(C))
148     return VM[V] = ConstantAggregateZero::get(NewTy);
149   assert(isa<ConstantPointerNull>(C));
150   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
151 }
152
153 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
154                      Metadata *Val) {
155   VM.MD()[Key].reset(Val);
156   return Val;
157 }
158
159 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
160   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
161 }
162
163 static Metadata *MapMetadataImpl(const Metadata *MD,
164                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
165                                  ValueToValueMapTy &VM, RemapFlags Flags,
166                                  ValueMapTypeRemapper *TypeMapper,
167                                  ValueMaterializer *Materializer);
168
169 static Metadata *mapMetadataOp(Metadata *Op,
170                                SmallVectorImpl<MDNode *> &DistinctWorklist,
171                                ValueToValueMapTy &VM, RemapFlags Flags,
172                                ValueMapTypeRemapper *TypeMapper,
173                                ValueMaterializer *Materializer) {
174   if (!Op)
175     return nullptr;
176   if (Metadata *MappedOp = MapMetadataImpl(Op, DistinctWorklist, VM, Flags,
177                                            TypeMapper, Materializer))
178     return MappedOp;
179   // Use identity map if MappedOp is null and we can ignore missing entries.
180   if (Flags & RF_IgnoreMissingEntries)
181     return Op;
182
183   // FIXME: This assert crashes during bootstrap, but I think it should be
184   // correct.  For now, just match behaviour from before the metadata/value
185   // split.
186   //
187   //    llvm_unreachable("Referenced metadata not in value map!");
188   return nullptr;
189 }
190
191 /// Resolve uniquing cycles involving the given metadata.
192 static void resolveCycles(Metadata *MD) {
193   if (auto *N = dyn_cast_or_null<MDNode>(MD))
194     if (!N->isResolved())
195       N->resolveCycles();
196 }
197
198 /// Remap the operands of an MDNode.
199 ///
200 /// If \c Node is temporary, uniquing cycles are ignored.  If \c Node is
201 /// distinct, uniquing cycles are resolved as they're found.
202 ///
203 /// \pre \c Node.isDistinct() or \c Node.isTemporary().
204 static bool remapOperands(MDNode &Node,
205                           SmallVectorImpl<MDNode *> &DistinctWorklist,
206                           ValueToValueMapTy &VM, RemapFlags Flags,
207                           ValueMapTypeRemapper *TypeMapper,
208                           ValueMaterializer *Materializer) {
209   assert(!Node.isUniqued() && "Expected temporary or distinct node");
210   const bool IsDistinct = Node.isDistinct();
211
212   bool AnyChanged = false;
213   for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) {
214     Metadata *Old = Node.getOperand(I);
215     Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper,
216                                   Materializer);
217     if (Old != New) {
218       AnyChanged = true;
219       Node.replaceOperandWith(I, New);
220
221       // Resolve uniquing cycles underneath distinct nodes on the fly so they
222       // don't infect later operands.
223       if (IsDistinct)
224         resolveCycles(New);
225     }
226   }
227
228   return AnyChanged;
229 }
230
231 /// Map a distinct MDNode.
232 ///
233 /// Whether distinct nodes change is independent of their operands.  If \a
234 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
235 /// place; effectively, they're moved from one graph to another.  Otherwise,
236 /// they're cloned/duplicated, and the new copy's operands are remapped.
237 static Metadata *mapDistinctNode(const MDNode *Node,
238                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
239                                  ValueToValueMapTy &VM, RemapFlags Flags,
240                                  ValueMapTypeRemapper *TypeMapper,
241                                  ValueMaterializer *Materializer) {
242   assert(Node->isDistinct() && "Expected distinct node");
243
244   MDNode *NewMD;
245   if (Flags & RF_MoveDistinctMDs)
246     NewMD = const_cast<MDNode *>(Node);
247   else
248     NewMD = MDNode::replaceWithDistinct(Node->clone());
249
250   // Remap operands later.
251   DistinctWorklist.push_back(NewMD);
252   return mapToMetadata(VM, Node, NewMD);
253 }
254
255 /// \brief Map a uniqued MDNode.
256 ///
257 /// Uniqued nodes may not need to be recreated (they may map to themselves).
258 static Metadata *mapUniquedNode(const MDNode *Node,
259                                 SmallVectorImpl<MDNode *> &DistinctWorklist,
260                                 ValueToValueMapTy &VM, RemapFlags Flags,
261                                 ValueMapTypeRemapper *TypeMapper,
262                                 ValueMaterializer *Materializer) {
263   assert(Node->isUniqued() && "Expected uniqued node");
264
265   // Create a temporary node and map it upfront in case we have a uniquing
266   // cycle.  If necessary, this mapping will get updated by RAUW logic before
267   // returning.
268   auto ClonedMD = Node->clone();
269   mapToMetadata(VM, Node, ClonedMD.get());
270   if (!remapOperands(*ClonedMD, DistinctWorklist, VM, Flags, TypeMapper,
271                      Materializer)) {
272     // No operands changed, so use the original.
273     ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
274     return const_cast<MDNode *>(Node);
275   }
276
277   // Uniquify the cloned node.
278   return MDNode::replaceWithUniqued(std::move(ClonedMD));
279 }
280
281 static Metadata *MapMetadataImpl(const Metadata *MD,
282                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
283                                  ValueToValueMapTy &VM, RemapFlags Flags,
284                                  ValueMapTypeRemapper *TypeMapper,
285                                  ValueMaterializer *Materializer) {
286   // If the value already exists in the map, use it.
287   if (Metadata *NewMD = VM.MD().lookup(MD).get())
288     return NewMD;
289
290   if (isa<MDString>(MD))
291     return mapToSelf(VM, MD);
292
293   if (isa<ConstantAsMetadata>(MD))
294     if ((Flags & RF_NoModuleLevelChanges))
295       return mapToSelf(VM, MD);
296
297   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
298     Value *MappedV =
299         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
300     if (VMD->getValue() == MappedV ||
301         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
302       return mapToSelf(VM, MD);
303
304     // FIXME: This assert crashes during bootstrap, but I think it should be
305     // correct.  For now, just match behaviour from before the metadata/value
306     // split.
307     //
308     //    assert(MappedV && "Referenced metadata not in value map!");
309     if (MappedV)
310       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
311     return nullptr;
312   }
313
314   // Note: this cast precedes the Flags check so we always get its associated
315   // assertion.
316   const MDNode *Node = cast<MDNode>(MD);
317
318   // If this is a module-level metadata and we know that nothing at the
319   // module level is changing, then use an identity mapping.
320   if (Flags & RF_NoModuleLevelChanges)
321     return mapToSelf(VM, MD);
322
323   // Require resolved nodes whenever metadata might be remapped.
324   assert(Node->isResolved() && "Unexpected unresolved node");
325
326   if (Node->isDistinct())
327     return mapDistinctNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
328                            Materializer);
329
330   return mapUniquedNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
331                         Materializer);
332 }
333
334 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
335                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
336                             ValueMaterializer *Materializer) {
337   SmallVector<MDNode *, 8> DistinctWorklist;
338   Metadata *NewMD = MapMetadataImpl(MD, DistinctWorklist, VM, Flags, TypeMapper,
339                                     Materializer);
340
341   // When there are no module-level changes, it's possible that the metadata
342   // graph has temporaries.  Skip the logic to resolve cycles, since it's
343   // unnecessary (and invalid) in that case.
344   if (Flags & RF_NoModuleLevelChanges)
345     return NewMD;
346
347   // Resolve cycles involving the entry metadata.
348   resolveCycles(NewMD);
349
350   // Remap the operands of distinct MDNodes.
351   while (!DistinctWorklist.empty())
352     remapOperands(*DistinctWorklist.pop_back_val(), DistinctWorklist, VM, Flags,
353                   TypeMapper, Materializer);
354
355   return NewMD;
356 }
357
358 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
359                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
360                           ValueMaterializer *Materializer) {
361   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
362                                   TypeMapper, Materializer));
363 }
364
365 /// RemapInstruction - Convert the instruction operands from referencing the
366 /// current values into those specified by VMap.
367 ///
368 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
369                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
370                             ValueMaterializer *Materializer){
371   // Remap operands.
372   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
373     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
374     // If we aren't ignoring missing entries, assert that something happened.
375     if (V)
376       *op = V;
377     else
378       assert((Flags & RF_IgnoreMissingEntries) &&
379              "Referenced value not in value map!");
380   }
381
382   // Remap phi nodes' incoming blocks.
383   if (PHINode *PN = dyn_cast<PHINode>(I)) {
384     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
385       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
386       // If we aren't ignoring missing entries, assert that something happened.
387       if (V)
388         PN->setIncomingBlock(i, cast<BasicBlock>(V));
389       else
390         assert((Flags & RF_IgnoreMissingEntries) &&
391                "Referenced block not in value map!");
392     }
393   }
394
395   // Remap attached metadata.
396   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
397   I->getAllMetadata(MDs);
398   for (const auto &MI : MDs) {
399     MDNode *Old = MI.second;
400     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
401     if (New != Old)
402       I->setMetadata(MI.first, New);
403   }
404   
405   if (!TypeMapper)
406     return;
407
408   // If the instruction's type is being remapped, do so now.
409   if (auto CS = CallSite(I)) {
410     SmallVector<Type *, 3> Tys;
411     FunctionType *FTy = CS.getFunctionType();
412     Tys.reserve(FTy->getNumParams());
413     for (Type *Ty : FTy->params())
414       Tys.push_back(TypeMapper->remapType(Ty));
415     CS.mutateFunctionType(FunctionType::get(
416         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
417     return;
418   }
419   if (auto *AI = dyn_cast<AllocaInst>(I))
420     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
421   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
422     GEP->setSourceElementType(
423         TypeMapper->remapType(GEP->getSourceElementType()));
424     GEP->setResultElementType(
425         TypeMapper->remapType(GEP->getResultElementType()));
426   }
427   I->mutateType(TypeMapper->remapType(I->getType()));
428 }