LLVM 18.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
15#include "llvm/IR/Module.h"
18using namespace llvm;
19
20namespace llvm {
21class Constant;
22}
23
24static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
25 const Comdat *SC = Src->getComdat();
26 if (!SC)
27 return;
28 Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
29 DC->setSelectionKind(SC->getSelectionKind());
30 Dst->setComdat(DC);
31}
32
33/// This is not as easy as it might seem because we have to worry about making
34/// copies of global variables and functions, and making their (initializers and
35/// references, respectively) refer to the right globals.
36///
37std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
38 // Create the value map that maps things from the old module over to the new
39 // module.
41 return CloneModule(M, VMap);
42}
43
44std::unique_ptr<Module> llvm::CloneModule(const Module &M,
45 ValueToValueMapTy &VMap) {
46 return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
47}
48
49std::unique_ptr<Module> llvm::CloneModule(
50 const Module &M, ValueToValueMapTy &VMap,
51 function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
52 // First off, we need to create the new module.
53 std::unique_ptr<Module> New =
54 std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
55 New->setSourceFileName(M.getSourceFileName());
56 New->setDataLayout(M.getDataLayout());
57 New->setTargetTriple(M.getTargetTriple());
58 New->setModuleInlineAsm(M.getModuleInlineAsm());
59
60 // Loop over all of the global variables, making corresponding globals in the
61 // new module. Here we add them to the VMap and to the new Module. We
62 // don't worry about attributes or initializers, they will come later.
63 //
64 for (const GlobalVariable &I : M.globals()) {
65 GlobalVariable *NewGV = new GlobalVariable(
66 *New, I.getValueType(), I.isConstant(), I.getLinkage(),
67 (Constant *)nullptr, I.getName(), (GlobalVariable *)nullptr,
68 I.getThreadLocalMode(), I.getType()->getAddressSpace());
69 NewGV->copyAttributesFrom(&I);
70 VMap[&I] = NewGV;
71 }
72
73 // Loop over the functions in the module, making external functions as before
74 for (const Function &I : M) {
75 Function *NF =
76 Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
77 I.getAddressSpace(), I.getName(), New.get());
79 VMap[&I] = NF;
80 }
81
82 // Loop over the aliases in the module
83 for (const GlobalAlias &I : M.aliases()) {
84 if (!ShouldCloneDefinition(&I)) {
85 // An alias cannot act as an external reference, so we need to create
86 // either a function or a global variable depending on the value type.
87 // FIXME: Once pointee types are gone we can probably pick one or the
88 // other.
89 GlobalValue *GV;
90 if (I.getValueType()->isFunctionTy())
91 GV = Function::Create(cast<FunctionType>(I.getValueType()),
92 GlobalValue::ExternalLinkage, I.getAddressSpace(),
93 I.getName(), New.get());
94 else
95 GV = new GlobalVariable(*New, I.getValueType(), false,
97 I.getName(), nullptr, I.getThreadLocalMode(),
98 I.getType()->getAddressSpace());
99 VMap[&I] = GV;
100 // We do not copy attributes (mainly because copying between different
101 // kinds of globals is forbidden), but this is generally not required for
102 // correctness.
103 continue;
104 }
105 auto *GA = GlobalAlias::create(I.getValueType(),
106 I.getType()->getPointerAddressSpace(),
107 I.getLinkage(), I.getName(), New.get());
108 GA->copyAttributesFrom(&I);
109 VMap[&I] = GA;
110 }
111
112 for (const GlobalIFunc &I : M.ifuncs()) {
113 // Defer setting the resolver function until after functions are cloned.
114 auto *GI =
115 GlobalIFunc::create(I.getValueType(), I.getAddressSpace(),
116 I.getLinkage(), I.getName(), nullptr, New.get());
117 GI->copyAttributesFrom(&I);
118 VMap[&I] = GI;
119 }
120
121 // Now that all of the things that global variable initializer can refer to
122 // have been created, loop through and copy the global variable referrers
123 // over... We also set the attributes on the global now.
124 //
125 for (const GlobalVariable &G : M.globals()) {
126 GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
127
129 G.getAllMetadata(MDs);
130 for (auto MD : MDs)
131 GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
132
133 if (G.isDeclaration())
134 continue;
135
136 if (!ShouldCloneDefinition(&G)) {
137 // Skip after setting the correct linkage for an external reference.
139 continue;
140 }
141 if (G.hasInitializer())
142 GV->setInitializer(MapValue(G.getInitializer(), VMap));
143
144 copyComdat(GV, &G);
145 }
146
147 // Similarly, copy over function bodies now...
148 //
149 for (const Function &I : M) {
150 Function *F = cast<Function>(VMap[&I]);
151
152 if (I.isDeclaration()) {
153 // Copy over metadata for declarations since we're not doing it below in
154 // CloneFunctionInto().
156 I.getAllMetadata(MDs);
157 for (auto MD : MDs)
158 F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
159 continue;
160 }
161
162 if (!ShouldCloneDefinition(&I)) {
163 // Skip after setting the correct linkage for an external reference.
164 F->setLinkage(GlobalValue::ExternalLinkage);
165 // Personality function is not valid on a declaration.
166 F->setPersonalityFn(nullptr);
167 continue;
168 }
169
170 Function::arg_iterator DestI = F->arg_begin();
171 for (const Argument &J : I.args()) {
172 DestI->setName(J.getName());
173 VMap[&J] = &*DestI++;
174 }
175
176 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
178 Returns);
179
180 if (I.hasPersonalityFn())
181 F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
182
183 copyComdat(F, &I);
184 }
185
186 // And aliases
187 for (const GlobalAlias &I : M.aliases()) {
188 // We already dealt with undefined aliases above.
189 if (!ShouldCloneDefinition(&I))
190 continue;
191 GlobalAlias *GA = cast<GlobalAlias>(VMap[&I]);
192 if (const Constant *C = I.getAliasee())
193 GA->setAliasee(MapValue(C, VMap));
194 }
195
196 for (const GlobalIFunc &I : M.ifuncs()) {
197 GlobalIFunc *GI = cast<GlobalIFunc>(VMap[&I]);
198 if (const Constant *Resolver = I.getResolver())
199 GI->setResolver(MapValue(Resolver, VMap));
200 }
201
202 // And named metadata....
203 for (const NamedMDNode &NMD : M.named_metadata()) {
204 NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
205 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
206 NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
207 }
208
209 return New;
210}
211
212extern "C" {
213
215 return wrap(CloneModule(*unwrap(M)).release());
216}
217
218}
static void copyComdat(GlobalObject *Dst, const GlobalObject *Src)
Definition: CloneModule.cpp:24
#define F(x, y, z)
Definition: MD5.cpp:55
#define I(x, y, z)
Definition: MD5.cpp:58
#define G(x, y, z)
Definition: MD5.cpp:56
Module.h This file contains the declarations for the Module class.
This class represents an incoming formal argument to a Function.
Definition: Argument.h:28
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:47
This is an important base class in LLVM.
Definition: Constant.h:41
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:138
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:757
void setAliasee(Constant *Aliasee)
These methods retrieve and set alias target.
Definition: Globals.cpp:538
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:506
static GlobalIFunc * create(Type *Ty, unsigned AddressSpace, LinkageTypes Linkage, const Twine &Name, Constant *Resolver, Module *Parent)
If a parent module is specified, the ifunc is automatically inserted into the end of the specified mo...
Definition: Globals.cpp:563
void setResolver(Constant *Resolver)
These methods retrieve and set ifunc resolver function.
Definition: GlobalIFunc.h:69
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1425
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:532
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:48
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:458
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:481
A Module instance is used to store all the information related to an LLVM module.
Definition: Module.h:65
A tuple of MDNodes.
Definition: Metadata.h:1604
void addOperand(MDNode *M)
Definition: Metadata.cpp:1287
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2190
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1200
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:378
An efficient, type-erasing, non-owning reference to a callable.
LLVMModuleRef LLVMCloneModule(LLVMModuleRef M)
Return an exact copy of the specified module.
struct LLVMOpaqueModule * LLVMModuleRef
The top-level container for all other LLVM Intermediate Representation (IR) objects.
Definition: Types.h:61
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
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:233
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:211
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:287
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.
LLVMAttributeRef wrap(Attribute Attr)
Definition: Attributes.h:282
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
Definition: CloneModule.cpp:37