1 //===- CloneModule.cpp - Clone an entire module ---------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the CloneModule interface which makes a copy of an
11 // entire module.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/Cloning.h"
16 #include "llvm/IR/Constant.h"
17 #include "llvm/IR/DerivedTypes.h"
18 #include "llvm/IR/Module.h"
19 #include "llvm/Transforms/Utils/ValueMapper.h"
20 #include "llvm-c/Core.h"
21 using namespace llvm;
22 
23 /// This is not as easy as it might seem because we have to worry about making
24 /// copies of global variables and functions, and making their (initializers and
25 /// references, respectively) refer to the right globals.
26 ///
27 std::unique_ptr<Module> llvm::CloneModule(const Module *M) {
28   // Create the value map that maps things from the old module over to the new
29   // module.
30   ValueToValueMapTy VMap;
31   return CloneModule(M, VMap);
32 }
33 
34 std::unique_ptr<Module> llvm::CloneModule(const Module *M,
35                                           ValueToValueMapTy &VMap) {
36   return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; });
37 }
38 
39 std::unique_ptr<Module> llvm::CloneModule(
40     const Module *M, ValueToValueMapTy &VMap,
41     function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) {
42   // First off, we need to create the new module.
43   std::unique_ptr<Module> New =
44       llvm::make_unique<Module>(M->getModuleIdentifier(), M->getContext());
45   New->setDataLayout(M->getDataLayout());
46   New->setTargetTriple(M->getTargetTriple());
47   New->setModuleInlineAsm(M->getModuleInlineAsm());
48 
49   // Loop over all of the global variables, making corresponding globals in the
50   // new module.  Here we add them to the VMap and to the new Module.  We
51   // don't worry about attributes or initializers, they will come later.
52   //
53   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
54        I != E; ++I) {
55     GlobalVariable *GV = new GlobalVariable(*New,
56                                             I->getValueType(),
57                                             I->isConstant(), I->getLinkage(),
58                                             (Constant*) nullptr, I->getName(),
59                                             (GlobalVariable*) nullptr,
60                                             I->getThreadLocalMode(),
61                                             I->getType()->getAddressSpace());
62     GV->copyAttributesFrom(&*I);
63     VMap[&*I] = GV;
64   }
65 
66   // Loop over the functions in the module, making external functions as before
67   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
68     Function *NF =
69         Function::Create(cast<FunctionType>(I->getValueType()),
70                          I->getLinkage(), I->getName(), New.get());
71     NF->copyAttributesFrom(&*I);
72     VMap[&*I] = NF;
73   }
74 
75   // Loop over the aliases in the module
76   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
77        I != E; ++I) {
78     if (!ShouldCloneDefinition(&*I)) {
79       // An alias cannot act as an external reference, so we need to create
80       // either a function or a global variable depending on the value type.
81       // FIXME: Once pointee types are gone we can probably pick one or the
82       // other.
83       GlobalValue *GV;
84       if (I->getValueType()->isFunctionTy())
85         GV = Function::Create(cast<FunctionType>(I->getValueType()),
86                               GlobalValue::ExternalLinkage, I->getName(),
87                               New.get());
88       else
89         GV = new GlobalVariable(
90             *New, I->getValueType(), false, GlobalValue::ExternalLinkage,
91             (Constant *)nullptr, I->getName(), (GlobalVariable *)nullptr,
92             I->getThreadLocalMode(), I->getType()->getAddressSpace());
93       VMap[&*I] = GV;
94       // We do not copy attributes (mainly because copying between different
95       // kinds of globals is forbidden), but this is generally not required for
96       // correctness.
97       continue;
98     }
99     auto *GA = GlobalAlias::create(I->getValueType(),
100                                    I->getType()->getPointerAddressSpace(),
101                                    I->getLinkage(), I->getName(), New.get());
102     GA->copyAttributesFrom(&*I);
103     VMap[&*I] = GA;
104   }
105 
106   // Now that all of the things that global variable initializer can refer to
107   // have been created, loop through and copy the global variable referrers
108   // over...  We also set the attributes on the global now.
109   //
110   for (Module::const_global_iterator I = M->global_begin(), E = M->global_end();
111        I != E; ++I) {
112     if (I->isDeclaration())
113       continue;
114 
115     GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]);
116     if (!ShouldCloneDefinition(&*I)) {
117       // Skip after setting the correct linkage for an external reference.
118       GV->setLinkage(GlobalValue::ExternalLinkage);
119       continue;
120     }
121     if (I->hasInitializer())
122       GV->setInitializer(MapValue(I->getInitializer(), VMap));
123   }
124 
125   // Similarly, copy over function bodies now...
126   //
127   for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) {
128     if (I->isDeclaration())
129       continue;
130 
131     Function *F = cast<Function>(VMap[&*I]);
132     if (!ShouldCloneDefinition(&*I)) {
133       // Skip after setting the correct linkage for an external reference.
134       F->setLinkage(GlobalValue::ExternalLinkage);
135       // Personality function is not valid on a declaration.
136       F->setPersonalityFn(nullptr);
137       continue;
138     }
139 
140     Function::arg_iterator DestI = F->arg_begin();
141     for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end();
142          ++J) {
143       DestI->setName(J->getName());
144       VMap[&*J] = &*DestI++;
145     }
146 
147     SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned.
148     CloneFunctionInto(F, &*I, VMap, /*ModuleLevelChanges=*/true, Returns);
149 
150     if (I->hasPersonalityFn())
151       F->setPersonalityFn(MapValue(I->getPersonalityFn(), VMap));
152   }
153 
154   // And aliases
155   for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end();
156        I != E; ++I) {
157     // We already dealt with undefined aliases above.
158     if (!ShouldCloneDefinition(&*I))
159       continue;
160     GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]);
161     if (const Constant *C = I->getAliasee())
162       GA->setAliasee(MapValue(C, VMap));
163   }
164 
165   // And named metadata....
166   for (Module::const_named_metadata_iterator I = M->named_metadata_begin(),
167          E = M->named_metadata_end(); I != E; ++I) {
168     const NamedMDNode &NMD = *I;
169     NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName());
170     for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i)
171       NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap));
172   }
173 
174   return New;
175 }
176 
177 extern "C" {
178 
179 LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) {
180   return wrap(CloneModule(unwrap(M)).release());
181 }
182 
183 }
184