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-c/Core.h"
15#include "llvm/IR/DerivedTypes.h"
16#include "llvm/IR/Module.h"
17#include "llvm/Transforms/Utils/Cloning.h"
18#include "llvm/Transforms/Utils/ValueMapper.h"
19using namespace llvm;
20
21namespace llvm {
22class Constant;
23}
24
25static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
26 const Comdat *SC = Src->getComdat();
27 if (!SC)
28 return;
29 Comdat *DC = Dst->getParent()->getOrInsertComdat(Name: SC->getName());
30 DC->setSelectionKind(SC->getSelectionKind());
31 Dst->setComdat(DC);
32}
33
34/// This is not as easy as it might seem because we have to worry about making
35/// copies of global variables and functions, and making their (initializers and
36/// references, respectively) refer to the right globals.
37///
38/// Cloning un-materialized modules is not currently supported, so any
39/// modules initialized via lazy loading should be materialized before cloning
40std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
41 // Create the value map that maps things from the old module over to the new
42 // module.
43 ValueToValueMapTy VMap;
44 return CloneModule(M, VMap);
45}
46
47std::unique_ptr<Module> llvm::CloneModule(const Module &M,
48 ValueToValueMapTy &VMap) {
49 return CloneModule(M, VMap, ShouldCloneDefinition: [](const GlobalValue *GV) { return true; });
50}
51
52std::unique_ptr<Module> llvm::CloneModule(
53 const Module &M, ValueToValueMapTy &VMap,
54 function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
55
56 assert(M.isMaterialized() && "Module must be materialized before cloning!");
57
58 // First off, we need to create the new module.
59 std::unique_ptr<Module> New =
60 std::make_unique<Module>(args: M.getModuleIdentifier(), args&: M.getContext());
61 New->setSourceFileName(M.getSourceFileName());
62 New->setDataLayout(M.getDataLayout());
63 New->setTargetTriple(M.getTargetTriple());
64 New->setModuleInlineAsm(M.getModuleInlineAsm());
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(Src: &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(Ty: I.getFunctionType(), Linkage: I.getLinkage(),
83 AddrSpace: I.getAddressSpace(), N: I.getName(), M: New.get());
84 NF->copyAttributesFrom(Src: &I);
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(Ty: cast<FunctionType>(Val: I.getValueType()),
98 Linkage: GlobalValue::ExternalLinkage, AddrSpace: I.getAddressSpace(),
99 N: I.getName(), M: New.get());
100 else
101 GV = new GlobalVariable(*New, I.getValueType(), false,
102 GlobalValue::ExternalLinkage, nullptr,
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(Ty: I.getValueType(),
112 AddressSpace: I.getType()->getPointerAddressSpace(),
113 Linkage: I.getLinkage(), Name: I.getName(), Parent: New.get());
114 GA->copyAttributesFrom(Src: &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 if (!ShouldCloneDefinition(&I)) {
121 // An ifunc also cannot act as an external reference, so we need to create
122 // a function.
123 GlobalValue *GV;
124 assert(I.getValueType()->isFunctionTy() &&
125 "ValueType of ifunc must be function type!");
126 GV = Function::Create(Ty: cast<FunctionType>(Val: I.getValueType()),
127 Linkage: GlobalValue::ExternalLinkage, AddrSpace: I.getAddressSpace(),
128 N: I.getName(), M: New.get());
129 VMap[&I] = GV;
130 continue;
131 }
132 auto *GI =
133 GlobalIFunc::create(Ty: I.getValueType(), AddressSpace: I.getAddressSpace(),
134 Linkage: I.getLinkage(), Name: I.getName(), Resolver: nullptr, Parent: New.get());
135 GI->copyAttributesFrom(Src: &I);
136 VMap[&I] = GI;
137 }
138
139 // Similarly, copy over function bodies now...
140 //
141 for (const Function &I : M) {
142 Function *F = cast<Function>(Val&: VMap[&I]);
143
144 if (I.isDeclaration()) {
145 // Copy over metadata for declarations since we're not doing it below in
146 // CloneFunctionInto().
147 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
148 I.getAllMetadata(MDs);
149 for (auto MD : MDs)
150 F->addMetadata(KindID: MD.first, MD&: *MapMetadata(MD: MD.second, VM&: VMap));
151 continue;
152 }
153
154 if (!ShouldCloneDefinition(&I)) {
155 // Skip after setting the correct linkage for an external reference.
156 F->setLinkage(GlobalValue::ExternalLinkage);
157 // Personality function is not valid on a declaration.
158 F->setPersonalityFn(nullptr);
159 continue;
160 }
161
162 Function::arg_iterator DestI = F->arg_begin();
163 for (const Argument &J : I.args()) {
164 DestI->setName(J.getName());
165 VMap[&J] = &*DestI++;
166 }
167
168 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
169 CloneFunctionInto(NewFunc: F, OldFunc: &I, VMap, Changes: CloneFunctionChangeType::ClonedModule,
170 Returns);
171
172 if (I.hasPersonalityFn())
173 F->setPersonalityFn(MapValue(V: I.getPersonalityFn(), VM&: VMap));
174
175 copyComdat(Dst: F, Src: &I);
176 }
177
178 // And aliases
179 for (const GlobalAlias &I : M.aliases()) {
180 // We already dealt with undefined aliases above.
181 if (!ShouldCloneDefinition(&I))
182 continue;
183 GlobalAlias *GA = cast<GlobalAlias>(Val&: VMap[&I]);
184 if (const Constant *C = I.getAliasee())
185 GA->setAliasee(MapValue(V: C, VM&: VMap));
186 }
187
188 for (const GlobalIFunc &I : M.ifuncs()) {
189 // We already dealt with undefined ifuncs above.
190 if (!ShouldCloneDefinition(&I))
191 continue;
192 GlobalIFunc *GI = cast<GlobalIFunc>(Val&: VMap[&I]);
193 if (const Constant *Resolver = I.getResolver())
194 GI->setResolver(MapValue(V: Resolver, VM&: VMap));
195 }
196
197 // And named metadata....
198 for (const NamedMDNode &NMD : M.named_metadata()) {
199 NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(Name: NMD.getName());
200 for (const MDNode *N : NMD.operands())
201 NewNMD->addOperand(M: MapMetadata(MD: N, VM&: VMap));
202 }
203
204 // Now that all of the things that global variable initializer can refer to
205 // have been created, loop through and copy the global variable referrers
206 // over... We also set the attributes on the global now.
207 //
208 for (const GlobalVariable &G : M.globals()) {
209 GlobalVariable *GV = cast<GlobalVariable>(Val&: VMap[&G]);
210
211 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
212 G.getAllMetadata(MDs);
213 for (auto MD : MDs)
214 GV->addMetadata(KindID: MD.first, MD&: *MapMetadata(MD: MD.second, VM&: VMap));
215
216 if (G.isDeclaration())
217 continue;
218
219 if (!ShouldCloneDefinition(&G)) {
220 // Skip after setting the correct linkage for an external reference.
221 GV->setLinkage(GlobalValue::ExternalLinkage);
222 continue;
223 }
224 if (G.hasInitializer())
225 GV->setInitializer(MapValue(V: G.getInitializer(), VM&: VMap));
226
227 copyComdat(Dst: GV, Src: &G);
228 }
229
230 return New;
231}
232
233extern "C" {
234
235LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
236 return wrap(P: CloneModule(M: *unwrap(P: M)).release());
237}
238
239}
240