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