-/// Loop over all of the linked values to compute type mappings. For example,
-/// if we link "extern Foo *x" and "Foo *x = NULL", then we have two struct
-/// types 'Foo' but one got renamed when the module was loaded into the same
-/// LLVMContext.
-void ModuleLinker::computeTypeMapping() {
- for (GlobalValue &SGV : SrcM.globals()) {
- GlobalValue *DGV = getLinkedToGlobal(&SGV);
- if (!DGV)
- continue;
-
- if (!DGV->hasAppendingLinkage() || !SGV.hasAppendingLinkage()) {
- TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
- continue;
- }
-
- // Unify the element type of appending arrays.
- ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
- ArrayType *SAT = cast<ArrayType>(SGV.getType()->getElementType());
- TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
- }
-
- for (GlobalValue &SGV : SrcM) {
- if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
- TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
- }
-
- for (GlobalValue &SGV : SrcM.aliases()) {
- if (GlobalValue *DGV = getLinkedToGlobal(&SGV))
- TypeMap.addTypeMapping(DGV->getType(), SGV.getType());
- }
-
- // Incorporate types by name, scanning all the types in the source module.
- // At this point, the destination module may have a type "%foo = { i32 }" for
- // example. When the source module got loaded into the same LLVMContext, if
- // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
- std::vector<StructType *> Types = SrcM.getIdentifiedStructTypes();
- for (StructType *ST : Types) {
- if (!ST->hasName())
- continue;
-
- // Check to see if there is a dot in the name followed by a digit.
- size_t DotPos = ST->getName().rfind('.');
- if (DotPos == 0 || DotPos == StringRef::npos ||
- ST->getName().back() == '.' ||
- !isdigit(static_cast<unsigned char>(ST->getName()[DotPos + 1])))
- continue;
-
- // Check to see if the destination module has a struct with the prefix name.
- StructType *DST = DstM.getTypeByName(ST->getName().substr(0, DotPos));
- if (!DST)
- continue;
-
- // Don't use it if this actually came from the source module. They're in
- // the same LLVMContext after all. Also don't use it unless the type is
- // actually used in the destination module. This can happen in situations
- // like this:
- //
- // Module A Module B
- // -------- --------
- // %Z = type { %A } %B = type { %C.1 }
- // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
- // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
- // %C = type { i8* } %B.3 = type { %C.1 }
- //
- // When we link Module B with Module A, the '%B' in Module B is
- // used. However, that would then use '%C.1'. But when we process '%C.1',
- // we prefer to take the '%C' version. So we are then left with both
- // '%C.1' and '%C' being used for the same types. This leads to some
- // variables using one type and some using the other.
- if (TypeMap.DstStructTypesSet.hasType(DST))
- TypeMap.addTypeMapping(DST, ST);
- }
-
- // Now that we have discovered all of the type equivalences, get a body for
- // any 'opaque' types in the dest module that are now resolved.
- TypeMap.linkDefinedTypeBodies();
-}
-
-static void getArrayElements(const Constant *C,
- SmallVectorImpl<Constant *> &Dest) {
- unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
-
- for (unsigned i = 0; i != NumElements; ++i)
- Dest.push_back(C->getAggregateElement(i));
-}
-
-/// If there were any appending global variables, link them together now.
-/// Return true on error.
-Constant *ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
- const GlobalVariable *SrcGV) {
- Type *EltTy = cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()))
- ->getElementType();
-
- StringRef Name = SrcGV->getName();
- bool IsNewStructor = false;
- bool IsOldStructor = false;
- if (Name == "llvm.global_ctors" || Name == "llvm.global_dtors") {
- if (cast<StructType>(EltTy)->getNumElements() == 3)
- IsNewStructor = true;
- else
- IsOldStructor = true;
- }
-
- PointerType *VoidPtrTy = Type::getInt8Ty(SrcGV->getContext())->getPointerTo();
- if (IsOldStructor) {
- auto &ST = *cast<StructType>(EltTy);
- Type *Tys[3] = {ST.getElementType(0), ST.getElementType(1), VoidPtrTy};
- EltTy = StructType::get(SrcGV->getContext(), Tys, false);
- }
-
- if (DstGV) {
- ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
-
- if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage()) {
- emitError(
- "Linking globals named '" + SrcGV->getName() +
- "': can only link appending global with another appending global!");
- return nullptr;
- }
-
- // Check to see that they two arrays agree on type.
- if (EltTy != DstTy->getElementType()) {
- emitError("Appending variables with different element types!");
- return nullptr;
- }
- if (DstGV->isConstant() != SrcGV->isConstant()) {
- emitError("Appending variables linked with different const'ness!");
- return nullptr;
- }
-
- if (DstGV->getAlignment() != SrcGV->getAlignment()) {
- emitError(
- "Appending variables with different alignment need to be linked!");
- return nullptr;
- }
-
- if (DstGV->getVisibility() != SrcGV->getVisibility()) {
- emitError(
- "Appending variables with different visibility need to be linked!");
- return nullptr;
- }
-
- if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr()) {
- emitError(
- "Appending variables with different unnamed_addr need to be linked!");
- return nullptr;
- }
-
- if (StringRef(DstGV->getSection()) != SrcGV->getSection()) {
- emitError(
- "Appending variables with different section name need to be linked!");
- return nullptr;
- }
- }
-
- SmallVector<Constant *, 16> DstElements;
- if (DstGV)
- getArrayElements(DstGV->getInitializer(), DstElements);
-
- SmallVector<Constant *, 16> SrcElements;
- getArrayElements(SrcGV->getInitializer(), SrcElements);
-
- if (IsNewStructor)
- SrcElements.erase(
- std::remove_if(SrcElements.begin(), SrcElements.end(),
- [this](Constant *E) {
- auto *Key = dyn_cast<GlobalValue>(
- E->getAggregateElement(2)->stripPointerCasts());
- return Key && !ValuesToLink.count(Key) &&
- !shouldLazyLink(*Key);
- }),
- SrcElements.end());
- uint64_t NewSize = DstElements.size() + SrcElements.size();
- ArrayType *NewType = ArrayType::get(EltTy, NewSize);
-
- // Create the new global variable.
- GlobalVariable *NG = new GlobalVariable(
- DstM, NewType, SrcGV->isConstant(), SrcGV->getLinkage(),
- /*init*/ nullptr, /*name*/ "", DstGV, SrcGV->getThreadLocalMode(),
- SrcGV->getType()->getAddressSpace());
-
- // Propagate alignment, visibility and section info.
- copyGVAttributes(NG, SrcGV);
-
- Constant *Ret = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
-
- // Stop recursion.
- ValueMap[SrcGV] = Ret;
-
- for (auto *V : SrcElements) {
- Constant *NewV;
- if (IsOldStructor) {
- auto *S = cast<ConstantStruct>(V);
- auto *E1 = MapValue(S->getOperand(0), ValueMap, RF_MoveDistinctMDs,
- &TypeMap, &ValMaterializer);
- auto *E2 = MapValue(S->getOperand(1), ValueMap, RF_MoveDistinctMDs,
- &TypeMap, &ValMaterializer);
- Value *Null = Constant::getNullValue(VoidPtrTy);
- NewV =
- ConstantStruct::get(cast<StructType>(EltTy), E1, E2, Null, nullptr);
- } else {
- NewV =
- MapValue(V, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
- }
- DstElements.push_back(NewV);
- }
-
- NG->setInitializer(ConstantArray::get(NewType, DstElements));
-
- // Replace any uses of the two global variables with uses of the new
- // global.
- if (DstGV) {
- DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
- DstGV->eraseFromParent();
- }
-
- return Ret;
-}
-
-Constant *ModuleLinker::linkGlobalValueProto(GlobalValue *SGV) {
- GlobalValue *DGV = getLinkedToGlobal(SGV);
-
- // Handle the ultra special appending linkage case first.
- assert(!DGV || SGV->hasAppendingLinkage() == DGV->hasAppendingLinkage());
- if (SGV->hasAppendingLinkage()) {
- // Should have prevented importing for appending linkage in linkIfNeeded.
- assert(!isPerformingImport());
- return linkAppendingVarProto(cast_or_null<GlobalVariable>(DGV),
- cast<GlobalVariable>(SGV));
- }
-
- bool LinkFromSrc = true;
- Comdat *C = nullptr;
- bool HasUnnamedAddr = SGV->hasUnnamedAddr();
-
- if (isPerformingImport() && !doImportAsDefinition(SGV)) {
- LinkFromSrc = false;
- } else if (const Comdat *SC = SGV->getComdat()) {
- Comdat::SelectionKind SK;
- std::tie(SK, LinkFromSrc) = ComdatsChosen[SC];
- C = DstM.getOrInsertComdat(SC->getName());
- C->setSelectionKind(SK);
- if (SGV->hasLocalLinkage())
- LinkFromSrc = true;
- } else if (DGV) {
- if (shouldLinkFromSource(LinkFromSrc, *DGV, *SGV))
- return nullptr;
- }
-
- if (DGV)
- HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
-
- GlobalValue *NewGV;
- if (!LinkFromSrc && DGV) {
- NewGV = DGV;
- // When linking from source we setVisibility from copyGlobalValueProto.
- setVisibility(NewGV, SGV, DGV);
- } else {
- // If we are done linking global value bodies (i.e. we are performing
- // metadata linking), don't link in the global value due to this
- // reference, simply map it to null.
- if (DoneLinkingBodies)
- return nullptr;
-
- NewGV = copyGlobalValueProto(SGV, DGV, LinkFromSrc);
- }
-
- NewGV->setUnnamedAddr(HasUnnamedAddr);
-
- if (auto *NewGO = dyn_cast<GlobalObject>(NewGV)) {
- if (C && LinkFromSrc)
- NewGO->setComdat(C);
-
- if (DGV && DGV->hasCommonLinkage() && SGV->hasCommonLinkage())
- NewGO->setAlignment(std::max(DGV->getAlignment(), SGV->getAlignment()));
- }
-
- if (auto *NewGVar = dyn_cast<GlobalVariable>(NewGV)) {
- auto *DGVar = dyn_cast_or_null<GlobalVariable>(DGV);
- auto *SGVar = dyn_cast<GlobalVariable>(SGV);
- if (DGVar && SGVar && DGVar->isDeclaration() && SGVar->isDeclaration() &&
- (!DGVar->isConstant() || !SGVar->isConstant()))
- NewGVar->setConstant(false);
- }
-
- if (NewGV != DGV && DGV) {
- DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewGV, DGV->getType()));
- DGV->eraseFromParent();
- }
-
- return ConstantExpr::getBitCast(NewGV, TypeMap.get(SGV->getType()));
-}
-
-/// Update the initializers in the Dest module now that all globals that may be
-/// referenced are in Dest.
-void ModuleLinker::linkGlobalInit(GlobalVariable &Dst, GlobalVariable &Src) {
- // Figure out what the initializer looks like in the dest module.
- Dst.setInitializer(MapValue(Src.getInitializer(), ValueMap,
- RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
-}
-
-/// Copy the source function over into the dest function and fix up references
-/// to values. At this point we know that Dest is an external function, and
-/// that Src is not.
-bool ModuleLinker::linkFunctionBody(Function &Dst, Function &Src) {
- assert(Dst.isDeclaration() && !Src.isDeclaration());
-
- // Materialize if needed.
- if (std::error_code EC = Src.materialize())
- return emitError(EC.message());
-
- // Link in the prefix data.
- if (Src.hasPrefixData())
- Dst.setPrefixData(MapValue(Src.getPrefixData(), ValueMap,
- RF_MoveDistinctMDs, &TypeMap, &ValMaterializer));
-
- // Link in the prologue data.
- if (Src.hasPrologueData())
- Dst.setPrologueData(MapValue(Src.getPrologueData(), ValueMap,
- RF_MoveDistinctMDs, &TypeMap,
- &ValMaterializer));
-
- // Link in the personality function.
- if (Src.hasPersonalityFn())
- Dst.setPersonalityFn(MapValue(Src.getPersonalityFn(), ValueMap,
- RF_MoveDistinctMDs, &TypeMap,
- &ValMaterializer));
-
- // Go through and convert function arguments over, remembering the mapping.
- Function::arg_iterator DI = Dst.arg_begin();
- for (Argument &Arg : Src.args()) {
- DI->setName(Arg.getName()); // Copy the name over.
-
- // Add a mapping to our mapping.
- ValueMap[&Arg] = &*DI;
- ++DI;
- }
-
- // Copy over the metadata attachments.
- SmallVector<std::pair<unsigned, MDNode *>, 8> MDs;
- Src.getAllMetadata(MDs);
- for (const auto &I : MDs)
- Dst.setMetadata(I.first, MapMetadata(I.second, ValueMap, RF_MoveDistinctMDs,
- &TypeMap, &ValMaterializer));
-
- // Splice the body of the source function into the dest function.
- Dst.getBasicBlockList().splice(Dst.end(), Src.getBasicBlockList());
-
- // At this point, all of the instructions and values of the function are now
- // copied over. The only problem is that they are still referencing values in
- // the Source function as operands. Loop through all of the operands of the
- // functions and patch them up to point to the local versions.
- for (BasicBlock &BB : Dst)
- for (Instruction &I : BB)
- RemapInstruction(&I, ValueMap,
- RF_IgnoreMissingEntries | RF_MoveDistinctMDs, &TypeMap,
- &ValMaterializer);
-
- // There is no need to map the arguments anymore.
- for (Argument &Arg : Src.args())
- ValueMap.erase(&Arg);
-
- Src.dematerialize();
- return false;
-}
-
-void ModuleLinker::linkAliasBody(GlobalAlias &Dst, GlobalAlias &Src) {
- Constant *Aliasee = Src.getAliasee();
- Constant *Val = MapValue(Aliasee, ValueMap, RF_MoveDistinctMDs, &TypeMap,
- &ValMaterializer);
- Dst.setAliasee(Val);
-}
-
-bool ModuleLinker::linkGlobalValueBody(GlobalValue &Dst, GlobalValue &Src) {
- if (const Comdat *SC = Src.getComdat()) {
- // To ensure that we don't generate an incomplete comdat group,
- // we must materialize and map in any other members that are not
- // yet materialized in Dst, which also ensures their definitions
- // are linked in. Otherwise, linkonce and other lazy linked GVs will
- // not be materialized if they aren't referenced.
- for (auto *SGV : ComdatMembers[SC]) {
- auto *DGV = cast_or_null<GlobalValue>(ValueMap.lookup(SGV));
- if (DGV && !DGV->isDeclaration())
- continue;
- MapValue(SGV, ValueMap, RF_MoveDistinctMDs, &TypeMap, &ValMaterializer);
- }
- }
- if (shouldInternalizeLinkedSymbols())
- if (auto *DGV = dyn_cast<GlobalValue>(&Dst))
- DGV->setLinkage(GlobalValue::InternalLinkage);
- if (auto *F = dyn_cast<Function>(&Src))
- return linkFunctionBody(cast<Function>(Dst), *F);
- if (auto *GVar = dyn_cast<GlobalVariable>(&Src)) {
- linkGlobalInit(cast<GlobalVariable>(Dst), *GVar);
- return false;
- }
- linkAliasBody(cast<GlobalAlias>(Dst), cast<GlobalAlias>(Src));
- return false;
-}
-
-/// Insert all of the named MDNodes in Src into the Dest module.
-void ModuleLinker::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, &ValMaterializer));
- }
-}
-
-/// Merge the linker flags in Src into the Dest module.
-bool ModuleLinker::linkModuleFlagsMetadata() {
- // If the source module has no module flags, we are done.
- const NamedMDNode *SrcModFlags = SrcM.getModuleFlagsMetadata();
- if (!SrcModFlags)
- return false;
-
- // 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 false;
- }
-
- // 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.
- bool HasErr = false;
- 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)) {
- HasErr |= emitError("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) {
- HasErr |= emitError("linking module flags '" + ID->getString() +
- "': IDs have conflicting behaviors");
- continue;
- }
-
- 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)) {
- HasErr |= emitError("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) {
- HasErr |= emitError("linking module flags '" + Flag->getString() +
- "': does not have the required value");
- continue;
- }
- }
-
- return HasErr;
-}
-
-// This function returns true if the triples match.
-static bool triplesMatch(const Triple &T0, const Triple &T1) {
- // If vendor is apple, ignore the version number.
- if (T0.getVendor() == Triple::Apple)
- return T0.getArch() == T1.getArch() && T0.getSubArch() == T1.getSubArch() &&
- T0.getVendor() == T1.getVendor() && T0.getOS() == T1.getOS();
-
- return T0 == T1;
-}
-
-// This function returns the merged triple.
-static std::string mergeTriples(const Triple &SrcTriple,
- const Triple &DstTriple) {
- // If vendor is apple, pick the triple with the larger version number.
- if (SrcTriple.getVendor() == Triple::Apple)
- if (DstTriple.isOSVersionLT(SrcTriple))
- return SrcTriple.str();
-
- return DstTriple.str();
-}
-