LLVM  14.0.0git
CloneModule.cpp
Go to the documentation of this file.
1 //===- CloneModule.cpp - Clone an entire module ---------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the CloneModule interface which makes a copy of an
10 // entire module.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "llvm/IR/Constant.h"
15 #include "llvm/IR/DerivedTypes.h"
16 #include "llvm/IR/Module.h"
19 using namespace llvm;
20 
21 static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
22  const Comdat *SC = Src->getComdat();
23  if (!SC)
24  return;
25  Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
26  DC->setSelectionKind(SC->getSelectionKind());
27  Dst->setComdat(DC);
28 }
29 
30 /// This is not as easy as it might seem because we have to worry about making
31 /// copies of global variables and functions, and making their (initializers and
32 /// references, respectively) refer to the right globals.
33 ///
34 std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
35  // Create the value map that maps things from the old module over to the new
36  // module.
37  ValueToValueMapTy VMap;
38  return CloneModule(M, VMap);
39 }
40 
41 std::unique_ptr<Module> llvm::CloneModule(const Module &M,
42  ValueToValueMapTy &VMap) {
43  return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
44 }
45 
46 std::unique_ptr<Module> llvm::CloneModule(
47  const Module &M, ValueToValueMapTy &VMap,
48  function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
49  // First off, we need to create the new module.
50  std::unique_ptr<Module> New =
51  std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
52  New->setSourceFileName(M.getSourceFileName());
53  New->setDataLayout(M.getDataLayout());
54  New->setTargetTriple(M.getTargetTriple());
55  New->setModuleInlineAsm(M.getModuleInlineAsm());
56 
57  // Loop over all of the global variables, making corresponding globals in the
58  // new module. Here we add them to the VMap and to the new Module. We
59  // don't worry about attributes or initializers, they will come later.
60  //
61  for (Module::const_global_iterator I = M.global_begin(), E = M.global_end();
62  I != E; ++I) {
63  GlobalVariable *GV = new GlobalVariable(*New,
64  I->getValueType(),
65  I->isConstant(), I->getLinkage(),
66  (Constant*) nullptr, I->getName(),
67  (GlobalVariable*) nullptr,
68  I->getThreadLocalMode(),
69  I->getType()->getAddressSpace());
70  GV->copyAttributesFrom(&*I);
71  VMap[&*I] = GV;
72  }
73 
74  // Loop over the functions in the module, making external functions as before
75  for (const Function &I : M) {
76  Function *NF =
77  Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
78  I.getAddressSpace(), I.getName(), New.get());
79  NF->copyAttributesFrom(&I);
80  VMap[&I] = NF;
81  }
82 
83  // Loop over the aliases in the module
84  for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
85  I != E; ++I) {
86  if (!ShouldCloneDefinition(&*I)) {
87  // An alias cannot act as an external reference, so we need to create
88  // either a function or a global variable depending on the value type.
89  // FIXME: Once pointee types are gone we can probably pick one or the
90  // other.
91  GlobalValue *GV;
92  if (I->getValueType()->isFunctionTy())
93  GV = Function::Create(cast<FunctionType>(I->getValueType()),
95  I->getAddressSpace(), I->getName(), New.get());
96  else
97  GV = new GlobalVariable(
98  *New, I->getValueType(), false, GlobalValue::ExternalLinkage,
99  nullptr, I->getName(), nullptr,
100  I->getThreadLocalMode(), I->getType()->getAddressSpace());
101  VMap[&*I] = GV;
102  // We do not copy attributes (mainly because copying between different
103  // kinds of globals is forbidden), but this is generally not required for
104  // correctness.
105  continue;
106  }
107  auto *GA = GlobalAlias::create(I->getValueType(),
108  I->getType()->getPointerAddressSpace(),
109  I->getLinkage(), I->getName(), New.get());
110  GA->copyAttributesFrom(&*I);
111  VMap[&*I] = GA;
112  }
113 
114  // Now that all of the things that global variable initializer can refer to
115  // have been created, loop through and copy the global variable referrers
116  // over... We also set the attributes on the global now.
117  //
118  for (const GlobalVariable &G : M.globals()) {
119  GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
120 
122  G.getAllMetadata(MDs);
123  for (auto MD : MDs)
124  GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
125 
126  if (G.isDeclaration())
127  continue;
128 
129  if (!ShouldCloneDefinition(&G)) {
130  // Skip after setting the correct linkage for an external reference.
132  continue;
133  }
134  if (G.hasInitializer())
135  GV->setInitializer(MapValue(G.getInitializer(), VMap));
136 
137  copyComdat(GV, &G);
138  }
139 
140  // Similarly, copy over function bodies now...
141  //
142  for (const Function &I : M) {
143  if (I.isDeclaration())
144  continue;
145 
146  Function *F = cast<Function>(VMap[&I]);
147  if (!ShouldCloneDefinition(&I)) {
148  // Skip after setting the correct linkage for an external reference.
149  F->setLinkage(GlobalValue::ExternalLinkage);
150  // Personality function is not valid on a declaration.
151  F->setPersonalityFn(nullptr);
152  continue;
153  }
154 
155  Function::arg_iterator DestI = F->arg_begin();
156  for (Function::const_arg_iterator J = I.arg_begin(); J != I.arg_end();
157  ++J) {
158  DestI->setName(J->getName());
159  VMap[&*J] = &*DestI++;
160  }
161 
162  SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
164  Returns);
165 
166  if (I.hasPersonalityFn())
167  F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
168 
169  copyComdat(F, &I);
170  }
171 
172  // And aliases
173  for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end();
174  I != E; ++I) {
175  // We already dealt with undefined aliases above.
176  if (!ShouldCloneDefinition(&*I))
177  continue;
178  GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
179  if (const Constant *C = I->getAliasee())
180  GA->setAliasee(MapValue(C, VMap));
181  }
182 
183  // And named metadata....
184  for (Module::const_named_metadata_iterator I = M.named_metadata_begin(),
185  E = M.named_metadata_end();
186  I != E; ++I) {
187  const NamedMDNode &NMD = *I;
188  NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
189  for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
190  NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
191  }
192 
193  return New;
194 }
195 
196 extern "C" {
197 
199  return wrap(CloneModule(*unwrap(M)).release());
200 }
201 
202 }
i
i
Definition: README.txt:29
llvm::Argument
This class represents an incoming formal argument to a Function.
Definition: Argument.h:29
llvm
---------------------— PointerInfo ------------------------------------—
Definition: AllocatorList.h:23
M
We currently emits eax Perhaps this is what we really should generate is Is imull three or four cycles eax eax The current instruction priority is based on pattern complexity The former is more complex because it folds a load so the latter will not be emitted Perhaps we should use AddedComplexity to give LEA32r a higher priority We should always try to match LEA first since the LEA matching code does some estimate to determine whether the match is profitable if we care more about code then imull is better It s two bytes shorter than movl leal On a Pentium M
Definition: README.txt:252
llvm::NamedMDNode
A tuple of MDNodes.
Definition: Metadata.h:1396
ValueMapper.h
llvm::MapMetadata
Metadata * MapMetadata(const Metadata *MD, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Lookup or compute a mapping for a piece of metadata.
Definition: ValueMapper.h:230
llvm::NamedMDNode::getNumOperands
unsigned getNumOperands() const
Definition: Metadata.cpp:1120
llvm::GlobalVariable::copyAttributesFrom
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:412
llvm::Function
Definition: Function.h:61
llvm::SmallVector
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1168
LLVMCloneModule
LLVMModuleRef LLVMCloneModule(LLVMModuleRef M)
Return an exact copy of the specified module.
Definition: CloneModule.cpp:198
llvm::GlobalVariable
Definition: GlobalVariable.h:40
llvm::GlobalAlias
Definition: GlobalAlias.h:27
copyComdat
static void copyComdat(GlobalObject *Dst, const GlobalObject *Src)
Definition: CloneModule.cpp:21
llvm::CloneFunctionChangeType::ClonedModule
@ ClonedModule
llvm::MapValue
Value * MapValue(const Value *V, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Look up or compute a value in the value map.
Definition: ValueMapper.h:208
llvm::AtomicOrderingCABI::release
@ release
Module.h
llvm::Module::const_alias_iterator
AliasListType::const_iterator const_alias_iterator
The Global Alias constant iterator.
Definition: Module.h:104
F
#define F(x, y, z)
Definition: MD5.cpp:56
llvm::NamedMDNode::addOperand
void addOperand(MDNode *M)
Definition: Metadata.cpp:1130
llvm::PPCISD::SC
@ SC
CHAIN = SC CHAIN, Imm128 - System call.
Definition: PPCISelLowering.h:410
E
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
C
(vector float) vec_cmpeq(*A, *B) C
Definition: README_ALTIVEC.txt:86
llvm::GlobalObject
Definition: GlobalObject.h:28
llvm::NamedMDNode::getName
StringRef getName() const
Definition: Metadata.cpp:1141
llvm::unwrap
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:256
llvm::Function::copyAttributesFrom
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:712
llvm::GlobalObject::addMetadata
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1268
llvm::Value::setName
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:376
llvm::Comdat
Definition: Comdat.h:31
llvm::function_ref
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:168
G
const DataFlowGraph & G
Definition: RDFGraph.cpp:202
llvm::GlobalValue
Definition: GlobalValue.h:44
llvm::Constant
This is an important base class in LLVM.
Definition: Constant.h:41
llvm::numbers::e
constexpr double e
Definition: MathExtras.h:57
I
#define I(x, y, z)
Definition: MD5.cpp:59
Cloning.h
llvm::GlobalValue::setLinkage
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:460
llvm::NamedMDNode::getOperand
MDNode * getOperand(unsigned i) const
Definition: Metadata.cpp:1124
llvm::Function::Create
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:138
llvm::Module
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:67
llvm::wrap
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:251
DC
static ManagedStatic< DebugCounter > DC
Definition: DebugCounter.cpp:70
llvm::ValueMap< const Value *, WeakTrackingVH >
Constant.h
llvm::GlobalAlias::create
static GlobalAlias * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Aliasee, Module *Parent)
If a parent module is specified, the alias is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:480
llvm::ilist_iterator
Iterator for intrusive lists based on ilist_node.
Definition: ilist_iterator.h:57
llvm::GlobalValue::ExternalLinkage
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
llvm::Module::const_global_iterator
GlobalListType::const_iterator const_global_iterator
The Global Variable constant iterator.
Definition: Module.h:89
llvm::CloneModule
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
Definition: CloneModule.cpp:34
DerivedTypes.h
llvm::CloneFunctionInto
void CloneFunctionInto(Function *NewFunc, const Function *OldFunc, ValueToValueMapTy &VMap, CloneFunctionChangeType Changes, SmallVectorImpl< ReturnInst * > &Returns, const char *NameSuffix="", ClonedCodeInfo *CodeInfo=nullptr, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr)
Clone OldFunc into NewFunc, transforming the old arguments into references to VMap values.
Definition: CloneFunction.cpp:83
llvm::GlobalAlias::setAliasee
void setAliasee(Constant *Aliasee)
These methods retrieve and set alias target.
Definition: Globals.cpp:516
llvm::GlobalVariable::setInitializer
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:389
LLVMModuleRef
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61