LLVM  mainline
ValueMapper.cpp
Go to the documentation of this file.
00001 //===- ValueMapper.cpp - Interface shared by lib/Transforms/Utils ---------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines the MapValue function, which is shared by various parts of
00011 // the lib/Transforms/Utils library.
00012 //
00013 //===----------------------------------------------------------------------===//
00014 
00015 #include "llvm/Transforms/Utils/ValueMapper.h"
00016 #include "llvm/IR/CallSite.h"
00017 #include "llvm/IR/Constants.h"
00018 #include "llvm/IR/Function.h"
00019 #include "llvm/IR/InlineAsm.h"
00020 #include "llvm/IR/Instructions.h"
00021 #include "llvm/IR/Metadata.h"
00022 using namespace llvm;
00023 
00024 // Out of line method to get vtable etc for class.
00025 void ValueMapTypeRemapper::anchor() {}
00026 void ValueMaterializer::anchor() {}
00027 
00028 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
00029                       ValueMapTypeRemapper *TypeMapper,
00030                       ValueMaterializer *Materializer) {
00031   ValueToValueMapTy::iterator I = VM.find(V);
00032   
00033   // If the value already exists in the map, use it.
00034   if (I != VM.end() && I->second) return I->second;
00035   
00036   // If we have a materializer and it can materialize a value, use that.
00037   if (Materializer) {
00038     if (Value *NewV = Materializer->materializeValueFor(const_cast<Value*>(V)))
00039       return VM[V] = NewV;
00040   }
00041 
00042   // Global values do not need to be seeded into the VM if they
00043   // are using the identity mapping.
00044   if (isa<GlobalValue>(V))
00045     return VM[V] = const_cast<Value*>(V);
00046   
00047   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00048     // Inline asm may need *type* remapping.
00049     FunctionType *NewTy = IA->getFunctionType();
00050     if (TypeMapper) {
00051       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
00052 
00053       if (NewTy != IA->getFunctionType())
00054         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
00055                            IA->hasSideEffects(), IA->isAlignStack());
00056     }
00057     
00058     return VM[V] = const_cast<Value*>(V);
00059   }
00060 
00061   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
00062     const Metadata *MD = MDV->getMetadata();
00063     // If this is a module-level metadata and we know that nothing at the module
00064     // level is changing, then use an identity mapping.
00065     if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
00066       return VM[V] = const_cast<Value *>(V);
00067 
00068     auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
00069     if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
00070       return VM[V] = const_cast<Value *>(V);
00071 
00072     // FIXME: This assert crashes during bootstrap, but I think it should be
00073     // correct.  For now, just match behaviour from before the metadata/value
00074     // split.
00075     //
00076     //    assert(MappedMD && "Referenced metadata value not in value map");
00077     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
00078   }
00079 
00080   // Okay, this either must be a constant (which may or may not be mappable) or
00081   // is something that is not in the mapping table.
00082   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
00083   if (!C)
00084     return nullptr;
00085   
00086   if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
00087     Function *F = 
00088       cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
00089     BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
00090                                                        Flags, TypeMapper, Materializer));
00091     return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
00092   }
00093   
00094   // Otherwise, we have some other constant to remap.  Start by checking to see
00095   // if all operands have an identity remapping.
00096   unsigned OpNo = 0, NumOperands = C->getNumOperands();
00097   Value *Mapped = nullptr;
00098   for (; OpNo != NumOperands; ++OpNo) {
00099     Value *Op = C->getOperand(OpNo);
00100     Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
00101     if (Mapped != C) break;
00102   }
00103   
00104   // See if the type mapper wants to remap the type as well.
00105   Type *NewTy = C->getType();
00106   if (TypeMapper)
00107     NewTy = TypeMapper->remapType(NewTy);
00108 
00109   // If the result type and all operands match up, then just insert an identity
00110   // mapping.
00111   if (OpNo == NumOperands && NewTy == C->getType())
00112     return VM[V] = C;
00113   
00114   // Okay, we need to create a new constant.  We've already processed some or
00115   // all of the operands, set them all up now.
00116   SmallVector<Constant*, 8> Ops;
00117   Ops.reserve(NumOperands);
00118   for (unsigned j = 0; j != OpNo; ++j)
00119     Ops.push_back(cast<Constant>(C->getOperand(j)));
00120   
00121   // If one of the operands mismatch, push it and the other mapped operands.
00122   if (OpNo != NumOperands) {
00123     Ops.push_back(cast<Constant>(Mapped));
00124   
00125     // Map the rest of the operands that aren't processed yet.
00126     for (++OpNo; OpNo != NumOperands; ++OpNo)
00127       Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
00128                              Flags, TypeMapper, Materializer));
00129   }
00130   
00131   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
00132     return VM[V] = CE->getWithOperands(Ops, NewTy);
00133   if (isa<ConstantArray>(C))
00134     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
00135   if (isa<ConstantStruct>(C))
00136     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
00137   if (isa<ConstantVector>(C))
00138     return VM[V] = ConstantVector::get(Ops);
00139   // If this is a no-operand constant, it must be because the type was remapped.
00140   if (isa<UndefValue>(C))
00141     return VM[V] = UndefValue::get(NewTy);
00142   if (isa<ConstantAggregateZero>(C))
00143     return VM[V] = ConstantAggregateZero::get(NewTy);
00144   assert(isa<ConstantPointerNull>(C));
00145   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
00146 }
00147 
00148 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
00149                      Metadata *Val) {
00150   VM.MD()[Key].reset(Val);
00151   return Val;
00152 }
00153 
00154 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD) {
00155   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD));
00156 }
00157 
00158 static Metadata *MapMetadataImpl(const Metadata *MD,
00159                                  SmallVectorImpl<MDNode *> &Cycles,
00160                                  ValueToValueMapTy &VM, RemapFlags Flags,
00161                                  ValueMapTypeRemapper *TypeMapper,
00162                                  ValueMaterializer *Materializer);
00163 
00164 static Metadata *mapMetadataOp(Metadata *Op, SmallVectorImpl<MDNode *> &Cycles,
00165                                ValueToValueMapTy &VM, RemapFlags Flags,
00166                                ValueMapTypeRemapper *TypeMapper,
00167                                ValueMaterializer *Materializer) {
00168   if (!Op)
00169     return nullptr;
00170   if (Metadata *MappedOp =
00171           MapMetadataImpl(Op, Cycles, VM, Flags, TypeMapper, Materializer))
00172     return MappedOp;
00173   // Use identity map if MappedOp is null and we can ignore missing entries.
00174   if (Flags & RF_IgnoreMissingEntries)
00175     return Op;
00176 
00177   // FIXME: This assert crashes during bootstrap, but I think it should be
00178   // correct.  For now, just match behaviour from before the metadata/value
00179   // split.
00180   //
00181   //    llvm_unreachable("Referenced metadata not in value map!");
00182   return nullptr;
00183 }
00184 
00185 /// \brief Remap nodes.
00186 ///
00187 /// Insert \c NewNode in the value map, and then remap \c OldNode's operands.
00188 /// Assumes that \c NewNode is already a clone of \c OldNode.
00189 ///
00190 /// \pre \c NewNode is a clone of \c OldNode.
00191 static bool remap(const MDNode *OldNode, MDNode *NewNode,
00192                   SmallVectorImpl<MDNode *> &Cycles, ValueToValueMapTy &VM,
00193                   RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00194                   ValueMaterializer *Materializer) {
00195   assert(OldNode->getNumOperands() == NewNode->getNumOperands() &&
00196          "Expected nodes to match");
00197   assert(OldNode->isResolved() && "Expected resolved node");
00198   assert(!NewNode->isUniqued() && "Expected non-uniqued node");
00199 
00200   // Map the node upfront so it's available for cyclic references.
00201   mapToMetadata(VM, OldNode, NewNode);
00202   bool AnyChanged = false;
00203   for (unsigned I = 0, E = OldNode->getNumOperands(); I != E; ++I) {
00204     Metadata *Old = OldNode->getOperand(I);
00205     assert(NewNode->getOperand(I) == Old &&
00206            "Expected old operands to already be in place");
00207 
00208     Metadata *New = mapMetadataOp(OldNode->getOperand(I), Cycles, VM, Flags,
00209                                   TypeMapper, Materializer);
00210     if (Old != New) {
00211       AnyChanged = true;
00212       NewNode->replaceOperandWith(I, New);
00213     }
00214   }
00215 
00216   return AnyChanged;
00217 }
00218 
00219 /// \brief Map a distinct MDNode.
00220 ///
00221 /// Distinct nodes are not uniqued, so they must always recreated.
00222 static Metadata *mapDistinctNode(const MDNode *Node,
00223                                  SmallVectorImpl<MDNode *> &Cycles,
00224                                  ValueToValueMapTy &VM, RemapFlags Flags,
00225                                  ValueMapTypeRemapper *TypeMapper,
00226                                  ValueMaterializer *Materializer) {
00227   assert(Node->isDistinct() && "Expected distinct node");
00228 
00229   MDNode *NewMD = MDNode::replaceWithDistinct(Node->clone());
00230   remap(Node, NewMD, Cycles, VM, Flags, TypeMapper, Materializer);
00231 
00232   // Track any cycles beneath this node.
00233   for (Metadata *Op : NewMD->operands())
00234     if (auto *Node = dyn_cast_or_null<MDNode>(Op))
00235       if (!Node->isResolved())
00236         Cycles.push_back(Node);
00237 
00238   return NewMD;
00239 }
00240 
00241 /// \brief Map a uniqued MDNode.
00242 ///
00243 /// Uniqued nodes may not need to be recreated (they may map to themselves).
00244 static Metadata *mapUniquedNode(const MDNode *Node,
00245                                 SmallVectorImpl<MDNode *> &Cycles,
00246                                 ValueToValueMapTy &VM, RemapFlags Flags,
00247                                 ValueMapTypeRemapper *TypeMapper,
00248                                 ValueMaterializer *Materializer) {
00249   assert(Node->isUniqued() && "Expected uniqued node");
00250 
00251   // Create a temporary node upfront in case we have a metadata cycle.
00252   auto ClonedMD = Node->clone();
00253   if (!remap(Node, ClonedMD.get(), Cycles, VM, Flags, TypeMapper, Materializer))
00254     // No operands changed, so use the identity mapping.
00255     return mapToSelf(VM, Node);
00256 
00257   // At least one operand has changed, so uniquify the cloned node.
00258   return mapToMetadata(VM, Node,
00259                        MDNode::replaceWithUniqued(std::move(ClonedMD)));
00260 }
00261 
00262 static Metadata *MapMetadataImpl(const Metadata *MD,
00263                                  SmallVectorImpl<MDNode *> &Cycles,
00264                                  ValueToValueMapTy &VM, RemapFlags Flags,
00265                                  ValueMapTypeRemapper *TypeMapper,
00266                                  ValueMaterializer *Materializer) {
00267   // If the value already exists in the map, use it.
00268   if (Metadata *NewMD = VM.MD().lookup(MD).get())
00269     return NewMD;
00270 
00271   if (isa<MDString>(MD))
00272     return mapToSelf(VM, MD);
00273 
00274   if (isa<ConstantAsMetadata>(MD))
00275     if ((Flags & RF_NoModuleLevelChanges))
00276       return mapToSelf(VM, MD);
00277 
00278   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
00279     Value *MappedV =
00280         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
00281     if (VMD->getValue() == MappedV ||
00282         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
00283       return mapToSelf(VM, MD);
00284 
00285     // FIXME: This assert crashes during bootstrap, but I think it should be
00286     // correct.  For now, just match behaviour from before the metadata/value
00287     // split.
00288     //
00289     //    assert(MappedV && "Referenced metadata not in value map!");
00290     if (MappedV)
00291       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
00292     return nullptr;
00293   }
00294 
00295   // Note: this cast precedes the Flags check so we always get its associated
00296   // assertion.
00297   const MDNode *Node = cast<MDNode>(MD);
00298 
00299   // If this is a module-level metadata and we know that nothing at the
00300   // module level is changing, then use an identity mapping.
00301   if (Flags & RF_NoModuleLevelChanges)
00302     return mapToSelf(VM, MD);
00303 
00304   // Require resolved nodes whenever metadata might be remapped.
00305   assert(Node->isResolved() && "Unexpected unresolved node");
00306 
00307   if (Node->isDistinct())
00308     return mapDistinctNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
00309 
00310   return mapUniquedNode(Node, Cycles, VM, Flags, TypeMapper, Materializer);
00311 }
00312 
00313 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
00314                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00315                             ValueMaterializer *Materializer) {
00316   SmallVector<MDNode *, 8> Cycles;
00317   Metadata *NewMD =
00318       MapMetadataImpl(MD, Cycles, VM, Flags, TypeMapper, Materializer);
00319 
00320   // Resolve cycles underneath MD.
00321   if (NewMD && NewMD != MD) {
00322     if (auto *N = dyn_cast<MDNode>(NewMD))
00323       if (!N->isResolved())
00324         N->resolveCycles();
00325 
00326     for (MDNode *N : Cycles)
00327       if (!N->isResolved())
00328         N->resolveCycles();
00329   } else {
00330     // Shouldn't get unresolved cycles if nothing was remapped.
00331     assert(Cycles.empty() && "Expected no unresolved cycles");
00332   }
00333 
00334   return NewMD;
00335 }
00336 
00337 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
00338                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00339                           ValueMaterializer *Materializer) {
00340   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
00341                                   TypeMapper, Materializer));
00342 }
00343 
00344 /// RemapInstruction - Convert the instruction operands from referencing the
00345 /// current values into those specified by VMap.
00346 ///
00347 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
00348                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00349                             ValueMaterializer *Materializer){
00350   // Remap operands.
00351   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
00352     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
00353     // If we aren't ignoring missing entries, assert that something happened.
00354     if (V)
00355       *op = V;
00356     else
00357       assert((Flags & RF_IgnoreMissingEntries) &&
00358              "Referenced value not in value map!");
00359   }
00360 
00361   // Remap phi nodes' incoming blocks.
00362   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00363     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00364       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
00365       // If we aren't ignoring missing entries, assert that something happened.
00366       if (V)
00367         PN->setIncomingBlock(i, cast<BasicBlock>(V));
00368       else
00369         assert((Flags & RF_IgnoreMissingEntries) &&
00370                "Referenced block not in value map!");
00371     }
00372   }
00373 
00374   // Remap attached metadata.
00375   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00376   I->getAllMetadata(MDs);
00377   for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
00378            MI = MDs.begin(),
00379            ME = MDs.end();
00380        MI != ME; ++MI) {
00381     MDNode *Old = MI->second;
00382     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
00383     if (New != Old)
00384       I->setMetadata(MI->first, New);
00385   }
00386   
00387   if (!TypeMapper)
00388     return;
00389 
00390   // If the instruction's type is being remapped, do so now.
00391   if (auto CS = CallSite(I)) {
00392     SmallVector<Type *, 3> Tys;
00393     FunctionType *FTy = CS.getFunctionType();
00394     Tys.reserve(FTy->getNumParams());
00395     for (Type *Ty : FTy->params())
00396       Tys.push_back(TypeMapper->remapType(Ty));
00397     CS.mutateFunctionType(FunctionType::get(
00398         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
00399     return;
00400   }
00401   if (auto *AI = dyn_cast<AllocaInst>(I))
00402     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
00403   if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
00404     GEP->setSourceElementType(
00405         TypeMapper->remapType(GEP->getSourceElementType()));
00406   I->mutateType(TypeMapper->remapType(I->getType()));
00407 }