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/IR/Constant.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" 19 using namespace llvm; 20 21 static void copyComdat(GlobalObject *Dst, const GlobalObject *Src) { 22 const Comdat *SC = Src->getComdat(); 23 if (!SC) 24 return; 25 Comdat *DC = Dst->getParent()->getOrInsertComdat(SC->getName()); 26 DC->setSelectionKind(SC->getSelectionKind()); 27 Dst->setComdat(DC); 28 } 29 30 /// This is not as easy as it might seem because we have to worry about making 31 /// copies of global variables and functions, and making their (initializers and 32 /// references, respectively) refer to the right globals. 33 /// 34 std::unique_ptr<Module> llvm::CloneModule(const Module &M) { 35 // Create the value map that maps things from the old module over to the new 36 // module. 37 ValueToValueMapTy VMap; 38 return CloneModule(M, VMap); 39 } 40 41 std::unique_ptr<Module> llvm::CloneModule(const Module &M, 42 ValueToValueMapTy &VMap) { 43 return CloneModule(M, VMap, [](const GlobalValue *GV) { return true; }); 44 } 45 46 std::unique_ptr<Module> llvm::CloneModule( 47 const Module &M, ValueToValueMapTy &VMap, 48 function_ref<bool(const GlobalValue *)> ShouldCloneDefinition) { 49 // First off, we need to create the new module. 50 std::unique_ptr<Module> New = 51 std::make_unique<Module>(M.getModuleIdentifier(), M.getContext()); 52 New->setSourceFileName(M.getSourceFileName()); 53 New->setDataLayout(M.getDataLayout()); 54 New->setTargetTriple(M.getTargetTriple()); 55 New->setModuleInlineAsm(M.getModuleInlineAsm()); 56 57 // Loop over all of the global variables, making corresponding globals in the 58 // new module. Here we add them to the VMap and to the new Module. We 59 // don't worry about attributes or initializers, they will come later. 60 // 61 for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); 62 I != E; ++I) { 63 GlobalVariable *GV = new GlobalVariable(*New, 64 I->getValueType(), 65 I->isConstant(), I->getLinkage(), 66 (Constant*) nullptr, I->getName(), 67 (GlobalVariable*) nullptr, 68 I->getThreadLocalMode(), 69 I->getType()->getAddressSpace()); 70 GV->copyAttributesFrom(&*I); 71 VMap[&*I] = GV; 72 } 73 74 // Loop over the functions in the module, making external functions as before 75 for (const Function &I : M) { 76 Function *NF = 77 Function::Create(cast<FunctionType>(I.getValueType()), I.getLinkage(), 78 I.getAddressSpace(), I.getName(), New.get()); 79 NF->copyAttributesFrom(&I); 80 VMap[&I] = NF; 81 } 82 83 // Loop over the aliases in the module 84 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 85 I != E; ++I) { 86 if (!ShouldCloneDefinition(&*I)) { 87 // An alias cannot act as an external reference, so we need to create 88 // either a function or a global variable depending on the value type. 89 // FIXME: Once pointee types are gone we can probably pick one or the 90 // other. 91 GlobalValue *GV; 92 if (I->getValueType()->isFunctionTy()) 93 GV = Function::Create(cast<FunctionType>(I->getValueType()), 94 GlobalValue::ExternalLinkage, 95 I->getAddressSpace(), I->getName(), New.get()); 96 else 97 GV = new GlobalVariable( 98 *New, I->getValueType(), false, GlobalValue::ExternalLinkage, 99 nullptr, I->getName(), nullptr, 100 I->getThreadLocalMode(), I->getType()->getAddressSpace()); 101 VMap[&*I] = GV; 102 // We do not copy attributes (mainly because copying between different 103 // kinds of globals is forbidden), but this is generally not required for 104 // correctness. 105 continue; 106 } 107 auto *GA = GlobalAlias::create(I->getValueType(), 108 I->getType()->getPointerAddressSpace(), 109 I->getLinkage(), I->getName(), New.get()); 110 GA->copyAttributesFrom(&*I); 111 VMap[&*I] = GA; 112 } 113 114 // Now that all of the things that global variable initializer can refer to 115 // have been created, loop through and copy the global variable referrers 116 // over... We also set the attributes on the global now. 117 // 118 for (const GlobalVariable &G : M.globals()) { 119 GlobalVariable *GV = cast<GlobalVariable>(VMap[&G]); 120 121 SmallVector<std::pair<unsigned, MDNode *>, 1> MDs; 122 G.getAllMetadata(MDs); 123 124 // FIXME: Stop using RF_ReuseAndMutateDistinctMDs here, since it's unsound 125 // to mutate metadata that is still referenced by the source module unless 126 // the source is about to be discarded (see IRMover for a valid use). 127 for (auto MD : MDs) 128 GV->addMetadata(MD.first, *MapMetadata(MD.second, VMap, 129 RF_ReuseAndMutateDistinctMDs)); 130 131 if (G.isDeclaration()) 132 continue; 133 134 if (!ShouldCloneDefinition(&G)) { 135 // Skip after setting the correct linkage for an external reference. 136 GV->setLinkage(GlobalValue::ExternalLinkage); 137 continue; 138 } 139 if (G.hasInitializer()) 140 GV->setInitializer(MapValue(G.getInitializer(), VMap)); 141 142 copyComdat(GV, &G); 143 } 144 145 // Similarly, copy over function bodies now... 146 // 147 for (const Function &I : M) { 148 if (I.isDeclaration()) 149 continue; 150 151 Function *F = cast<Function>(VMap[&I]); 152 if (!ShouldCloneDefinition(&I)) { 153 // Skip after setting the correct linkage for an external reference. 154 F->setLinkage(GlobalValue::ExternalLinkage); 155 // Personality function is not valid on a declaration. 156 F->setPersonalityFn(nullptr); 157 continue; 158 } 159 160 Function::arg_iterator DestI = F->arg_begin(); 161 for (Function::const_arg_iterator J = I.arg_begin(); J != I.arg_end(); 162 ++J) { 163 DestI->setName(J->getName()); 164 VMap[&*J] = &*DestI++; 165 } 166 167 SmallVector<ReturnInst *, 8> Returns; // Ignore returns cloned. 168 CloneFunctionInto(F, &I, VMap, /*ModuleLevelChanges=*/true, Returns); 169 170 if (I.hasPersonalityFn()) 171 F->setPersonalityFn(MapValue(I.getPersonalityFn(), VMap)); 172 173 copyComdat(F, &I); 174 } 175 176 // And aliases 177 for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); 178 I != E; ++I) { 179 // We already dealt with undefined aliases above. 180 if (!ShouldCloneDefinition(&*I)) 181 continue; 182 GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]); 183 if (const Constant *C = I->getAliasee()) 184 GA->setAliasee(MapValue(C, VMap)); 185 } 186 187 // And named metadata.... 188 const auto* LLVM_DBG_CU = M.getNamedMetadata("llvm.dbg.cu"); 189 for (Module::const_named_metadata_iterator I = M.named_metadata_begin(), 190 E = M.named_metadata_end(); 191 I != E; ++I) { 192 const NamedMDNode &NMD = *I; 193 NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName()); 194 if (&NMD == LLVM_DBG_CU) { 195 // Do not insert duplicate operands. 196 SmallPtrSet<const void*, 8> Visited; 197 for (const auto* Operand : NewNMD->operands()) 198 Visited.insert(Operand); 199 for (const auto* Operand : NMD.operands()) { 200 auto* MappedOperand = MapMetadata(Operand, VMap); 201 if (Visited.insert(MappedOperand).second) 202 NewNMD->addOperand(MappedOperand); 203 } 204 } else 205 for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) 206 NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap)); 207 } 208 209 return New; 210 } 211 212 extern "C" { 213 214 LLVMModuleRef LLVMCloneModule(LLVMModuleRef M) { 215 return wrap(CloneModule(*unwrap(M)).release()); 216 } 217 218 } 219