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 #include "llvm/IR/Operator.h"
00023 using namespace llvm;
00024 
00025 // Out of line method to get vtable etc for class.
00026 void ValueMapTypeRemapper::anchor() {}
00027 void ValueMaterializer::anchor() {}
00028 void ValueMaterializer::materializeInitFor(GlobalValue *New, GlobalValue *Old) {
00029 }
00030 
00031 Value *llvm::MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags,
00032                       ValueMapTypeRemapper *TypeMapper,
00033                       ValueMaterializer *Materializer) {
00034   ValueToValueMapTy::iterator I = VM.find(V);
00035   
00036   // If the value already exists in the map, use it.
00037   if (I != VM.end() && I->second) return I->second;
00038   
00039   // If we have a materializer and it can materialize a value, use that.
00040   if (Materializer) {
00041     if (Value *NewV =
00042             Materializer->materializeDeclFor(const_cast<Value *>(V))) {
00043       VM[V] = NewV;
00044       if (auto *NewGV = dyn_cast<GlobalValue>(NewV))
00045         Materializer->materializeInitFor(
00046             NewGV, const_cast<GlobalValue *>(cast<GlobalValue>(V)));
00047       return NewV;
00048     }
00049   }
00050 
00051   // Global values do not need to be seeded into the VM if they
00052   // are using the identity mapping.
00053   if (isa<GlobalValue>(V)) {
00054     if (Flags & RF_NullMapMissingGlobalValues) {
00055       assert(!(Flags & RF_IgnoreMissingEntries) &&
00056              "Illegal to specify both RF_NullMapMissingGlobalValues and "
00057              "RF_IgnoreMissingEntries");
00058       return nullptr;
00059     }
00060     return VM[V] = const_cast<Value*>(V);
00061   }
00062 
00063   if (const InlineAsm *IA = dyn_cast<InlineAsm>(V)) {
00064     // Inline asm may need *type* remapping.
00065     FunctionType *NewTy = IA->getFunctionType();
00066     if (TypeMapper) {
00067       NewTy = cast<FunctionType>(TypeMapper->remapType(NewTy));
00068 
00069       if (NewTy != IA->getFunctionType())
00070         V = InlineAsm::get(NewTy, IA->getAsmString(), IA->getConstraintString(),
00071                            IA->hasSideEffects(), IA->isAlignStack());
00072     }
00073     
00074     return VM[V] = const_cast<Value*>(V);
00075   }
00076 
00077   if (const auto *MDV = dyn_cast<MetadataAsValue>(V)) {
00078     const Metadata *MD = MDV->getMetadata();
00079     // If this is a module-level metadata and we know that nothing at the module
00080     // level is changing, then use an identity mapping.
00081     if (!isa<LocalAsMetadata>(MD) && (Flags & RF_NoModuleLevelChanges))
00082       return VM[V] = const_cast<Value *>(V);
00083 
00084     auto *MappedMD = MapMetadata(MD, VM, Flags, TypeMapper, Materializer);
00085     if (MD == MappedMD || (!MappedMD && (Flags & RF_IgnoreMissingEntries)))
00086       return VM[V] = const_cast<Value *>(V);
00087 
00088     // FIXME: This assert crashes during bootstrap, but I think it should be
00089     // correct.  For now, just match behaviour from before the metadata/value
00090     // split.
00091     //
00092     //    assert((MappedMD || (Flags & RF_NullMapMissingGlobalValues)) &&
00093     //           "Referenced metadata value not in value map");
00094     return VM[V] = MetadataAsValue::get(V->getContext(), MappedMD);
00095   }
00096 
00097   // Okay, this either must be a constant (which may or may not be mappable) or
00098   // is something that is not in the mapping table.
00099   Constant *C = const_cast<Constant*>(dyn_cast<Constant>(V));
00100   if (!C)
00101     return nullptr;
00102   
00103   if (BlockAddress *BA = dyn_cast<BlockAddress>(C)) {
00104     Function *F = 
00105       cast<Function>(MapValue(BA->getFunction(), VM, Flags, TypeMapper, Materializer));
00106     BasicBlock *BB = cast_or_null<BasicBlock>(MapValue(BA->getBasicBlock(), VM,
00107                                                        Flags, TypeMapper, Materializer));
00108     return VM[V] = BlockAddress::get(F, BB ? BB : BA->getBasicBlock());
00109   }
00110   
00111   // Otherwise, we have some other constant to remap.  Start by checking to see
00112   // if all operands have an identity remapping.
00113   unsigned OpNo = 0, NumOperands = C->getNumOperands();
00114   Value *Mapped = nullptr;
00115   for (; OpNo != NumOperands; ++OpNo) {
00116     Value *Op = C->getOperand(OpNo);
00117     Mapped = MapValue(Op, VM, Flags, TypeMapper, Materializer);
00118     if (Mapped != C) break;
00119   }
00120   
00121   // See if the type mapper wants to remap the type as well.
00122   Type *NewTy = C->getType();
00123   if (TypeMapper)
00124     NewTy = TypeMapper->remapType(NewTy);
00125 
00126   // If the result type and all operands match up, then just insert an identity
00127   // mapping.
00128   if (OpNo == NumOperands && NewTy == C->getType())
00129     return VM[V] = C;
00130   
00131   // Okay, we need to create a new constant.  We've already processed some or
00132   // all of the operands, set them all up now.
00133   SmallVector<Constant*, 8> Ops;
00134   Ops.reserve(NumOperands);
00135   for (unsigned j = 0; j != OpNo; ++j)
00136     Ops.push_back(cast<Constant>(C->getOperand(j)));
00137   
00138   // If one of the operands mismatch, push it and the other mapped operands.
00139   if (OpNo != NumOperands) {
00140     Ops.push_back(cast<Constant>(Mapped));
00141   
00142     // Map the rest of the operands that aren't processed yet.
00143     for (++OpNo; OpNo != NumOperands; ++OpNo)
00144       Ops.push_back(MapValue(cast<Constant>(C->getOperand(OpNo)), VM,
00145                              Flags, TypeMapper, Materializer));
00146   }
00147   Type *NewSrcTy = nullptr;
00148   if (TypeMapper)
00149     if (auto *GEPO = dyn_cast<GEPOperator>(C))
00150       NewSrcTy = TypeMapper->remapType(GEPO->getSourceElementType());
00151 
00152   if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
00153     return VM[V] = CE->getWithOperands(Ops, NewTy, false, NewSrcTy);
00154   if (isa<ConstantArray>(C))
00155     return VM[V] = ConstantArray::get(cast<ArrayType>(NewTy), Ops);
00156   if (isa<ConstantStruct>(C))
00157     return VM[V] = ConstantStruct::get(cast<StructType>(NewTy), Ops);
00158   if (isa<ConstantVector>(C))
00159     return VM[V] = ConstantVector::get(Ops);
00160   // If this is a no-operand constant, it must be because the type was remapped.
00161   if (isa<UndefValue>(C))
00162     return VM[V] = UndefValue::get(NewTy);
00163   if (isa<ConstantAggregateZero>(C))
00164     return VM[V] = ConstantAggregateZero::get(NewTy);
00165   assert(isa<ConstantPointerNull>(C));
00166   return VM[V] = ConstantPointerNull::get(cast<PointerType>(NewTy));
00167 }
00168 
00169 static Metadata *mapToMetadata(ValueToValueMapTy &VM, const Metadata *Key,
00170                                Metadata *Val, ValueMaterializer *Materializer,
00171                                RemapFlags Flags) {
00172   VM.MD()[Key].reset(Val);
00173   if (Materializer && !(Flags & RF_HaveUnmaterializedMetadata)) {
00174     auto *N = dyn_cast_or_null<MDNode>(Val);
00175     // Need to invoke this once we have non-temporary MD.
00176     if (!N || !N->isTemporary())
00177       Materializer->replaceTemporaryMetadata(Key, Val);
00178   }
00179   return Val;
00180 }
00181 
00182 static Metadata *mapToSelf(ValueToValueMapTy &VM, const Metadata *MD,
00183                            ValueMaterializer *Materializer, RemapFlags Flags) {
00184   return mapToMetadata(VM, MD, const_cast<Metadata *>(MD), Materializer, Flags);
00185 }
00186 
00187 static Metadata *MapMetadataImpl(const Metadata *MD,
00188                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
00189                                  ValueToValueMapTy &VM, RemapFlags Flags,
00190                                  ValueMapTypeRemapper *TypeMapper,
00191                                  ValueMaterializer *Materializer);
00192 
00193 static Metadata *mapMetadataOp(Metadata *Op,
00194                                SmallVectorImpl<MDNode *> &DistinctWorklist,
00195                                ValueToValueMapTy &VM, RemapFlags Flags,
00196                                ValueMapTypeRemapper *TypeMapper,
00197                                ValueMaterializer *Materializer) {
00198   if (!Op)
00199     return nullptr;
00200 
00201   if (Materializer && !Materializer->isMetadataNeeded(Op))
00202     return nullptr;
00203 
00204   if (Metadata *MappedOp = MapMetadataImpl(Op, DistinctWorklist, VM, Flags,
00205                                            TypeMapper, Materializer))
00206     return MappedOp;
00207   // Use identity map if MappedOp is null and we can ignore missing entries.
00208   if (Flags & RF_IgnoreMissingEntries)
00209     return Op;
00210 
00211   // FIXME: This assert crashes during bootstrap, but I think it should be
00212   // correct.  For now, just match behaviour from before the metadata/value
00213   // split.
00214   //
00215   //    assert((Flags & RF_NullMapMissingGlobalValues) &&
00216   //           "Referenced metadata not in value map!");
00217   return nullptr;
00218 }
00219 
00220 /// Resolve uniquing cycles involving the given metadata.
00221 static void resolveCycles(Metadata *MD, bool AllowTemps) {
00222   if (auto *N = dyn_cast_or_null<MDNode>(MD)) {
00223     if (AllowTemps && N->isTemporary())
00224       return;
00225     if (!N->isResolved()) {
00226       if (AllowTemps)
00227         // Note that this will drop RAUW support on any temporaries, which
00228         // blocks uniquing. If this ends up being an issue, in the future
00229         // we can experiment with delaying resolving these nodes until
00230         // after metadata is fully materialized (i.e. when linking metadata
00231         // as a postpass after function importing).
00232         N->resolveNonTemporaries();
00233       else
00234         N->resolveCycles();
00235     }
00236   }
00237 }
00238 
00239 /// Remap the operands of an MDNode.
00240 ///
00241 /// If \c Node is temporary, uniquing cycles are ignored.  If \c Node is
00242 /// distinct, uniquing cycles are resolved as they're found.
00243 ///
00244 /// \pre \c Node.isDistinct() or \c Node.isTemporary().
00245 static bool remapOperands(MDNode &Node,
00246                           SmallVectorImpl<MDNode *> &DistinctWorklist,
00247                           ValueToValueMapTy &VM, RemapFlags Flags,
00248                           ValueMapTypeRemapper *TypeMapper,
00249                           ValueMaterializer *Materializer) {
00250   assert(!Node.isUniqued() && "Expected temporary or distinct node");
00251   const bool IsDistinct = Node.isDistinct();
00252 
00253   bool AnyChanged = false;
00254   for (unsigned I = 0, E = Node.getNumOperands(); I != E; ++I) {
00255     Metadata *Old = Node.getOperand(I);
00256     Metadata *New = mapMetadataOp(Old, DistinctWorklist, VM, Flags, TypeMapper,
00257                                   Materializer);
00258     if (Old != New) {
00259       AnyChanged = true;
00260       Node.replaceOperandWith(I, New);
00261 
00262       // Resolve uniquing cycles underneath distinct nodes on the fly so they
00263       // don't infect later operands.
00264       if (IsDistinct)
00265         resolveCycles(New, Flags & RF_HaveUnmaterializedMetadata);
00266     }
00267   }
00268 
00269   return AnyChanged;
00270 }
00271 
00272 /// Map a distinct MDNode.
00273 ///
00274 /// Whether distinct nodes change is independent of their operands.  If \a
00275 /// RF_MoveDistinctMDs, then they are reused, and their operands remapped in
00276 /// place; effectively, they're moved from one graph to another.  Otherwise,
00277 /// they're cloned/duplicated, and the new copy's operands are remapped.
00278 static Metadata *mapDistinctNode(const MDNode *Node,
00279                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
00280                                  ValueToValueMapTy &VM, RemapFlags Flags,
00281                                  ValueMapTypeRemapper *TypeMapper,
00282                                  ValueMaterializer *Materializer) {
00283   assert(Node->isDistinct() && "Expected distinct node");
00284 
00285   MDNode *NewMD;
00286   if (Flags & RF_MoveDistinctMDs)
00287     NewMD = const_cast<MDNode *>(Node);
00288   else
00289     NewMD = MDNode::replaceWithDistinct(Node->clone());
00290 
00291   // Remap operands later.
00292   DistinctWorklist.push_back(NewMD);
00293   return mapToMetadata(VM, Node, NewMD, Materializer, Flags);
00294 }
00295 
00296 /// \brief Map a uniqued MDNode.
00297 ///
00298 /// Uniqued nodes may not need to be recreated (they may map to themselves).
00299 static Metadata *mapUniquedNode(const MDNode *Node,
00300                                 SmallVectorImpl<MDNode *> &DistinctWorklist,
00301                                 ValueToValueMapTy &VM, RemapFlags Flags,
00302                                 ValueMapTypeRemapper *TypeMapper,
00303                                 ValueMaterializer *Materializer) {
00304   assert(((Flags & RF_HaveUnmaterializedMetadata) || Node->isUniqued()) &&
00305          "Expected uniqued node");
00306 
00307   // Create a temporary node and map it upfront in case we have a uniquing
00308   // cycle.  If necessary, this mapping will get updated by RAUW logic before
00309   // returning.
00310   auto ClonedMD = Node->clone();
00311   mapToMetadata(VM, Node, ClonedMD.get(), Materializer, Flags);
00312   if (!remapOperands(*ClonedMD, DistinctWorklist, VM, Flags, TypeMapper,
00313                      Materializer)) {
00314     // No operands changed, so use the original.
00315     ClonedMD->replaceAllUsesWith(const_cast<MDNode *>(Node));
00316     // Even though replaceAllUsesWith would have replaced the value map
00317     // entry, we need to explictly map with the final non-temporary node
00318     // to replace any temporary metadata via the callback.
00319     return mapToSelf(VM, Node, Materializer, Flags);
00320   }
00321 
00322   // Uniquify the cloned node. Explicitly map it with the final non-temporary
00323   // node so that replacement of temporary metadata via the callback occurs.
00324   return mapToMetadata(VM, Node,
00325                        MDNode::replaceWithUniqued(std::move(ClonedMD)),
00326                        Materializer, Flags);
00327 }
00328 
00329 static Metadata *MapMetadataImpl(const Metadata *MD,
00330                                  SmallVectorImpl<MDNode *> &DistinctWorklist,
00331                                  ValueToValueMapTy &VM, RemapFlags Flags,
00332                                  ValueMapTypeRemapper *TypeMapper,
00333                                  ValueMaterializer *Materializer) {
00334   // If the value already exists in the map, use it.
00335   if (Metadata *NewMD = VM.MD().lookup(MD).get())
00336     return NewMD;
00337 
00338   if (isa<MDString>(MD))
00339     return mapToSelf(VM, MD, Materializer, Flags);
00340 
00341   if (isa<ConstantAsMetadata>(MD))
00342     if ((Flags & RF_NoModuleLevelChanges))
00343       return mapToSelf(VM, MD, Materializer, Flags);
00344 
00345   if (const auto *VMD = dyn_cast<ValueAsMetadata>(MD)) {
00346     Value *MappedV =
00347         MapValue(VMD->getValue(), VM, Flags, TypeMapper, Materializer);
00348     if (VMD->getValue() == MappedV ||
00349         (!MappedV && (Flags & RF_IgnoreMissingEntries)))
00350       return mapToSelf(VM, MD, Materializer, Flags);
00351 
00352     // FIXME: This assert crashes during bootstrap, but I think it should be
00353     // correct.  For now, just match behaviour from before the metadata/value
00354     // split.
00355     //
00356     //    assert((MappedV || (Flags & RF_NullMapMissingGlobalValues)) &&
00357     //           "Referenced metadata not in value map!");
00358     if (MappedV)
00359       return mapToMetadata(VM, MD, ValueAsMetadata::get(MappedV), Materializer,
00360                            Flags);
00361     return nullptr;
00362   }
00363 
00364   // Note: this cast precedes the Flags check so we always get its associated
00365   // assertion.
00366   const MDNode *Node = cast<MDNode>(MD);
00367 
00368   // If this is a module-level metadata and we know that nothing at the
00369   // module level is changing, then use an identity mapping.
00370   if (Flags & RF_NoModuleLevelChanges)
00371     return mapToSelf(VM, MD, Materializer, Flags);
00372 
00373   // Require resolved nodes whenever metadata might be remapped.
00374   assert(((Flags & RF_HaveUnmaterializedMetadata) || Node->isResolved()) &&
00375          "Unexpected unresolved node");
00376 
00377   if (Materializer && Node->isTemporary()) {
00378     assert(Flags & RF_HaveUnmaterializedMetadata);
00379     Metadata *TempMD =
00380         Materializer->mapTemporaryMetadata(const_cast<Metadata *>(MD));
00381     // If the above callback returned an existing temporary node, use it
00382     // instead of the current temporary node. This happens when earlier
00383     // function importing passes already created and saved a temporary
00384     // metadata node for the same value id.
00385     if (TempMD) {
00386       mapToMetadata(VM, MD, TempMD, Materializer, Flags);
00387       return TempMD;
00388     }
00389   }
00390 
00391   if (Node->isDistinct())
00392     return mapDistinctNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
00393                            Materializer);
00394 
00395   return mapUniquedNode(Node, DistinctWorklist, VM, Flags, TypeMapper,
00396                         Materializer);
00397 }
00398 
00399 Metadata *llvm::MapMetadata(const Metadata *MD, ValueToValueMapTy &VM,
00400                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00401                             ValueMaterializer *Materializer) {
00402   SmallVector<MDNode *, 8> DistinctWorklist;
00403   Metadata *NewMD = MapMetadataImpl(MD, DistinctWorklist, VM, Flags, TypeMapper,
00404                                     Materializer);
00405 
00406   // When there are no module-level changes, it's possible that the metadata
00407   // graph has temporaries.  Skip the logic to resolve cycles, since it's
00408   // unnecessary (and invalid) in that case.
00409   if (Flags & RF_NoModuleLevelChanges)
00410     return NewMD;
00411 
00412   // Resolve cycles involving the entry metadata.
00413   resolveCycles(NewMD, Flags & RF_HaveUnmaterializedMetadata);
00414 
00415   // Remap the operands of distinct MDNodes.
00416   while (!DistinctWorklist.empty())
00417     remapOperands(*DistinctWorklist.pop_back_val(), DistinctWorklist, VM, Flags,
00418                   TypeMapper, Materializer);
00419 
00420   return NewMD;
00421 }
00422 
00423 MDNode *llvm::MapMetadata(const MDNode *MD, ValueToValueMapTy &VM,
00424                           RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00425                           ValueMaterializer *Materializer) {
00426   return cast<MDNode>(MapMetadata(static_cast<const Metadata *>(MD), VM, Flags,
00427                                   TypeMapper, Materializer));
00428 }
00429 
00430 /// RemapInstruction - Convert the instruction operands from referencing the
00431 /// current values into those specified by VMap.
00432 ///
00433 void llvm::RemapInstruction(Instruction *I, ValueToValueMapTy &VMap,
00434                             RemapFlags Flags, ValueMapTypeRemapper *TypeMapper,
00435                             ValueMaterializer *Materializer){
00436   // Remap operands.
00437   for (User::op_iterator op = I->op_begin(), E = I->op_end(); op != E; ++op) {
00438     Value *V = MapValue(*op, VMap, Flags, TypeMapper, Materializer);
00439     // If we aren't ignoring missing entries, assert that something happened.
00440     if (V)
00441       *op = V;
00442     else
00443       assert((Flags & RF_IgnoreMissingEntries) &&
00444              "Referenced value not in value map!");
00445   }
00446 
00447   // Remap phi nodes' incoming blocks.
00448   if (PHINode *PN = dyn_cast<PHINode>(I)) {
00449     for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
00450       Value *V = MapValue(PN->getIncomingBlock(i), VMap, Flags);
00451       // If we aren't ignoring missing entries, assert that something happened.
00452       if (V)
00453         PN->setIncomingBlock(i, cast<BasicBlock>(V));
00454       else
00455         assert((Flags & RF_IgnoreMissingEntries) &&
00456                "Referenced block not in value map!");
00457     }
00458   }
00459 
00460   // Remap attached metadata.
00461   SmallVector<std::pair<unsigned, MDNode *>, 4> MDs;
00462   I->getAllMetadata(MDs);
00463   for (const auto &MI : MDs) {
00464     MDNode *Old = MI.second;
00465     MDNode *New = MapMetadata(Old, VMap, Flags, TypeMapper, Materializer);
00466     if (New != Old)
00467       I->setMetadata(MI.first, New);
00468   }
00469   
00470   if (!TypeMapper)
00471     return;
00472 
00473   // If the instruction's type is being remapped, do so now.
00474   if (auto CS = CallSite(I)) {
00475     SmallVector<Type *, 3> Tys;
00476     FunctionType *FTy = CS.getFunctionType();
00477     Tys.reserve(FTy->getNumParams());
00478     for (Type *Ty : FTy->params())
00479       Tys.push_back(TypeMapper->remapType(Ty));
00480     CS.mutateFunctionType(FunctionType::get(
00481         TypeMapper->remapType(I->getType()), Tys, FTy->isVarArg()));
00482     return;
00483   }
00484   if (auto *AI = dyn_cast<AllocaInst>(I))
00485     AI->setAllocatedType(TypeMapper->remapType(AI->getAllocatedType()));
00486   if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
00487     GEP->setSourceElementType(
00488         TypeMapper->remapType(GEP->getSourceElementType()));
00489     GEP->setResultElementType(
00490         TypeMapper->remapType(GEP->getResultElementType()));
00491   }
00492   I->mutateType(TypeMapper->remapType(I->getType()));
00493 }