DICompileUnit *DIBuilder::createCompileUnit( unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, DebugEmissionKind Kind, uint64_t DWOId, bool EmitDebugInfo) { assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!Filename.empty() && "Unable to create compile unit without filename"); assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); CUNode = DICompileUnit::getDistinct( VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer, isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId); // Create a named metadata so that it is easier to find cu in a module. // Note that we only generate this when the caller wants to actually // emit debug information. When we are only interested in tracking // source line locations throughout the backend, we prevent codegen from // emitting debug info in the final output by not generating llvm.dbg.cu. if (EmitDebugInfo) { NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(CUNode); } trackIfUnresolved(CUNode); return CUNode; }
/// createVariable - Create a new descriptor for the specified variable. DIVariable DIBuilder::createLocalVariable(unsigned Tag, DIDescriptor Scope, StringRef Name, DIFile File, unsigned LineNo, DIType Ty, bool AlwaysPreserve, unsigned Flags, unsigned ArgNo) { Value *Elts[] = { GetTagConstant(VMContext, Tag), getNonCompileUnitScope(Scope), MDString::get(VMContext, Name), File, ConstantInt::get(Type::getInt32Ty(VMContext), (LineNo | (ArgNo << 24))), Ty, ConstantInt::get(Type::getInt32Ty(VMContext), Flags), Constant::getNullValue(Type::getInt32Ty(VMContext)) }; MDNode *Node = MDNode::get(VMContext, Elts); if (AlwaysPreserve) { // The optimizer may remove local variable. If there is an interest // to preserve variable info in such situation then stash it in a // named mdnode. DISubprogram Fn(getDISubprogram(Scope)); NamedMDNode *FnLocals = getOrInsertFnSpecificMDNode(M, Fn); FnLocals->addOperand(Node); } return DIVariable(Node); }
void LLVMAddNamedMetadataOperand2(LLVMModuleRef M, const char *name, LLVMMetadataRef Val) { NamedMDNode *N = unwrap(M)->getOrInsertNamedMetadata(name); if (!N) return; if (!Val) return; N->addOperand(unwrap<MDNode>(Val)); }
static void ModuleMetaSet(Module *module, StringRef MetaName, StringRef ValueStr) { NamedMDNode *node = module->getNamedMetadata(MetaName); if (node) module->eraseNamedMetadata(node); node = module->getOrInsertNamedMetadata(MetaName); MDString *value = MDString::get(module->getContext(), ValueStr); node->addOperand(MDNode::get(module->getContext(), makeArrayRef(static_cast<Value*>(value)))); }
/// Insert all of the named MDNodes in Src into the Dest module. void IRLinker::linkNamedMDNodes() { const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); for (const NamedMDNode &NMD : SrcM->named_metadata()) { // Don't link module flags here. Do them separately. if (&NMD == SrcModFlags) continue; NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName()); // Add Src elements into Dest node. for (const MDNode *Op : NMD.operands()) DestNMD->addOperand(Mapper.mapMDNode(*Op)); } }
/// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest /// module. void ModuleLinker::linkNamedMDNodes() { const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(), E = SrcM->named_metadata_end(); I != E; ++I) { // Don't link module flags here. Do them separately. if (&*I == SrcModFlags) continue; NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName()); // Add Src elements into Dest node. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap, RF_None, &TypeMap)); } }
DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, DebugEmissionKind Kind, bool EmitDebugInfo) { assert(((Lang <= dwarf::DW_LANG_OCaml && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!Filename.empty() && "Unable to create compile unit without filename"); Value *TElts[] = {HeaderBuilder::get(DW_TAG_base_type).get(VMContext)}; TempEnumTypes = MDNode::getTemporary(VMContext, TElts); TempRetainTypes = MDNode::getTemporary(VMContext, TElts); TempSubprograms = MDNode::getTemporary(VMContext, TElts); TempGVs = MDNode::getTemporary(VMContext, TElts); TempImportedModules = MDNode::getTemporary(VMContext, TElts); Value *Elts[] = {HeaderBuilder::get(dwarf::DW_TAG_compile_unit) .concat(Lang) .concat(Producer) .concat(isOptimized) .concat(Flags) .concat(RunTimeVer) .concat(SplitName) .concat(Kind) .get(VMContext), createFilePathPair(VMContext, Filename, Directory), TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs, TempImportedModules}; MDNode *CUNode = MDNode::get(VMContext, Elts); // Create a named metadata so that it is easier to find cu in a module. // Note that we only generate this when the caller wants to actually // emit debug information. When we are only interested in tracking // source line locations throughout the backend, we prevent codegen from // emitting debug info in the final output by not generating llvm.dbg.cu. if (EmitDebugInfo) { NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(CUNode); } return DICompileUnit(CUNode); }
/// Insert all of the named MDNodes in Src into the Dest module. void IRLinker::linkNamedMDNodes() { const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata(); for (const NamedMDNode &NMD : SrcM.named_metadata()) { // Don't link module flags here. Do them separately. if (&NMD == SrcModFlags) continue; NamedMDNode *DestNMD = DstM.getOrInsertNamedMetadata(NMD.getName()); // Add Src elements into Dest node. for (const MDNode *op : NMD.operands()) DestNMD->addOperand(MapMetadata( op, ValueMap, RF_MoveDistinctMDs | RF_NullMapMissingGlobalValues, &TypeMap, &GValMaterializer)); } }
/// createCompileUnit - A CompileUnit provides an anchor for all debugging /// information generated during this instance of compilation. void DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer) { assert(((Lang <= dwarf::DW_LANG_Python && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!Filename.empty() && "Unable to create compile unit without filename"); Value *TElts[] = { GetTagConstant(VMContext, DW_TAG_base_type) }; TempEnumTypes = MDNode::getTemporary(VMContext, TElts); Value *THElts[] = { TempEnumTypes }; MDNode *EnumHolder = MDNode::get(VMContext, THElts); TempRetainTypes = MDNode::getTemporary(VMContext, TElts); Value *TRElts[] = { TempRetainTypes }; MDNode *RetainHolder = MDNode::get(VMContext, TRElts); TempSubprograms = MDNode::getTemporary(VMContext, TElts); Value *TSElts[] = { TempSubprograms }; MDNode *SPHolder = MDNode::get(VMContext, TSElts); TempGVs = MDNode::getTemporary(VMContext, TElts); Value *TVElts[] = { TempGVs }; MDNode *GVHolder = MDNode::get(VMContext, TVElts); Value *Elts[] = { GetTagConstant(VMContext, dwarf::DW_TAG_compile_unit), Constant::getNullValue(Type::getInt32Ty(VMContext)), ConstantInt::get(Type::getInt32Ty(VMContext), Lang), MDString::get(VMContext, Filename), MDString::get(VMContext, Directory), MDString::get(VMContext, Producer), // Deprecate isMain field. ConstantInt::get(Type::getInt1Ty(VMContext), true), // isMain ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized), MDString::get(VMContext, Flags), ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer), EnumHolder, RetainHolder, SPHolder, GVHolder }; TheCU = DICompileUnit(MDNode::get(VMContext, Elts)); // Create a named metadata so that it is easier to find cu in a module. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(TheCU); }
CopyConnectedComponent(Module * dest_, Module * src_, llvmutil_Property copyGlobal_, void * data_, ValueToValueMapTy & VMap_) : dest(dest_), src(src_), copyGlobal(copyGlobal_), data(data_), VMap(VMap_), DI(NULL) { if(NamedMDNode * NMD = src->getNamedMetadata("llvm.module.flags")) { NamedMDNode * New = dest->getOrInsertNamedMetadata(NMD->getName()); for (unsigned i = 0; i < NMD->getNumOperands(); i++) { New->addOperand(MapValue(NMD->getOperand(i), VMap)); } } if(NamedMDNode * CUN = src->getNamedMetadata("llvm.dbg.cu")) { DI = new DIBuilder(*dest); DICompileUnit CU(CUN->getOperand(0)); NCU = DI->createCompileUnit(CU.getLanguage(), CU.getFilename(), CU.getDirectory(), CU.getProducer(), CU.isOptimized(), CU.getFlags(), CU.getRunTimeVersion()); } }
void Module::convertLibraryListToMetadata() const { if (LibraryList.size() == 0) return; // Get the DepLib node NamedMDNode *Node = getNamedMetadata("DepLibs"); assert(Node && "DepLibs metadata node missing"); // Erase all existing operands Node->dropAllReferences(); // Add all libraries from the library list for (Module::lib_iterator I = lib_begin(), E = lib_end(); I != E; ++I) { MDString *value = MDString::get(getContext(), *I); Node->addOperand(MDNode::get(getContext(), makeArrayRef(static_cast<Value*>(value)))); } }
bool ReduceCrashingNamedMDOps::TestNamedMDOps( std::vector<const MDNode *> &NamedMDOps) { // Convert list to set for fast lookup... SmallPtrSet<const MDNode *, 32> OldMDNodeOps; for (unsigned i = 0, e = NamedMDOps.size(); i != e; ++i) { OldMDNodeOps.insert(NamedMDOps[i]); } outs() << "Checking for crash with only " << OldMDNodeOps.size(); if (OldMDNodeOps.size() == 1) outs() << " named metadata operand: "; else outs() << " named metadata operands: "; ValueToValueMapTy VMap; Module *M = CloneModule(BD.getProgram(), VMap).release(); // This is a little wasteful. In the future it might be good if we could have // these dropped during cloning. for (auto &NamedMD : BD.getProgram()->named_metadata()) { // Drop the old one and create a new one M->eraseNamedMetadata(M->getNamedMetadata(NamedMD.getName())); NamedMDNode *NewNamedMDNode = M->getOrInsertNamedMetadata(NamedMD.getName()); for (MDNode *op : NamedMD.operands()) if (OldMDNodeOps.count(op)) NewNamedMDNode->addOperand(cast<MDNode>(MapMetadata(op, VMap))); } // Verify that this is still valid. legacy::PassManager Passes; Passes.add(createVerifierPass(/*FatalErrors=*/false)); Passes.run(*M); // Try running on the hacked up program... if (TestFn(BD, M)) { // Make sure to use instruction pointers that point into the now-current // module, and that they don't include any deleted blocks. NamedMDOps.clear(); for (const MDNode *Node : OldMDNodeOps) NamedMDOps.push_back(cast<MDNode>(*VMap.getMappedMD(Node))); BD.setNewProgram(M); // It crashed, keep the trimmed version... return true; } delete M; // It didn't crash, try something else. return false; }
bool SpecializationTable::addSpecialization(Function* parent, ConstSpecScheme scheme, Function* specialization, bool record) { assert(parent != NULL); assert(specialization != NULL); SpecTable::iterator cursor = this->specialized.find(specialization); //Specialization* spec = this->specialized.lookup(specialization->getName()); if (cursor != this->specialized.end()) { return false; } Specialization* parentSpec = this->getSpecialization(parent); Specialization* spec = new Specialization(); spec->handle = specialization; spec->parent = parentSpec; spec->args = scheme; this->specialized[specialization] = spec; //.GetOrCreateValue(specialization->getName(), spec); parentSpec->children.push_back(spec); #if RECORD_IN_METADATA // Add the meta-data if (record) { NamedMDNode* md = this->module->getOrInsertNamedMetadata( "previrt::specializations"); const unsigned int arg_count = parent->getArgumentList().size(); Value** vals = new Value*[2 + arg_count]; vals[0] = MDString::get(parent->getContext(), parent->getName()); vals[1] = MDString::get(parent->getContext(), specialization->getName()); for (unsigned int i = 0; i < parent->getArgumentList().size(); ++i) { vals[i+2] = scheme[i]; } ArrayRef<Value*> ar_vals(vals, vals+2+arg_count); MDNode* nde = MDNode::get(this->module->getContext(), ar_vals); md->addOperand(nde); } #endif /* RECORD_IN_METADATA */ return true; }
void Module::addNeededRecord(StringRef DynFile, GlobalValue *GV) { if (DynFile.empty()) { // We never resolved this symbol, even after linking. // This should only happen in a shared object. // It is safe to ignore this symbol, and let the dynamic loader // figure out where it comes from. return; } std::string Key = NeededPrefix; Key += DynFile; // Get the node for this file. NamedMDNode *Node = getOrInsertNamedMetadata(Key); // Add this global value's name to the list. MDString *value = MDString::get(getContext(), GV->getName()); Node->addOperand(MDNode::get(getContext(), makeArrayRef(static_cast<Value*>(value)))); }
/// createCompileUnit - A CompileUnit provides an anchor for all debugging /// information generated during this instance of compilation. DICompileUnit DIBuilder::createCompileUnit(unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName) { assert(((Lang <= dwarf::DW_LANG_Python && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!Filename.empty() && "Unable to create compile unit without filename"); Value *TElts[] = { GetTagConstant(VMContext, DW_TAG_base_type) }; TempEnumTypes = MDNode::getTemporary(VMContext, TElts); TempRetainTypes = MDNode::getTemporary(VMContext, TElts); TempSubprograms = MDNode::getTemporary(VMContext, TElts); TempGVs = MDNode::getTemporary(VMContext, TElts); TempImportedModules = MDNode::getTemporary(VMContext, TElts); Value *Elts[] = { GetTagConstant(VMContext, dwarf::DW_TAG_compile_unit), createFilePathPair(VMContext, Filename, Directory), ConstantInt::get(Type::getInt32Ty(VMContext), Lang), MDString::get(VMContext, Producer), ConstantInt::get(Type::getInt1Ty(VMContext), isOptimized), MDString::get(VMContext, Flags), ConstantInt::get(Type::getInt32Ty(VMContext), RunTimeVer), TempEnumTypes, TempRetainTypes, TempSubprograms, TempGVs, TempImportedModules, MDString::get(VMContext, SplitName) }; MDNode *CUNode = MDNode::get(VMContext, Elts); // Create a named metadata so that it is easier to find cu in a module. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(CUNode); return DICompileUnit(CUNode); }
DICompileUnit *DIBuilder::createCompileUnit( unsigned Lang, StringRef Filename, StringRef Directory, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, DebugEmissionKind Kind, bool EmitDebugInfo) { assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!Filename.empty() && "Unable to create compile unit without filename"); // TODO: Once we make DICompileUnit distinct, stop using temporaries here // (just start with operands assigned to nullptr). TempEnumTypes = MDTuple::getTemporary(VMContext, None); TempRetainTypes = MDTuple::getTemporary(VMContext, None); TempSubprograms = MDTuple::getTemporary(VMContext, None); TempGVs = MDTuple::getTemporary(VMContext, None); TempImportedModules = MDTuple::getTemporary(VMContext, None); // TODO: Switch to getDistinct(). We never want to merge compile units based // on contents. DICompileUnit *CUNode = DICompileUnit::get( VMContext, Lang, DIFile::get(VMContext, Filename, Directory), Producer, isOptimized, Flags, RunTimeVer, SplitName, Kind, TempEnumTypes.get(), TempRetainTypes.get(), TempSubprograms.get(), TempGVs.get(), TempImportedModules.get()); // Create a named metadata so that it is easier to find cu in a module. // Note that we only generate this when the caller wants to actually // emit debug information. When we are only interested in tracking // source line locations throughout the backend, we prevent codegen from // emitting debug info in the final output by not generating llvm.dbg.cu. if (EmitDebugInfo) { NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(CUNode); } trackIfUnresolved(CUNode); return CUNode; }
DICompileUnit *DIBuilder::createCompileUnit( unsigned Lang, DIFile *File, StringRef Producer, bool isOptimized, StringRef Flags, unsigned RunTimeVer, StringRef SplitName, DICompileUnit::DebugEmissionKind Kind, uint64_t DWOId, bool SplitDebugInlining, bool DebugInfoForProfiling, bool GnuPubnames) { assert(((Lang <= dwarf::DW_LANG_Fortran08 && Lang >= dwarf::DW_LANG_C89) || (Lang <= dwarf::DW_LANG_hi_user && Lang >= dwarf::DW_LANG_lo_user)) && "Invalid Language tag"); assert(!CUNode && "Can only make one compile unit per DIBuilder instance"); CUNode = DICompileUnit::getDistinct( VMContext, Lang, File, Producer, isOptimized, Flags, RunTimeVer, SplitName, Kind, nullptr, nullptr, nullptr, nullptr, nullptr, DWOId, SplitDebugInlining, DebugInfoForProfiling, GnuPubnames); // Create a named metadata so that it is easier to find cu in a module. NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->addOperand(CUNode); trackIfUnresolved(CUNode); return CUNode; }
/// Remove any debug info for global variables/functions in the given module for /// which said global variable/function no longer exists (i.e. is null). /// /// Debugging information is encoded in llvm IR using metadata. This is designed /// such a way that debug info for symbols preserved even if symbols are /// optimized away by the optimizer. This special pass removes debug info for /// such symbols. bool StripDeadDebugInfo::runOnModule(Module &M) { if (skipModule(M)) return false; bool Changed = false; LLVMContext &C = M.getContext(); // Find all debug info in F. This is actually overkill in terms of what we // want to do, but we want to try and be as resilient as possible in the face // of potential debug info changes by using the formal interfaces given to us // as much as possible. DebugInfoFinder F; F.processModule(M); // For each compile unit, find the live set of global variables/functions and // replace the current list of potentially dead global variables/functions // with the live list. SmallVector<Metadata *, 64> LiveGlobalVariables; DenseSet<DIGlobalVariableExpression *> VisitedSet; std::set<DIGlobalVariableExpression *> LiveGVs; for (GlobalVariable &GV : M.globals()) { SmallVector<DIGlobalVariableExpression *, 1> GVEs; GV.getDebugInfo(GVEs); for (auto *GVE : GVEs) LiveGVs.insert(GVE); } std::set<DICompileUnit *> LiveCUs; // Any CU referenced from a subprogram is live. for (DISubprogram *SP : F.subprograms()) { if (SP->getUnit()) LiveCUs.insert(SP->getUnit()); } bool HasDeadCUs = false; for (DICompileUnit *DIC : F.compile_units()) { // Create our live global variable list. bool GlobalVariableChange = false; for (auto *DIG : DIC->getGlobalVariables()) { if (DIG->getExpression() && DIG->getExpression()->isConstant()) LiveGVs.insert(DIG); // Make sure we only visit each global variable only once. if (!VisitedSet.insert(DIG).second) continue; // If a global variable references DIG, the global variable is live. if (LiveGVs.count(DIG)) LiveGlobalVariables.push_back(DIG); else GlobalVariableChange = true; } if (!LiveGlobalVariables.empty()) LiveCUs.insert(DIC); else if (!LiveCUs.count(DIC)) HasDeadCUs = true; // If we found dead global variables, replace the current global // variable list with our new live global variable list. if (GlobalVariableChange) { DIC->replaceGlobalVariables(MDTuple::get(C, LiveGlobalVariables)); Changed = true; } // Reset lists for the next iteration. LiveGlobalVariables.clear(); } if (HasDeadCUs) { // Delete the old node and replace it with a new one NamedMDNode *NMD = M.getOrInsertNamedMetadata("llvm.dbg.cu"); NMD->clearOperands(); if (!LiveCUs.empty()) { for (DICompileUnit *CU : LiveCUs) NMD->addOperand(CU); } Changed = true; } return Changed; }
std::unique_ptr<Module> llvm::CloneSubModule(const Module &M, HandleGlobalVariableFtor HandleGlobalVariable, HandleFunctionFtor HandleFunction, bool KeepInlineAsm) { ValueToValueMapTy VMap; // First off, we need to create the new module. std::unique_ptr<Module> New = llvm::make_unique<Module>(M.getModuleIdentifier(), M.getContext()); New->setDataLayout(M.getDataLayout()); New->setTargetTriple(M.getTargetTriple()); if (KeepInlineAsm) New->setModuleInlineAsm(M.getModuleInlineAsm()); // Copy global variables (but not initializers, yet). for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { GlobalVariable *GV = new GlobalVariable( *New, I->getType()->getElementType(), I->isConstant(), I->getLinkage(), (Constant *)nullptr, I->getName(), (GlobalVariable *)nullptr, I->getThreadLocalMode(), I->getType()->getAddressSpace()); GV->copyAttributesFrom(I); VMap[I] = GV; } // Loop over the functions in the module, making external functions as before for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { Function *NF = Function::Create(cast<FunctionType>(I->getType()->getElementType()), I->getLinkage(), I->getName(), &*New); NF->copyAttributesFrom(I); VMap[I] = NF; } // Loop over the aliases in the module for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E; ++I) { auto *PTy = cast<PointerType>(I->getType()); auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), I->getLinkage(), I->getName(), &*New); GA->copyAttributesFrom(I); VMap[I] = GA; } // Now that all of the things that global variable initializer can refer to // have been created, loop through and copy the global variable referrers // over... We also set the attributes on the global now. for (Module::const_global_iterator I = M.global_begin(), E = M.global_end(); I != E; ++I) { GlobalVariable &GV = *cast<GlobalVariable>(VMap[I]); HandleGlobalVariable(GV, *I, VMap); } // Similarly, copy over function bodies now... // for (Module::const_iterator I = M.begin(), E = M.end(); I != E; ++I) { Function &F = *cast<Function>(VMap[I]); HandleFunction(F, *I, VMap); } // And aliases for (Module::const_alias_iterator I = M.alias_begin(), E = M.alias_end(); I != E; ++I) { GlobalAlias *GA = cast<GlobalAlias>(VMap[I]); if (const Constant *C = I->getAliasee()) GA->setAliasee(MapValue(C, VMap)); } // And named metadata.... for (Module::const_named_metadata_iterator I = M.named_metadata_begin(), E = M.named_metadata_end(); I != E; ++I) { const NamedMDNode &NMD = *I; NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName()); for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap)); } return New; }
Module *llvm::CloneModule(const Module *M, ValueToValueMapTy &VMap) { // First off, we need to create the new module. Module *New = new Module(M->getModuleIdentifier(), M->getContext()); New->setDataLayout(M->getDataLayout()); New->setTargetTriple(M->getTargetTriple()); New->setModuleInlineAsm(M->getModuleInlineAsm()); // Loop over all of the global variables, making corresponding globals in the // new module. Here we add them to the VMap and to the new Module. We // don't worry about attributes or initializers, they will come later. // for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) { GlobalVariable *GV = new GlobalVariable(*New, I->getType()->getElementType(), I->isConstant(), I->getLinkage(), (Constant*) nullptr, I->getName(), (GlobalVariable*) nullptr, I->getThreadLocalMode(), I->getType()->getAddressSpace()); GV->copyAttributesFrom(I); VMap[I] = GV; } // Loop over the functions in the module, making external functions as before for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) { Function *NF = Function::Create(cast<FunctionType>(I->getType()->getElementType()), I->getLinkage(), I->getName(), New); NF->copyAttributesFrom(I); VMap[I] = NF; } // Loop over the aliases in the module for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); I != E; ++I) { auto *PTy = cast<PointerType>(I->getType()); auto *GA = GlobalAlias::create(PTy->getElementType(), PTy->getAddressSpace(), I->getLinkage(), I->getName(), New); GA->copyAttributesFrom(I); VMap[I] = GA; } // Now that all of the things that global variable initializer can refer to // have been created, loop through and copy the global variable referrers // over... We also set the attributes on the global now. // for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) { GlobalVariable *GV = cast<GlobalVariable>(VMap[I]); if (I->hasInitializer()) GV->setInitializer(MapValue(I->getInitializer(), VMap)); } // Similarly, copy over function bodies now... // for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) { Function *F = cast<Function>(VMap[I]); if (!I->isDeclaration()) { Function::arg_iterator DestI = F->arg_begin(); for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end(); ++J) { DestI->setName(J->getName()); VMap[J] = DestI++; } SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. CloneFunctionInto(F, I, VMap, /*ModuleLevelChanges=*/true, Returns); } } // And aliases for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); I != E; ++I) { GlobalAlias *GA = cast<GlobalAlias>(VMap[I]); if (const Constant *C = I->getAliasee()) GA->setAliasee(cast<GlobalObject>(MapValue(C, VMap))); } // And named metadata.... for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), E = M->named_metadata_end(); I != E; ++I) { const NamedMDNode &NMD = *I; NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName()); for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) NewNMD->addOperand(MapValue(NMD.getOperand(i), VMap)); } return New; }
std::unique_ptr<Module> llvm::CloneModule( const Module *M, ValueToValueMapTy &VMap, std::function<bool(const GlobalValue *)> ShouldCloneDefinition) { // First off, we need to create the new module. std::unique_ptr<Module> New = llvm::make_unique<Module>(M->getModuleIdentifier(), M->getContext()); New->setDataLayout(M->getDataLayout()); New->setTargetTriple(M->getTargetTriple()); New->setModuleInlineAsm(M->getModuleInlineAsm()); // Loop over all of the global variables, making corresponding globals in the // new module. Here we add them to the VMap and to the new Module. We // don't worry about attributes or initializers, they will come later. // for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) { GlobalVariable *GV = new GlobalVariable(*New, I->getValueType(), I->isConstant(), I->getLinkage(), (Constant*) nullptr, I->getName(), (GlobalVariable*) nullptr, I->getThreadLocalMode(), I->getType()->getAddressSpace()); GV->copyAttributesFrom(&*I); VMap[&*I] = GV; } // Loop over the functions in the module, making external functions as before for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) { Function *NF = Function::Create(cast<FunctionType>(I->getValueType()), I->getLinkage(), I->getName(), New.get()); NF->copyAttributesFrom(&*I); VMap[&*I] = NF; } // Loop over the aliases in the module for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); I != E; ++I) { if (!ShouldCloneDefinition(&*I)) { // An alias cannot act as an external reference, so we need to create // either a function or a global variable depending on the value type. // FIXME: Once pointee types are gone we can probably pick one or the // other. GlobalValue *GV; if (I->getValueType()->isFunctionTy()) GV = Function::Create(cast<FunctionType>(I->getValueType()), GlobalValue::ExternalLinkage, I->getName(), New.get()); else GV = new GlobalVariable( *New, I->getValueType(), false, GlobalValue::ExternalLinkage, (Constant *)nullptr, I->getName(), (GlobalVariable *)nullptr, I->getThreadLocalMode(), I->getType()->getAddressSpace()); VMap[&*I] = GV; // We do not copy attributes (mainly because copying between different // kinds of globals is forbidden), but this is generally not required for // correctness. continue; } auto *GA = GlobalAlias::create(I->getValueType(), I->getType()->getPointerAddressSpace(), I->getLinkage(), I->getName(), New.get()); GA->copyAttributesFrom(&*I); VMap[&*I] = GA; } // Now that all of the things that global variable initializer can refer to // have been created, loop through and copy the global variable referrers // over... We also set the attributes on the global now. // for (Module::const_global_iterator I = M->global_begin(), E = M->global_end(); I != E; ++I) { GlobalVariable *GV = cast<GlobalVariable>(VMap[&*I]); if (!ShouldCloneDefinition(&*I)) { // Skip after setting the correct linkage for an external reference. GV->setLinkage(GlobalValue::ExternalLinkage); continue; } if (I->hasInitializer()) GV->setInitializer(MapValue(I->getInitializer(), VMap)); } // Similarly, copy over function bodies now... // for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I) { Function *F = cast<Function>(VMap[&*I]); if (!ShouldCloneDefinition(&*I)) { // Skip after setting the correct linkage for an external reference. F->setLinkage(GlobalValue::ExternalLinkage); // Personality function is not valid on a declaration. F->setPersonalityFn(nullptr); continue; } if (!I->isDeclaration()) { Function::arg_iterator DestI = F->arg_begin(); for (Function::const_arg_iterator J = I->arg_begin(); J != I->arg_end(); ++J) { DestI->setName(J->getName()); VMap[&*J] = &*DestI++; } SmallVector<ReturnInst*, 8> Returns; // Ignore returns cloned. CloneFunctionInto(F, &*I, VMap, /*ModuleLevelChanges=*/true, Returns); } if (I->hasPersonalityFn()) F->setPersonalityFn(MapValue(I->getPersonalityFn(), VMap)); } // And aliases for (Module::const_alias_iterator I = M->alias_begin(), E = M->alias_end(); I != E; ++I) { // We already dealt with undefined aliases above. if (!ShouldCloneDefinition(&*I)) continue; GlobalAlias *GA = cast<GlobalAlias>(VMap[&*I]); if (const Constant *C = I->getAliasee()) GA->setAliasee(MapValue(C, VMap)); } // And named metadata.... for (Module::const_named_metadata_iterator I = M->named_metadata_begin(), E = M->named_metadata_end(); I != E; ++I) { const NamedMDNode &NMD = *I; NamedMDNode *NewNMD = New->getOrInsertNamedMetadata(NMD.getName()); for (unsigned i = 0, e = NMD.getNumOperands(); i != e; ++i) NewNMD->addOperand(MapMetadata(NMD.getOperand(i), VMap)); } return New; }
/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest /// module. bool ModuleLinker::linkModuleFlagsMetadata() { const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); if (!SrcModFlags) return false; NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata(); // If the destination module doesn't have module flags yet, then just copy // over the source module's flags. if (DstModFlags->getNumOperands() == 0) { for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) DstModFlags->addOperand(SrcModFlags->getOperand(I)); return false; } bool HasErr = false; // Otherwise, we have to merge them based on their behaviors. First, // categorize all of the nodes in the modules' module flags. If an error or // warning occurs, then emit the appropriate message(s). DenseMap<MDString*, MDNode*> ErrorNode; DenseMap<MDString*, MDNode*> WarningNode; DenseMap<MDString*, MDNode*> OverrideNode; DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes; SmallSetVector<MDString*, 16> SeenIDs; HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode, OverrideNode, RequireNodes, SeenIDs); HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode, OverrideNode, RequireNodes, SeenIDs); // Check that there isn't both an error and warning node for a flag. for (SmallSetVector<MDString*, 16>::iterator I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) { MDString *ID = *I; if (ErrorNode[ID] && WarningNode[ID]) HasErr = emitError("linking module flags '" + ID->getString() + "': IDs have conflicting behaviors"); } // Early exit if we had an error. if (HasErr) return true; // Get the destination's module flags ready for new operands. DstModFlags->dropAllReferences(); // Add all of the module flags to the destination module. DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes; for (SmallSetVector<MDString*, 16>::iterator I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) { MDString *ID = *I; if (OverrideNode[ID]) { DstModFlags->addOperand(OverrideNode[ID]); AddedNodes[ID].push_back(OverrideNode[ID]); } else if (ErrorNode[ID]) { DstModFlags->addOperand(ErrorNode[ID]); AddedNodes[ID].push_back(ErrorNode[ID]); } else if (WarningNode[ID]) { DstModFlags->addOperand(WarningNode[ID]); AddedNodes[ID].push_back(WarningNode[ID]); } for (SmallSetVector<MDNode*, 8>::iterator II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end(); II != IE; ++II) DstModFlags->addOperand(*II); } // Now check that all of the requirements have been satisfied. for (SmallSetVector<MDString*, 16>::iterator I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) { MDString *ID = *I; SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID]; for (SmallSetVector<MDNode*, 8>::iterator II = Set.begin(), IE = Set.end(); II != IE; ++II) { MDNode *Node = *II; assert(isa<MDNode>(Node->getOperand(2)) && "Module flag's third operand must be an MDNode!"); MDNode *Val = cast<MDNode>(Node->getOperand(2)); MDString *ReqID = cast<MDString>(Val->getOperand(0)); Value *ReqVal = Val->getOperand(1); bool HasValue = false; for (SmallVectorImpl<MDNode*>::iterator RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end(); RI != RE; ++RI) { MDNode *ReqNode = *RI; if (ReqNode->getOperand(2) == ReqVal) { HasValue = true; break; } } if (!HasValue) HasErr = emitError("linking module flags '" + ReqID->getString() + "': does not have the required value"); } } return HasErr; }
// destructively move the contents of src into dest // this assumes that the targets of the two modules are the same // including the DataLayout and ModuleFlags (for example) // and that there is no module-level assembly static void jl_merge_module(Module *dest, std::unique_ptr<Module> src) { assert(dest != src.get()); for (Module::global_iterator I = src->global_begin(), E = src->global_end(); I != E;) { GlobalVariable *sG = &*I; GlobalValue *dG = dest->getNamedValue(sG->getName()); ++I; // Replace a declaration with the definition: if (dG) { if (sG->isDeclaration()) { sG->replaceAllUsesWith(dG); sG->eraseFromParent(); continue; } else { dG->replaceAllUsesWith(sG); dG->eraseFromParent(); } } // Reparent the global variable: sG->removeFromParent(); dest->getGlobalList().push_back(sG); // Comdat is owned by the Module, recreate it in the new parent: addComdat(sG); } for (Module::iterator I = src->begin(), E = src->end(); I != E;) { Function *sG = &*I; GlobalValue *dG = dest->getNamedValue(sG->getName()); ++I; // Replace a declaration with the definition: if (dG) { if (sG->isDeclaration()) { sG->replaceAllUsesWith(dG); sG->eraseFromParent(); continue; } else { dG->replaceAllUsesWith(sG); dG->eraseFromParent(); } } // Reparent the global variable: sG->removeFromParent(); dest->getFunctionList().push_back(sG); // Comdat is owned by the Module, recreate it in the new parent: addComdat(sG); } for (Module::alias_iterator I = src->alias_begin(), E = src->alias_end(); I != E;) { GlobalAlias *sG = &*I; GlobalValue *dG = dest->getNamedValue(sG->getName()); ++I; if (dG) { if (!dG->isDeclaration()) { // aliases are always definitions, so this test is reversed from the above two sG->replaceAllUsesWith(dG); sG->eraseFromParent(); continue; } else { dG->replaceAllUsesWith(sG); dG->eraseFromParent(); } } sG->removeFromParent(); dest->getAliasList().push_back(sG); } // metadata nodes need to be explicitly merged not just copied // so there are special passes here for each known type of metadata NamedMDNode *sNMD = src->getNamedMetadata("llvm.dbg.cu"); if (sNMD) { NamedMDNode *dNMD = dest->getOrInsertNamedMetadata("llvm.dbg.cu"); #ifdef LLVM35 for (NamedMDNode::op_iterator I = sNMD->op_begin(), E = sNMD->op_end(); I != E; ++I) { dNMD->addOperand(*I); } #else for (unsigned i = 0, l = sNMD->getNumOperands(); i < l; i++) { dNMD->addOperand(sNMD->getOperand(i)); } #endif } }
/// Merge the linker flags in Src into the Dest module. Error IRLinker::linkModuleFlagsMetadata() { // If the source module has no module flags, we are done. const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata(); if (!SrcModFlags) return Error::success(); // If the destination module doesn't have module flags yet, then just copy // over the source module's flags. NamedMDNode *DstModFlags = DstM.getOrInsertModuleFlagsMetadata(); if (DstModFlags->getNumOperands() == 0) { for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) DstModFlags->addOperand(SrcModFlags->getOperand(I)); return Error::success(); } // First build a map of the existing module flags and requirements. DenseMap<MDString *, std::pair<MDNode *, unsigned>> Flags; SmallSetVector<MDNode *, 16> Requirements; for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) { MDNode *Op = DstModFlags->getOperand(I); ConstantInt *Behavior = mdconst::extract<ConstantInt>(Op->getOperand(0)); MDString *ID = cast<MDString>(Op->getOperand(1)); if (Behavior->getZExtValue() == Module::Require) { Requirements.insert(cast<MDNode>(Op->getOperand(2))); } else { Flags[ID] = std::make_pair(Op, I); } } // Merge in the flags from the source module, and also collect its set of // requirements. for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) { MDNode *SrcOp = SrcModFlags->getOperand(I); ConstantInt *SrcBehavior = mdconst::extract<ConstantInt>(SrcOp->getOperand(0)); MDString *ID = cast<MDString>(SrcOp->getOperand(1)); MDNode *DstOp; unsigned DstIndex; std::tie(DstOp, DstIndex) = Flags.lookup(ID); unsigned SrcBehaviorValue = SrcBehavior->getZExtValue(); // If this is a requirement, add it and continue. if (SrcBehaviorValue == Module::Require) { // If the destination module does not already have this requirement, add // it. if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) { DstModFlags->addOperand(SrcOp); } continue; } // If there is no existing flag with this ID, just add it. if (!DstOp) { Flags[ID] = std::make_pair(SrcOp, DstModFlags->getNumOperands()); DstModFlags->addOperand(SrcOp); continue; } // Otherwise, perform a merge. ConstantInt *DstBehavior = mdconst::extract<ConstantInt>(DstOp->getOperand(0)); unsigned DstBehaviorValue = DstBehavior->getZExtValue(); // If either flag has override behavior, handle it first. if (DstBehaviorValue == Module::Override) { // Diagnose inconsistent flags which both have override behavior. if (SrcBehaviorValue == Module::Override && SrcOp->getOperand(2) != DstOp->getOperand(2)) return stringErr("linking module flags '" + ID->getString() + "': IDs have conflicting override values"); continue; } else if (SrcBehaviorValue == Module::Override) { // Update the destination flag to that of the source. DstModFlags->setOperand(DstIndex, SrcOp); Flags[ID].first = SrcOp; continue; } // Diagnose inconsistent merge behavior types. if (SrcBehaviorValue != DstBehaviorValue) return stringErr("linking module flags '" + ID->getString() + "': IDs have conflicting behaviors"); auto replaceDstValue = [&](MDNode *New) { Metadata *FlagOps[] = {DstOp->getOperand(0), ID, New}; MDNode *Flag = MDNode::get(DstM.getContext(), FlagOps); DstModFlags->setOperand(DstIndex, Flag); Flags[ID].first = Flag; }; // Perform the merge for standard behavior types. switch (SrcBehaviorValue) { case Module::Require: case Module::Override: llvm_unreachable("not possible"); case Module::Error: { // Emit an error if the values differ. if (SrcOp->getOperand(2) != DstOp->getOperand(2)) return stringErr("linking module flags '" + ID->getString() + "': IDs have conflicting values"); continue; } case Module::Warning: { // Emit a warning if the values differ. if (SrcOp->getOperand(2) != DstOp->getOperand(2)) { emitWarning("linking module flags '" + ID->getString() + "': IDs have conflicting values"); } continue; } case Module::Append: { MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); SmallVector<Metadata *, 8> MDs; MDs.reserve(DstValue->getNumOperands() + SrcValue->getNumOperands()); MDs.append(DstValue->op_begin(), DstValue->op_end()); MDs.append(SrcValue->op_begin(), SrcValue->op_end()); replaceDstValue(MDNode::get(DstM.getContext(), MDs)); break; } case Module::AppendUnique: { SmallSetVector<Metadata *, 16> Elts; MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2)); MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2)); Elts.insert(DstValue->op_begin(), DstValue->op_end()); Elts.insert(SrcValue->op_begin(), SrcValue->op_end()); replaceDstValue(MDNode::get(DstM.getContext(), makeArrayRef(Elts.begin(), Elts.end()))); break; } } } // Check all of the requirements. for (unsigned I = 0, E = Requirements.size(); I != E; ++I) { MDNode *Requirement = Requirements[I]; MDString *Flag = cast<MDString>(Requirement->getOperand(0)); Metadata *ReqValue = Requirement->getOperand(1); MDNode *Op = Flags[Flag].first; if (!Op || Op->getOperand(2) != ReqValue) return stringErr("linking module flags '" + Flag->getString() + "': does not have the required value"); } return Error::success(); }