LLVM 20.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///
37/// Cloning un-materialized modules is not currently supported, so any
38/// modules initialized via lazy loading should be materialized before cloning
39std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
40 // Create the value map that maps things from the old module over to the new
41 // module.
43 return CloneModule(M, VMap);
44}
45
46std::unique_ptr<Module> llvm::CloneModule(const Module &M,
47 ValueToValueMapTy &VMap) {
48 return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
49}
50
51std::unique_ptr<Module> llvm::CloneModule(
52 const Module &M, ValueToValueMapTy &VMap,
53 function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
54
55 assert(M.isMaterialized() && "Module must be materialized before cloning!");
56
57 // First off, we need to create the new module.
58 std::unique_ptr<Module> New =
59 std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
60 New->setSourceFileName(M.getSourceFileName());
61 New->setDataLayout(M.getDataLayout());
62 New->setTargetTriple(M.getTargetTriple());
63 New->setModuleInlineAsm(M.getModuleInlineAsm());
64 New->IsNewDbgInfoFormat = M.IsNewDbgInfoFormat;
65
66 // Loop over all of the global variables, making corresponding globals in the
67 // new module. Here we add them to the VMap and to the new Module. We
68 // don't worry about attributes or initializers, they will come later.
69 //
70 for (const GlobalVariable &I : M.globals()) {
71 GlobalVariable *NewGV = new GlobalVariable(
72 *New, I.getValueType(), I.isConstant(), I.getLinkage(),
73 (Constant *)nullptr, I.getName(), (GlobalVariable *)nullptr,
74 I.getThreadLocalMode(), I.getType()->getAddressSpace());
75 NewGV->copyAttributesFrom(&I);
76 VMap[&I] = NewGV;
77 }
78
79 // Loop over the functions in the module, making external functions as before
80 for (const Function &I : M) {
81 Function *NF =
82 Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
83 I.getAddressSpace(), I.getName(), New.get());
85 VMap[&I] = NF;
86 }
87
88 // Loop over the aliases in the module
89 for (const GlobalAlias &I : M.aliases()) {
90 if (!ShouldCloneDefinition(&I)) {
91 // An alias cannot act as an external reference, so we need to create
92 // either a function or a global variable depending on the value type.
93 // FIXME: Once pointee types are gone we can probably pick one or the
94 // other.
95 GlobalValue *GV;
96 if (I.getValueType()->isFunctionTy())
97 GV = Function::Create(cast<FunctionType>(I.getValueType()),
98 GlobalValue::ExternalLinkage, I.getAddressSpace(),
99 I.getName(), New.get());
100 else
101 GV = new GlobalVariable(*New, I.getValueType(), false,
103 I.getName(), nullptr, I.getThreadLocalMode(),
104 I.getType()->getAddressSpace());
105 VMap[&I] = GV;
106 // We do not copy attributes (mainly because copying between different
107 // kinds of globals is forbidden), but this is generally not required for
108 // correctness.
109 continue;
110 }
111 auto *GA = GlobalAlias::create(I.getValueType(),
112 I.getType()->getPointerAddressSpace(),
113 I.getLinkage(), I.getName(), New.get());
114 GA->copyAttributesFrom(&I);
115 VMap[&I] = GA;
116 }
117
118 for (const GlobalIFunc &I : M.ifuncs()) {
119 // Defer setting the resolver function until after functions are cloned.
120 auto *GI =
121 GlobalIFunc::create(I.getValueType(), I.getAddressSpace(),
122 I.getLinkage(), I.getName(), nullptr, New.get());
123 GI->copyAttributesFrom(&I);
124 VMap[&I] = GI;
125 }
126
127 // Now that all of the things that global variable initializer can refer to
128 // have been created, loop through and copy the global variable referrers
129 // over... We also set the attributes on the global now.
130 //
131 for (const GlobalVariable &G : M.globals()) {
132 GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
133
135 G.getAllMetadata(MDs);
136 for (auto MD : MDs)
137 GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
138
139 if (G.isDeclaration())
140 continue;
141
142 if (!ShouldCloneDefinition(&G)) {
143 // Skip after setting the correct linkage for an external reference.
145 continue;
146 }
147 if (G.hasInitializer())
148 GV->setInitializer(MapValue(G.getInitializer(), VMap));
149
150 copyComdat(GV, &G);
151 }
152
153 // Similarly, copy over function bodies now...
154 //
155 for (const Function &I : M) {
156 Function *F = cast<Function>(VMap[&I]);
157
158 if (I.isDeclaration()) {
159 // Copy over metadata for declarations since we're not doing it below in
160 // CloneFunctionInto().
162 I.getAllMetadata(MDs);
163 for (auto MD : MDs)
164 F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
165 continue;
166 }
167
168 if (!ShouldCloneDefinition(&I)) {
169 // Skip after setting the correct linkage for an external reference.
170 F->setLinkage(GlobalValue::ExternalLinkage);
171 // Personality function is not valid on a declaration.
172 F->setPersonalityFn(nullptr);
173 continue;
174 }
175
176 Function::arg_iterator DestI = F->arg_begin();
177 for (const Argument &J : I.args()) {
178 DestI->setName(J.getName());
179 VMap[&J] = &*DestI++;
180 }
181
182 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
184 Returns);
185
186 if (I.hasPersonalityFn())
187 F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
188
189 copyComdat(F, &I);
190 }
191
192 // And aliases
193 for (const GlobalAlias &I : M.aliases()) {
194 // We already dealt with undefined aliases above.
195 if (!ShouldCloneDefinition(&I))
196 continue;
197 GlobalAlias *GA = cast<GlobalAlias>(VMap[&I]);
198 if (const Constant *C = I.getAliasee())
199 GA->setAliasee(MapValue(C, VMap));
200 }
201
202 for (const GlobalIFunc &I : M.ifuncs()) {
203 GlobalIFunc *GI = cast<GlobalIFunc>(VMap[&I]);
204 if (const Constant *Resolver = I.getResolver())
205 GI->setResolver(MapValue(Resolver, VMap));
206 }
207
208 // And named metadata....
209 for (const NamedMDNode &NMD : M.named_metadata()) {
210 NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
211 for (const MDNode *N : NMD.operands())
212 NewNMD->addOperand(MapMetadata(N, VMap));
213 }
214
215 return New;
216}
217
218extern "C" {
219
221 return wrap(CloneModule(*unwrap(M)).release());
222}
223
224}
static void copyComdat(GlobalObject *Dst, const GlobalObject *Src)
Definition: CloneModule.cpp:24
Module.h This file contains the declarations for the Module class.
#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
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This class represents an incoming formal argument to a Function.
Definition: Argument.h:31
void setSelectionKind(SelectionKind Val)
Definition: Comdat.h:47
This is an important base class in LLVM.
Definition: Constant.h:42
static Function * Create(FunctionType *Ty, LinkageTypes Linkage, unsigned AddrSpace, const Twine &N="", Module *M=nullptr)
Definition: Function.h:173
void copyAttributesFrom(const Function *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a Function) from the ...
Definition: Function.cpp:860
void setAliasee(Constant *Aliasee)
These methods retrieve and set alias target.
Definition: Globals.cpp:589
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:557
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:614
void setResolver(Constant *Resolver)
These methods retrieve and set ifunc resolver function.
Definition: GlobalIFunc.h:71
void addMetadata(unsigned KindID, MDNode &MD)
Add a metadata attachment.
Definition: Metadata.cpp:1565
void setLinkage(LinkageTypes LT)
Definition: GlobalValue.h:537
@ ExternalLinkage
Externally visible function.
Definition: GlobalValue.h:52
void setInitializer(Constant *InitVal)
setInitializer - Sets the initializer for this global variable, removing any existing initializer if ...
Definition: Globals.cpp:492
void copyAttributesFrom(const GlobalVariable *Src)
copyAttributesFrom - copy all additional attributes (those not needed to create a GlobalVariable) fro...
Definition: Globals.cpp:521
Metadata node.
Definition: Metadata.h:1069
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:1731
void addOperand(MDNode *M)
Definition: Metadata.cpp:1431
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:2203
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1196
void setName(const Twine &Name)
Change the name of the value.
Definition: Value.cpp:377
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:240
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:218
Attribute unwrap(LLVMAttributeRef Attr)
Definition: Attributes.h:332
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:327
std::unique_ptr< Module > CloneModule(const Module &M)
Return an exact copy of the specified module.
Definition: CloneModule.cpp:39
#define N