xref: /src/contrib/llvm-project/llvm/lib/Transforms/Utils/CloneModule.cpp (revision 0fca6ea1d4eea4c934cfff25ac9ee8ad6fe95583)
1009b1c42SEd Schouten //===- CloneModule.cpp - Clone an entire module ---------------------------===//
2009b1c42SEd Schouten //
3e6d15924SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e6d15924SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5e6d15924SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6009b1c42SEd Schouten //
7009b1c42SEd Schouten //===----------------------------------------------------------------------===//
8009b1c42SEd Schouten //
9009b1c42SEd Schouten // This file implements the CloneModule interface which makes a copy of an
10009b1c42SEd Schouten // entire module.
11009b1c42SEd Schouten //
12009b1c42SEd Schouten //===----------------------------------------------------------------------===//
13009b1c42SEd Schouten 
144a16efa3SDimitry Andric #include "llvm/IR/DerivedTypes.h"
154a16efa3SDimitry Andric #include "llvm/IR/Module.h"
167ab83427SDimitry Andric #include "llvm/Transforms/Utils/Cloning.h"
17d39c594dSDimitry Andric #include "llvm/Transforms/Utils/ValueMapper.h"
18009b1c42SEd Schouten using namespace llvm;
19009b1c42SEd Schouten 
20145449b1SDimitry Andric namespace llvm {
21145449b1SDimitry Andric class Constant;
22145449b1SDimitry Andric }
23145449b1SDimitry Andric 
copyComdat(GlobalObject * Dst,const GlobalObject * Src)2471d5a254SDimitry Andric static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) {
2571d5a254SDimitry Andric   const Comdat *SC = Src->getComdat();
2671d5a254SDimitry Andric   if (!SC)
2771d5a254SDimitry Andric     return;
2871d5a254SDimitry Andric   Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName());
2971d5a254SDimitry Andric   DC->setSelectionKind(SC->getSelectionKind());
3071d5a254SDimitry Andric   Dst->setComdat(DC);
3171d5a254SDimitry Andric }
3271d5a254SDimitry Andric 
33dd58ef01SDimitry Andric /// This is not as easy as it might seem because we have to worry about making
34dd58ef01SDimitry Andric /// copies of global variables and functions, and making their (initializers and
35dd58ef01SDimitry Andric /// references, respectively) refer to the right globals.
36009b1c42SEd Schouten ///
37b1c73532SDimitry Andric /// Cloning un-materialized modules is not currently supported, so any
38b1c73532SDimitry Andric /// modules initialized via lazy loading should be materialized before cloning
CloneModule(const Module & M)39eb11fae6SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(const Module &M) {
40009b1c42SEd Schouten   // Create the value map that maps things from the old module over to the new
41009b1c42SEd Schouten   // module.
4266e41e3cSRoman Divacky   ValueToValueMapTy VMap;
4366e41e3cSRoman Divacky   return CloneModule(M, VMap);
44009b1c42SEd Schouten }
45009b1c42SEd Schouten 
CloneModule(const Module & M,ValueToValueMapTy & VMap)46eb11fae6SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(const Module &M,
47dd58ef01SDimitry Andric                                           ValueToValueMapTy &VMap) {
48dd58ef01SDimitry Andric   return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
49dd58ef01SDimitry Andric }
50dd58ef01SDimitry Andric 
CloneModule(const Module & M,ValueToValueMapTy & VMap,function_ref<bool (const GlobalValue *)> ShouldCloneDefinition)51dd58ef01SDimitry Andric std::unique_ptr<Module> llvm::CloneModule(
52eb11fae6SDimitry Andric     const Module &M, ValueToValueMapTy &VMap,
5301095a5dSDimitry Andric     function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
54b1c73532SDimitry Andric 
55b1c73532SDimitry Andric   assert(M.isMaterialized() && "Module must be materialized before cloning!");
56b1c73532SDimitry Andric 
57411bd29eSDimitry Andric   // First off, we need to create the new module.
58dd58ef01SDimitry Andric   std::unique_ptr<Module> New =
591d5ae102SDimitry Andric       std::make_unique<Module>(M.getModuleIdentifier(), M.getContext());
60eb11fae6SDimitry Andric   New->setSourceFileName(M.getSourceFileName());
61eb11fae6SDimitry Andric   New->setDataLayout(M.getDataLayout());
62eb11fae6SDimitry Andric   New->setTargetTriple(M.getTargetTriple());
63eb11fae6SDimitry Andric   New->setModuleInlineAsm(M.getModuleInlineAsm());
64b1c73532SDimitry Andric   New->IsNewDbgInfoFormat = M.IsNewDbgInfoFormat;
65009b1c42SEd Schouten 
66009b1c42SEd Schouten   // Loop over all of the global variables, making corresponding globals in the
6766e41e3cSRoman Divacky   // new module.  Here we add them to the VMap and to the new Module.  We
68009b1c42SEd Schouten   // don't worry about attributes or initializers, they will come later.
69009b1c42SEd Schouten   //
70846a2208SDimitry Andric   for (const GlobalVariable &I : M.globals()) {
71846a2208SDimitry Andric     GlobalVariable *NewGV = new GlobalVariable(
72846a2208SDimitry Andric         *New, I.getValueType(), I.isConstant(), I.getLinkage(),
73846a2208SDimitry Andric         (Constant *)nullptr, I.getName(), (GlobalVariable *)nullptr,
74846a2208SDimitry Andric         I.getThreadLocalMode(), I.getType()->getAddressSpace());
75846a2208SDimitry Andric     NewGV->copyAttributesFrom(&I);
76846a2208SDimitry Andric     VMap[&I] = NewGV;
77009b1c42SEd Schouten   }
78009b1c42SEd Schouten 
79009b1c42SEd Schouten   // Loop over the functions in the module, making external functions as before
80eb11fae6SDimitry Andric   for (const Function &I : M) {
81d8e91e46SDimitry Andric     Function *NF =
82d8e91e46SDimitry Andric         Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(),
83d8e91e46SDimitry Andric                          I.getAddressSpace(), I.getName(), New.get());
8401095a5dSDimitry Andric     NF->copyAttributesFrom(&I);
8501095a5dSDimitry Andric     VMap[&I] = NF;
86009b1c42SEd Schouten   }
87009b1c42SEd Schouten 
88009b1c42SEd Schouten   // Loop over the aliases in the module
89846a2208SDimitry Andric   for (const GlobalAlias &I : M.aliases()) {
90846a2208SDimitry Andric     if (!ShouldCloneDefinition(&I)) {
91dd58ef01SDimitry Andric       // An alias cannot act as an external reference, so we need to create
92dd58ef01SDimitry Andric       // either a function or a global variable depending on the value type.
93dd58ef01SDimitry Andric       // FIXME: Once pointee types are gone we can probably pick one or the
94dd58ef01SDimitry Andric       // other.
95dd58ef01SDimitry Andric       GlobalValue *GV;
96846a2208SDimitry Andric       if (I.getValueType()->isFunctionTy())
97846a2208SDimitry Andric         GV = Function::Create(cast<FunctionType>(I.getValueType()),
98846a2208SDimitry Andric                               GlobalValue::ExternalLinkage, I.getAddressSpace(),
99846a2208SDimitry Andric                               I.getName(), New.get());
100dd58ef01SDimitry Andric       else
101846a2208SDimitry Andric         GV = new GlobalVariable(*New, I.getValueType(), false,
102846a2208SDimitry Andric                                 GlobalValue::ExternalLinkage, nullptr,
103846a2208SDimitry Andric                                 I.getName(), nullptr, I.getThreadLocalMode(),
104846a2208SDimitry Andric                                 I.getType()->getAddressSpace());
105846a2208SDimitry Andric       VMap[&I] = GV;
106dd58ef01SDimitry Andric       // We do not copy attributes (mainly because copying between different
107dd58ef01SDimitry Andric       // kinds of globals is forbidden), but this is generally not required for
108dd58ef01SDimitry Andric       // correctness.
109dd58ef01SDimitry Andric       continue;
110dd58ef01SDimitry Andric     }
111846a2208SDimitry Andric     auto *GA = GlobalAlias::create(I.getValueType(),
112846a2208SDimitry Andric                                    I.getType()->getPointerAddressSpace(),
113846a2208SDimitry Andric                                    I.getLinkage(), I.getName(), New.get());
114846a2208SDimitry Andric     GA->copyAttributesFrom(&I);
115846a2208SDimitry Andric     VMap[&I] = GA;
11630815c53SDimitry Andric   }
117009b1c42SEd Schouten 
118e3b55780SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
119e3b55780SDimitry Andric     // Defer setting the resolver function until after functions are cloned.
120e3b55780SDimitry Andric     auto *GI =
121e3b55780SDimitry Andric         GlobalIFunc::create(I.getValueType(), I.getAddressSpace(),
122e3b55780SDimitry Andric                             I.getLinkage(), I.getName(), nullptr, New.get());
123e3b55780SDimitry Andric     GI->copyAttributesFrom(&I);
124e3b55780SDimitry Andric     VMap[&I] = GI;
125e3b55780SDimitry Andric   }
126e3b55780SDimitry Andric 
127009b1c42SEd Schouten   // Now that all of the things that global variable initializer can refer to
128009b1c42SEd Schouten   // have been created, loop through and copy the global variable referrers
129009b1c42SEd Schouten   // over...  We also set the attributes on the global now.
130009b1c42SEd Schouten   //
131344a3780SDimitry Andric   for (const GlobalVariable &G : M.globals()) {
132344a3780SDimitry Andric     GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]);
133b60736ecSDimitry Andric 
134b60736ecSDimitry Andric     SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
135344a3780SDimitry Andric     G.getAllMetadata(MDs);
136b60736ecSDimitry Andric     for (auto MD : MDs)
137344a3780SDimitry Andric       GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
138b60736ecSDimitry Andric 
139344a3780SDimitry Andric     if (G.isDeclaration())
14001095a5dSDimitry Andric       continue;
14101095a5dSDimitry Andric 
142344a3780SDimitry Andric     if (!ShouldCloneDefinition(&G)) {
143dd58ef01SDimitry Andric       // Skip after setting the correct linkage for an external reference.
144dd58ef01SDimitry Andric       GV->setLinkage(GlobalValue::ExternalLinkage);
145dd58ef01SDimitry Andric       continue;
146dd58ef01SDimitry Andric     }
147344a3780SDimitry Andric     if (G.hasInitializer())
148344a3780SDimitry Andric       GV->setInitializer(MapValue(G.getInitializer(), VMap));
149b915e9e0SDimitry Andric 
150344a3780SDimitry Andric     copyComdat(GV, &G);
151009b1c42SEd Schouten   }
152009b1c42SEd Schouten 
153009b1c42SEd Schouten   // Similarly, copy over function bodies now...
154009b1c42SEd Schouten   //
155eb11fae6SDimitry Andric   for (const Function &I : M) {
15601095a5dSDimitry Andric     Function *F = cast<Function>(VMap[&I]);
157f65dcba8SDimitry Andric 
158f65dcba8SDimitry Andric     if (I.isDeclaration()) {
159f65dcba8SDimitry Andric       // Copy over metadata for declarations since we're not doing it below in
160f65dcba8SDimitry Andric       // CloneFunctionInto().
161f65dcba8SDimitry Andric       SmallVector<std::pair<unsigned, MDNode *>, 1> MDs;
162f65dcba8SDimitry Andric       I.getAllMetadata(MDs);
163f65dcba8SDimitry Andric       for (auto MD : MDs)
164f65dcba8SDimitry Andric         F->addMetadata(MD.first, *MapMetadata(MD.second, VMap));
165f65dcba8SDimitry Andric       continue;
166f65dcba8SDimitry Andric     }
167f65dcba8SDimitry Andric 
16801095a5dSDimitry Andric     if (!ShouldCloneDefinition(&I)) {
169dd58ef01SDimitry Andric       // Skip after setting the correct linkage for an external reference.
170dd58ef01SDimitry Andric       F->setLinkage(GlobalValue::ExternalLinkage);
17101095a5dSDimitry Andric       // Personality function is not valid on a declaration.
17201095a5dSDimitry Andric       F->setPersonalityFn(nullptr);
173dd58ef01SDimitry Andric       continue;
174dd58ef01SDimitry Andric     }
17501095a5dSDimitry Andric 
176009b1c42SEd Schouten     Function::arg_iterator DestI = F->arg_begin();
177846a2208SDimitry Andric     for (const Argument &J : I.args()) {
178846a2208SDimitry Andric       DestI->setName(J.getName());
179846a2208SDimitry Andric       VMap[&J] = &*DestI++;
180009b1c42SEd Schouten     }
181009b1c42SEd Schouten 
18259850d08SRoman Divacky     SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
183344a3780SDimitry Andric     CloneFunctionInto(F, &I, VMap, CloneFunctionChangeType::ClonedModule,
184344a3780SDimitry Andric                       Returns);
1851a82d4c0SDimitry Andric 
18601095a5dSDimitry Andric     if (I.hasPersonalityFn())
18701095a5dSDimitry Andric       F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap));
18871d5a254SDimitry Andric 
18971d5a254SDimitry Andric     copyComdat(F, &I);
190009b1c42SEd Schouten   }
191009b1c42SEd Schouten 
192009b1c42SEd Schouten   // And aliases
193846a2208SDimitry Andric   for (const GlobalAlias &I : M.aliases()) {
194dd58ef01SDimitry Andric     // We already dealt with undefined aliases above.
195846a2208SDimitry Andric     if (!ShouldCloneDefinition(&I))
196dd58ef01SDimitry Andric       continue;
197846a2208SDimitry Andric     GlobalAlias *GA = cast<GlobalAlias>(VMap[&I]);
198846a2208SDimitry Andric     if (const Constant *C = I.getAliasee())
19967c32a98SDimitry Andric       GA->setAliasee(MapValue(C, VMap));
200009b1c42SEd Schouten   }
201009b1c42SEd Schouten 
202e3b55780SDimitry Andric   for (const GlobalIFunc &I : M.ifuncs()) {
203e3b55780SDimitry Andric     GlobalIFunc *GI = cast<GlobalIFunc>(VMap[&I]);
204e3b55780SDimitry Andric     if (const Constant *Resolver = I.getResolver())
205e3b55780SDimitry Andric       GI->setResolver(MapValue(Resolver, VMap));
206e3b55780SDimitry Andric   }
207e3b55780SDimitry Andric 
20866e41e3cSRoman Divacky   // And named metadata....
209846a2208SDimitry Andric   for (const NamedMDNode &NMD : M.named_metadata()) {
210d39c594dSDimitry Andric     NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
211ac9a064cSDimitry Andric     for (const MDNode *N : NMD.operands())
212ac9a064cSDimitry Andric       NewNMD->addOperand(MapMetadata(N, VMap));
21366e41e3cSRoman Divacky   }
21466e41e3cSRoman Divacky 
215009b1c42SEd Schouten   return New;
216009b1c42SEd Schouten }
21767c32a98SDimitry Andric 
21867c32a98SDimitry Andric extern "C" {
21967c32a98SDimitry Andric 
LLVMCloneModule(LLVMModuleRef M)22067c32a98SDimitry Andric LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
221eb11fae6SDimitry Andric   return wrap(CloneModule(*unwrap(M)).release());
22267c32a98SDimitry Andric }
22367c32a98SDimitry Andric 
22467c32a98SDimitry Andric }
225