LLVM API Documentation

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