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   // If the value already exists in the map, use it.
00162   if (Metadata *NewMD = VM.MD().lookup(MD).get())
00163     return NewMD;
00164 
00165   if (isa<MDString>(MD))
00166     return mapToSelf(VM, MD);
00167 
00168   if (isa<ConstantAsMetadata>(MD))
00169     if ((Flags & RF_NoModuleLevelChanges))
00170       return mapToSelf(VM, MD);
00171 
00172   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
00173     Value *MappedV =
00174         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
00175     if (VMD->getValue() == MappedV ||
00176         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
00177       return mapToSelf(VM, MD);
00178 
00179     // FIXME: This assert crashes during bootstrap, but I think it should be
00180     // correct.  For now, just match behaviour from before the metadata/value
00181     // split.
00182     //
00183     //    assert(MappedV && "Referenced metadata not in value map!");
00184     if (MappedV)
00185       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV));
00186     return nullptr;
00187   }
00188 
00189   const MDNode *Node = cast<MDNode>(MD);
00190   assert(Node->isResolved() && "Unexpected unresolved node");
00191 
00192   auto getMappedOp = [&](Metadata *Op) -> Metadata *{
00193     if (!Op)
00194       return nullptr;
00195     if (Metadata *MappedOp =
00196             MapMetadataImpl(Op, VM, Flags, TypeMapper, Materializer))
00197       return MappedOp;
00198     // Use identity map if MappedOp is null and we can ignore missing entries.
00199     if (Flags & RF_IgnoreMissingEntries)
00200       return Op;
00201 
00202     // FIXME: This assert crashes during bootstrap, but I think it should be
00203     // correct.  For now, just match behaviour from before the metadata/value
00204     // split.
00205     //
00206     //    llvm_unreachable("Referenced metadata not in value map!");
00207     return nullptr;
00208   };
00209 
00210   // If this is a module-level metadata and we know that nothing at the
00211   // module level is changing, then use an identity mapping.
00212   if (Flags & RF_NoModuleLevelChanges)
00213     return mapToSelf(VM, MD);
00214 
00215   // Create a dummy node in case we have a metadata cycle.
00216   MDNodeFwdDecl *Dummy = MDNode::getTemporary(Node->getContext(), None);
00217   mapToMetadata(VM, Node, Dummy);
00218 
00219   // Check all operands to see if any need to be remapped.
00220   for (unsigned I = 0, E = Node->getNumOperands(); I != E; ++I) {
00221     Metadata *Op = Node->getOperand(I);
00222     Metadata *MappedOp = getMappedOp(Op);
00223     if (Op == MappedOp)
00224       continue;
00225 
00226     // Ok, at least one operand needs remapping.
00227     SmallVector<Metadata *, 4> Elts;
00228     Elts.reserve(Node->getNumOperands());
00229     for (I = 0; I != E; ++I)
00230       Elts.push_back(getMappedOp(Node->getOperand(I)));
00231 
00232     MDNode *NewMD = MDNode::get(Node->getContext(), Elts);
00233     Dummy->replaceAllUsesWith(NewMD);
00234     MDNode::deleteTemporary(Dummy);
00235     return mapToMetadata(VM, Node, NewMD);
00236   }
00237 
00238   // No operands needed remapping.  Use an identity mapping.
00239   mapToSelf(VM, MD);
00240   MDNode::deleteTemporary(Dummy);
00241   return const_cast<Metadata *>(MD);
00242 }
00243 
00244 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
00245                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00246                             ValueMaterializer *Materializer) {
00247   Metadata *NewMD = MapMetadataImpl(MD, VM, Flags, TypeMapper, Materializer);
00248   if (NewMD && NewMD != MD)
00249     if (auto *G = dyn_cast<GenericMDNode>(NewMD))
00250       G->resolveCycles();
00251   return NewMD;
00252 }
00253 
00254 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
00255                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00256                           ValueMaterializer *Materializer) {
00257   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
00258                                   TypeMapper, Materializer));
00259 }
00260 
00261 /// RemapInstruction - Convert the instruction operands from referencing the
00262 /// current values into those specified by VMap.
00263 ///
00264 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
00265                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00266                             ValueMaterializer *Materializer){
00267   // Remap operands.
00268   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
00269     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
00270     // If we aren't ignoring missing entries, assert that something happened.
00271     if (V)
00272       *op = V;
00273     else
00274       assert((Flags & RF_IgnoreMissingEntries) &&
00275              "Referenced value not in value map!");
00276   }
00277 
00278   // Remap phi nodes' incoming blocks.
00279   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00280     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00281       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
00282       // If we aren't ignoring missing entries, assert that something happened.
00283       if (V)
00284         PN->setIncomingBlock(i, cast<BasicBlock>(V));
00285       else
00286         assert((Flags & RF_IgnoreMissingEntries) &&
00287                "Referenced block not in value map!");
00288     }
00289   }
00290 
00291   // Remap attached metadata.
00292   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00293   I->getAllMetadata(MDs);
00294   for (SmallVectorImpl<std::pair<unsigned, MDNode *>>::iterator
00295            MI = MDs.begin(),
00296            ME = MDs.end();
00297        MI != ME; ++MI) {
00298     MDNode *Old = MI->second;
00299     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
00300     if (New != Old)
00301       I->setMetadata(MI->first, New);
00302   }
00303   
00304   // If the instruction's type is being remapped, do so now.
00305   if (TypeMapper)
00306     I->mutateType(TypeMapper->remapType(I->getType()));
00307 }