159a5afa9SMikhail Glushenkov //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2361e513dSReid Spencer //
3361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4361e513dSReid Spencer //
5f3ebc3f3SChris Lattner // This file is distributed under the University of Illinois Open Source
6f3ebc3f3SChris Lattner // License. See LICENSE.TXT for details.
7361e513dSReid Spencer //
8361e513dSReid Spencer //===----------------------------------------------------------------------===//
9361e513dSReid Spencer //
10361e513dSReid Spencer // This file implements the LLVM module linker.
11361e513dSReid Spencer //
12361e513dSReid Spencer // Specifically, this:
13361e513dSReid Spencer //  * Merges global variables between the two modules
14361e513dSReid Spencer //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15361e513dSReid Spencer //  * Merges functions between two modules
16361e513dSReid Spencer //
17361e513dSReid Spencer //===----------------------------------------------------------------------===//
18361e513dSReid Spencer 
199b0ddbbeSReid Spencer #include "llvm/Linker.h"
20361e513dSReid Spencer #include "llvm/Constants.h"
21361e513dSReid Spencer #include "llvm/DerivedTypes.h"
22fac7b595SOwen Anderson #include "llvm/LLVMContext.h"
23361e513dSReid Spencer #include "llvm/Module.h"
2432af9e8cSReid Spencer #include "llvm/TypeSymbolTable.h"
253aaaa0b2SReid Spencer #include "llvm/ValueSymbolTable.h"
265ed50b61SBill Wendling #include "llvm/Instructions.h"
275ed50b61SBill Wendling #include "llvm/Assembly/Writer.h"
283d552423SDavid Greene #include "llvm/Support/Debug.h"
2956d06597STorok Edwin #include "llvm/Support/ErrorHandling.h"
30c521f541SChris Lattner #include "llvm/Support/raw_ostream.h"
31447762daSMichael J. Spencer #include "llvm/Support/Path.h"
32a2095034SDan Gohman #include "llvm/Transforms/Utils/ValueMapper.h"
335ed50b61SBill Wendling #include "llvm/ADT/DenseMap.h"
34361e513dSReid Spencer using namespace llvm;
35361e513dSReid Spencer 
36361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true.
37361e513dSReid Spencer // This just makes error return conditions a little bit simpler...
384975db62SDaniel Dunbar static inline bool Error(std::string *E, const Twine &Message) {
394975db62SDaniel Dunbar   if (E) *E = Message.str();
40361e513dSReid Spencer   return true;
41361e513dSReid Spencer }
42361e513dSReid Spencer 
43361e513dSReid Spencer // Function: ResolveTypes()
44361e513dSReid Spencer //
45361e513dSReid Spencer // Description:
46361e513dSReid Spencer //  Attempt to link the two specified types together.
47361e513dSReid Spencer //
48361e513dSReid Spencer // Inputs:
49361e513dSReid Spencer //  DestTy - The type to which we wish to resolve.
50361e513dSReid Spencer //  SrcTy  - The original type which we want to resolve.
51361e513dSReid Spencer //
52361e513dSReid Spencer // Outputs:
53361e513dSReid Spencer //  DestST - The symbol table in which the new type should be placed.
54361e513dSReid Spencer //
55361e513dSReid Spencer // Return value:
56361e513dSReid Spencer //  true  - There is an error and the types cannot yet be linked.
57361e513dSReid Spencer //  false - No errors.
58361e513dSReid Spencer //
598aa89e41SChris Lattner static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
60361e513dSReid Spencer   if (DestTy == SrcTy) return false;       // If already equal, noop
618aa89e41SChris Lattner   assert(DestTy && SrcTy && "Can't handle null types");
62361e513dSReid Spencer 
638aa89e41SChris Lattner   if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
648aa89e41SChris Lattner     // Type _is_ in module, just opaque...
658aa89e41SChris Lattner     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
668aa89e41SChris Lattner   } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
67361e513dSReid Spencer     const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
68361e513dSReid Spencer   } else {
698aa89e41SChris Lattner     return true;  // Cannot link types... not-equal and neither is opaque.
70361e513dSReid Spencer   }
71361e513dSReid Spencer   return false;
72361e513dSReid Spencer }
73361e513dSReid Spencer 
74eee6f995SChris Lattner /// LinkerTypeMap - This implements a map of types that is stable
75eee6f995SChris Lattner /// even if types are resolved/refined to other types.  This is not a general
76eee6f995SChris Lattner /// purpose map, it is specific to the linker's use.
77eee6f995SChris Lattner namespace {
78eee6f995SChris Lattner class LinkerTypeMap : public AbstractTypeUser {
79eee6f995SChris Lattner   typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
80eee6f995SChris Lattner   TheMapTy TheMap;
81eee6f995SChris Lattner 
82d0fcc9a8SArgyrios Kyrtzidis   LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
83d0fcc9a8SArgyrios Kyrtzidis   void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
8456cdea6bSChris Lattner public:
8556cdea6bSChris Lattner   LinkerTypeMap() {}
8656cdea6bSChris Lattner   ~LinkerTypeMap() {
87eee6f995SChris Lattner     for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
88eee6f995SChris Lattner          E = TheMap.end(); I != E; ++I)
89eee6f995SChris Lattner       I->first->removeAbstractTypeUser(this);
90eee6f995SChris Lattner   }
91eee6f995SChris Lattner 
92eee6f995SChris Lattner   /// lookup - Return the value for the specified type or null if it doesn't
93eee6f995SChris Lattner   /// exist.
94eee6f995SChris Lattner   const Type *lookup(const Type *Ty) const {
95eee6f995SChris Lattner     TheMapTy::const_iterator I = TheMap.find(Ty);
96eee6f995SChris Lattner     if (I != TheMap.end()) return I->second;
97eee6f995SChris Lattner     return 0;
98eee6f995SChris Lattner   }
99eee6f995SChris Lattner 
100eee6f995SChris Lattner   /// insert - This returns true if the pointer was new to the set, false if it
101eee6f995SChris Lattner   /// was already in the set.
102eee6f995SChris Lattner   bool insert(const Type *Src, const Type *Dst) {
10338740a98SDan Gohman     if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))).second)
104eee6f995SChris Lattner       return false;  // Already in map.
105eee6f995SChris Lattner     if (Src->isAbstract())
106eee6f995SChris Lattner       Src->addAbstractTypeUser(this);
107eee6f995SChris Lattner     return true;
108eee6f995SChris Lattner   }
109eee6f995SChris Lattner 
110eee6f995SChris Lattner protected:
111eee6f995SChris Lattner   /// refineAbstractType - The callback method invoked when an abstract type is
112eee6f995SChris Lattner   /// resolved to another type.  An object must override this method to update
113eee6f995SChris Lattner   /// its internal state to reference NewType instead of OldType.
114eee6f995SChris Lattner   ///
115eee6f995SChris Lattner   virtual void refineAbstractType(const DerivedType *OldTy,
116eee6f995SChris Lattner                                   const Type *NewTy) {
117eee6f995SChris Lattner     TheMapTy::iterator I = TheMap.find(OldTy);
118eee6f995SChris Lattner     const Type *DstTy = I->second;
119eee6f995SChris Lattner 
120eee6f995SChris Lattner     TheMap.erase(I);
121eee6f995SChris Lattner     if (OldTy->isAbstract())
122eee6f995SChris Lattner       OldTy->removeAbstractTypeUser(this);
123eee6f995SChris Lattner 
124eee6f995SChris Lattner     // Don't reinsert into the map if the key is concrete now.
125eee6f995SChris Lattner     if (NewTy->isAbstract())
126eee6f995SChris Lattner       insert(NewTy, DstTy);
127eee6f995SChris Lattner   }
128eee6f995SChris Lattner 
129eee6f995SChris Lattner   /// The other case which AbstractTypeUsers must be aware of is when a type
130eee6f995SChris Lattner   /// makes the transition from being abstract (where it has clients on it's
131eee6f995SChris Lattner   /// AbstractTypeUsers list) to concrete (where it does not).  This method
132eee6f995SChris Lattner   /// notifies ATU's when this occurs for a type.
133eee6f995SChris Lattner   virtual void typeBecameConcrete(const DerivedType *AbsTy) {
134eee6f995SChris Lattner     TheMap.erase(AbsTy);
135eee6f995SChris Lattner     AbsTy->removeAbstractTypeUser(this);
136eee6f995SChris Lattner   }
137eee6f995SChris Lattner 
138eee6f995SChris Lattner   // for debugging...
139eee6f995SChris Lattner   virtual void dump() const {
1403d552423SDavid Greene     dbgs() << "AbstractTypeSet!\n";
141eee6f995SChris Lattner   }
142eee6f995SChris Lattner };
143eee6f995SChris Lattner }
144eee6f995SChris Lattner 
145eee6f995SChris Lattner 
146361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it
147361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types
148361e513dSReid Spencer // are compatible.
1499be15893SChris Lattner static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
150eee6f995SChris Lattner                                    LinkerTypeMap &Pointers) {
1519be15893SChris Lattner   if (DstTy == SrcTy) return false;       // If already equal, noop
152361e513dSReid Spencer 
153361e513dSReid Spencer   // If we found our opaque type, resolve it now!
154cbd43f89SDuncan Sands   if (DstTy->isOpaqueTy() || SrcTy->isOpaqueTy())
1559be15893SChris Lattner     return ResolveTypes(DstTy, SrcTy);
156361e513dSReid Spencer 
157361e513dSReid Spencer   // Two types cannot be resolved together if they are of different primitive
158361e513dSReid Spencer   // type.  For example, we cannot resolve an int to a float.
1599be15893SChris Lattner   if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
160361e513dSReid Spencer 
161fe677e95SChris Lattner   // If neither type is abstract, then they really are just different types.
1629be15893SChris Lattner   if (!DstTy->isAbstract() && !SrcTy->isAbstract())
163fe677e95SChris Lattner     return true;
164fe677e95SChris Lattner 
165361e513dSReid Spencer   // Otherwise, resolve the used type used by this derived type...
1669be15893SChris Lattner   switch (DstTy->getTypeID()) {
1679995302bSChris Lattner   default:
1687a9c62baSReid Spencer     return true;
169361e513dSReid Spencer   case Type::FunctionTyID: {
1709be15893SChris Lattner     const FunctionType *DstFT = cast<FunctionType>(DstTy);
1719be15893SChris Lattner     const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
17285b66d18SChris Lattner     if (DstFT->isVarArg() != SrcFT->isVarArg() ||
17385b66d18SChris Lattner         DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
174361e513dSReid Spencer       return true;
1759be15893SChris Lattner 
1769be15893SChris Lattner     // Use TypeHolder's so recursive resolution won't break us.
1779be15893SChris Lattner     PATypeHolder ST(SrcFT), DT(DstFT);
1789be15893SChris Lattner     for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
1799be15893SChris Lattner       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
1809be15893SChris Lattner       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
181361e513dSReid Spencer         return true;
1829be15893SChris Lattner     }
183361e513dSReid Spencer     return false;
184361e513dSReid Spencer   }
185361e513dSReid Spencer   case Type::StructTyID: {
1869be15893SChris Lattner     const StructType *DstST = cast<StructType>(DstTy);
1879be15893SChris Lattner     const StructType *SrcST = cast<StructType>(SrcTy);
18885b66d18SChris Lattner     if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
1899995302bSChris Lattner       return true;
1909be15893SChris Lattner 
1919be15893SChris Lattner     PATypeHolder ST(SrcST), DT(DstST);
1929be15893SChris Lattner     for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
1939be15893SChris Lattner       const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
1949be15893SChris Lattner       if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
195361e513dSReid Spencer         return true;
1969be15893SChris Lattner     }
197361e513dSReid Spencer     return false;
198361e513dSReid Spencer   }
199361e513dSReid Spencer   case Type::ArrayTyID: {
2009be15893SChris Lattner     const ArrayType *DAT = cast<ArrayType>(DstTy);
2019be15893SChris Lattner     const ArrayType *SAT = cast<ArrayType>(SrcTy);
202361e513dSReid Spencer     if (DAT->getNumElements() != SAT->getNumElements()) return true;
203361e513dSReid Spencer     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
2048aa89e41SChris Lattner                                   Pointers);
205361e513dSReid Spencer   }
2069995302bSChris Lattner   case Type::VectorTyID: {
2079be15893SChris Lattner     const VectorType *DVT = cast<VectorType>(DstTy);
2089be15893SChris Lattner     const VectorType *SVT = cast<VectorType>(SrcTy);
2099995302bSChris Lattner     if (DVT->getNumElements() != SVT->getNumElements()) return true;
2109995302bSChris Lattner     return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
2119995302bSChris Lattner                                   Pointers);
2129995302bSChris Lattner   }
213361e513dSReid Spencer   case Type::PointerTyID: {
2149be15893SChris Lattner     const PointerType *DstPT = cast<PointerType>(DstTy);
2159be15893SChris Lattner     const PointerType *SrcPT = cast<PointerType>(SrcTy);
21685b66d18SChris Lattner 
21785b66d18SChris Lattner     if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
21885b66d18SChris Lattner       return true;
21985b66d18SChris Lattner 
220361e513dSReid Spencer     // If this is a pointer type, check to see if we have already seen it.  If
221361e513dSReid Spencer     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
222361e513dSReid Spencer     // an associative container for this search, because the type pointers (keys
223eee6f995SChris Lattner     // in the container) change whenever types get resolved.
224eee6f995SChris Lattner     if (SrcPT->isAbstract())
225eee6f995SChris Lattner       if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
226eee6f995SChris Lattner         return ExistingDestTy != DstPT;
227eee6f995SChris Lattner 
228eee6f995SChris Lattner     if (DstPT->isAbstract())
229eee6f995SChris Lattner       if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
230eee6f995SChris Lattner         return ExistingSrcTy != SrcPT;
231361e513dSReid Spencer     // Otherwise, add the current pointers to the vector to stop recursion on
232361e513dSReid Spencer     // this pair.
233eee6f995SChris Lattner     if (DstPT->isAbstract())
234eee6f995SChris Lattner       Pointers.insert(DstPT, SrcPT);
235eee6f995SChris Lattner     if (SrcPT->isAbstract())
236eee6f995SChris Lattner       Pointers.insert(SrcPT, DstPT);
2379be15893SChris Lattner 
23885b66d18SChris Lattner     return RecursiveResolveTypesI(DstPT->getElementType(),
23985b66d18SChris Lattner                                   SrcPT->getElementType(), Pointers);
240361e513dSReid Spencer   }
241361e513dSReid Spencer   }
242361e513dSReid Spencer }
243361e513dSReid Spencer 
2449be15893SChris Lattner static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
245eee6f995SChris Lattner   LinkerTypeMap PointerTypes;
2468aa89e41SChris Lattner   return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
247361e513dSReid Spencer }
248361e513dSReid Spencer 
249361e513dSReid Spencer 
250361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any
251361e513dSReid Spencer // types are named in the src module that are not named in the Dst module.
252361e513dSReid Spencer // Make sure there are no type name conflicts.
253361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
25432af9e8cSReid Spencer         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
25532af9e8cSReid Spencer   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
256361e513dSReid Spencer 
257361e513dSReid Spencer   // Look for a type plane for Type's...
25832af9e8cSReid Spencer   TypeSymbolTable::const_iterator TI = SrcST->begin();
25932af9e8cSReid Spencer   TypeSymbolTable::const_iterator TE = SrcST->end();
260361e513dSReid Spencer   if (TI == TE) return false;  // No named types, do nothing.
261361e513dSReid Spencer 
262361e513dSReid Spencer   // Some types cannot be resolved immediately because they depend on other
263361e513dSReid Spencer   // types being resolved to each other first.  This contains a list of types we
264361e513dSReid Spencer   // are waiting to recheck.
265361e513dSReid Spencer   std::vector<std::string> DelayedTypesToResolve;
266361e513dSReid Spencer 
267361e513dSReid Spencer   for ( ; TI != TE; ++TI ) {
268361e513dSReid Spencer     const std::string &Name = TI->first;
269361e513dSReid Spencer     const Type *RHS = TI->second;
270361e513dSReid Spencer 
2718aa89e41SChris Lattner     // Check to see if this type name is already in the dest module.
27232af9e8cSReid Spencer     Type *Entry = DestST->lookup(Name);
273361e513dSReid Spencer 
2748aa89e41SChris Lattner     // If the name is just in the source module, bring it over to the dest.
2758aa89e41SChris Lattner     if (Entry == 0) {
2768aa89e41SChris Lattner       if (!Name.empty())
277e9bb8552SChris Lattner         DestST->insert(Name, const_cast<Type*>(RHS));
2788aa89e41SChris Lattner     } else if (ResolveTypes(Entry, RHS)) {
279361e513dSReid Spencer       // They look different, save the types 'till later to resolve.
280361e513dSReid Spencer       DelayedTypesToResolve.push_back(Name);
281361e513dSReid Spencer     }
282361e513dSReid Spencer   }
283361e513dSReid Spencer 
284361e513dSReid Spencer   // Iteratively resolve types while we can...
285361e513dSReid Spencer   while (!DelayedTypesToResolve.empty()) {
286361e513dSReid Spencer     // Loop over all of the types, attempting to resolve them if possible...
287361e513dSReid Spencer     unsigned OldSize = DelayedTypesToResolve.size();
288361e513dSReid Spencer 
289361e513dSReid Spencer     // Try direct resolution by name...
290361e513dSReid Spencer     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
291361e513dSReid Spencer       const std::string &Name = DelayedTypesToResolve[i];
29232af9e8cSReid Spencer       Type *T1 = SrcST->lookup(Name);
29332af9e8cSReid Spencer       Type *T2 = DestST->lookup(Name);
2948aa89e41SChris Lattner       if (!ResolveTypes(T2, T1)) {
295361e513dSReid Spencer         // We are making progress!
296361e513dSReid Spencer         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
297361e513dSReid Spencer         --i;
298361e513dSReid Spencer       }
299361e513dSReid Spencer     }
300361e513dSReid Spencer 
301361e513dSReid Spencer     // Did we not eliminate any types?
302361e513dSReid Spencer     if (DelayedTypesToResolve.size() == OldSize) {
303361e513dSReid Spencer       // Attempt to resolve subelements of types.  This allows us to merge these
304361e513dSReid Spencer       // two types: { int* } and { opaque* }
305361e513dSReid Spencer       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
306361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve[i];
3079be15893SChris Lattner         if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
308361e513dSReid Spencer           // We are making progress!
309361e513dSReid Spencer           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
310361e513dSReid Spencer 
311361e513dSReid Spencer           // Go back to the main loop, perhaps we can resolve directly by name
312361e513dSReid Spencer           // now...
313361e513dSReid Spencer           break;
314361e513dSReid Spencer         }
315361e513dSReid Spencer       }
316361e513dSReid Spencer 
317361e513dSReid Spencer       // If we STILL cannot resolve the types, then there is something wrong.
318361e513dSReid Spencer       if (DelayedTypesToResolve.size() == OldSize) {
319361e513dSReid Spencer         // Remove the symbol name from the destination.
320361e513dSReid Spencer         DelayedTypesToResolve.pop_back();
321361e513dSReid Spencer       }
322361e513dSReid Spencer     }
323361e513dSReid Spencer   }
324361e513dSReid Spencer 
325361e513dSReid Spencer 
326361e513dSReid Spencer   return false;
327361e513dSReid Spencer }
328361e513dSReid Spencer 
32990246aa7SReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
33090246aa7SReid Spencer /// in the symbol table.  This is good for all clients except for us.  Go
33190246aa7SReid Spencer /// through the trouble to force this back.
332361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
333361e513dSReid Spencer   assert(GV->getName() != Name && "Can't force rename to self");
3343aaaa0b2SReid Spencer   ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
335361e513dSReid Spencer 
336361e513dSReid Spencer   // If there is a conflict, rename the conflict.
3372a8d2e0eSChris Lattner   if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
3386de96a1bSRafael Espindola     assert(ConflictGV->hasLocalLinkage() &&
33990246aa7SReid Spencer            "Not conflicting with a static global, should link instead!");
3402a8d2e0eSChris Lattner     GV->takeName(ConflictGV);
341361e513dSReid Spencer     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
3423aaaa0b2SReid Spencer     assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
3432a8d2e0eSChris Lattner   } else {
3442a8d2e0eSChris Lattner     GV->setName(Name);              // Force the name back
3453aaaa0b2SReid Spencer   }
3463aaaa0b2SReid Spencer }
3473aaaa0b2SReid Spencer 
3483aaaa0b2SReid Spencer /// CopyGVAttributes - copy additional attributes (those not needed to construct
3493aaaa0b2SReid Spencer /// a GlobalValue) from the SrcGV to the DestGV.
3503aaaa0b2SReid Spencer static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
351dd7daee8SDuncan Sands   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
352dd7daee8SDuncan Sands   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
353dd7daee8SDuncan Sands   DestGV->copyAttributesFrom(SrcGV);
354dd7daee8SDuncan Sands   DestGV->setAlignment(Alignment);
355361e513dSReid Spencer }
356361e513dSReid Spencer 
357fc61de39SChris Lattner /// GetLinkageResult - This analyzes the two global values and determines what
358fc61de39SChris Lattner /// the result will look like in the destination module.  In particular, it
359fc61de39SChris Lattner /// computes the resultant linkage type, computes whether the global in the
360fc61de39SChris Lattner /// source should be copied over to the destination (replacing the existing
36131fc4f95SAnton Korobeynikov /// one), and computes whether this linkage is an error or not. It also performs
36231fc4f95SAnton Korobeynikov /// visibility checks: we cannot link together two symbols with different
36331fc4f95SAnton Korobeynikov /// visibilities.
364f6439246SAnton Korobeynikov static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
365fc61de39SChris Lattner                              GlobalValue::LinkageTypes &LT, bool &LinkFromSrc,
366fc61de39SChris Lattner                              std::string *Err) {
3676de96a1bSRafael Espindola   assert((!Dest || !Src->hasLocalLinkage()) &&
368fc61de39SChris Lattner          "If Src has internal linkage, Dest shouldn't be set!");
369fc61de39SChris Lattner   if (!Dest) {
370fc61de39SChris Lattner     // Linking something to nothing.
371fc61de39SChris Lattner     LinkFromSrc = true;
372fc61de39SChris Lattner     LT = Src->getLinkage();
3735301e7c6SReid Spencer   } else if (Src->isDeclaration()) {
3741f93c50aSAnton Korobeynikov     // If Src is external or if both Src & Dest are external..  Just link the
375fc61de39SChris Lattner     // external globals, we aren't adding anything.
376d61d39ecSAnton Korobeynikov     if (Src->hasDLLImportLinkage()) {
37712c94949SAnton Korobeynikov       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
3785301e7c6SReid Spencer       if (Dest->isDeclaration()) {
379d61d39ecSAnton Korobeynikov         LinkFromSrc = true;
380d61d39ecSAnton Korobeynikov         LT = Src->getLinkage();
381d61d39ecSAnton Korobeynikov       }
382e06036d2SAndrew Lenharth     } else if (Dest->hasExternalWeakLinkage()) {
38312da8ce3SDuncan Sands       // If the Dest is weak, use the source linkage.
384e06036d2SAndrew Lenharth       LinkFromSrc = true;
385e06036d2SAndrew Lenharth       LT = Src->getLinkage();
386d61d39ecSAnton Korobeynikov     } else {
387fc61de39SChris Lattner       LinkFromSrc = false;
388fc61de39SChris Lattner       LT = Dest->getLinkage();
389d61d39ecSAnton Korobeynikov     }
3905301e7c6SReid Spencer   } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
391fc61de39SChris Lattner     // If Dest is external but Src is not:
392fc61de39SChris Lattner     LinkFromSrc = true;
393fc61de39SChris Lattner     LT = Src->getLinkage();
394fc61de39SChris Lattner   } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
395fc61de39SChris Lattner     if (Src->getLinkage() != Dest->getLinkage())
396fc61de39SChris Lattner       return Error(Err, "Linking globals named '" + Src->getName() +
397fc61de39SChris Lattner             "': can only link appending global with another appending global!");
398fc61de39SChris Lattner     LinkFromSrc = true; // Special cased.
399fc61de39SChris Lattner     LT = Src->getLinkage();
400d725c991SDuncan Sands   } else if (Src->isWeakForLinker()) {
401ce4396bcSDale Johannesen     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
402ce4396bcSDale Johannesen     // or DLL* linkage.
403184f1be4SChris Lattner     if (Dest->hasExternalWeakLinkage() ||
404184f1be4SChris Lattner         Dest->hasAvailableExternallyLinkage() ||
405184f1be4SChris Lattner         (Dest->hasLinkOnceLinkage() &&
406184f1be4SChris Lattner          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
407fc61de39SChris Lattner       LinkFromSrc = true;
408fc61de39SChris Lattner       LT = Src->getLinkage();
409fc61de39SChris Lattner     } else {
410fc61de39SChris Lattner       LinkFromSrc = false;
411fc61de39SChris Lattner       LT = Dest->getLinkage();
412fc61de39SChris Lattner     }
413d725c991SDuncan Sands   } else if (Dest->isWeakForLinker()) {
41412c94949SAnton Korobeynikov     // At this point we know that Src has External* or DLL* linkage.
41512c94949SAnton Korobeynikov     if (Src->hasExternalWeakLinkage()) {
41612c94949SAnton Korobeynikov       LinkFromSrc = false;
41712c94949SAnton Korobeynikov       LT = Dest->getLinkage();
41812c94949SAnton Korobeynikov     } else {
419fc61de39SChris Lattner       LinkFromSrc = true;
420fc61de39SChris Lattner       LT = GlobalValue::ExternalLinkage;
42112c94949SAnton Korobeynikov     }
422fc61de39SChris Lattner   } else {
423d61d39ecSAnton Korobeynikov     assert((Dest->hasExternalLinkage() ||
424d61d39ecSAnton Korobeynikov             Dest->hasDLLImportLinkage() ||
42512c94949SAnton Korobeynikov             Dest->hasDLLExportLinkage() ||
42612c94949SAnton Korobeynikov             Dest->hasExternalWeakLinkage()) &&
427d61d39ecSAnton Korobeynikov            (Src->hasExternalLinkage() ||
428d61d39ecSAnton Korobeynikov             Src->hasDLLImportLinkage() ||
42912c94949SAnton Korobeynikov             Src->hasDLLExportLinkage() ||
43012c94949SAnton Korobeynikov             Src->hasExternalWeakLinkage()) &&
431fc61de39SChris Lattner            "Unexpected linkage type!");
432fc61de39SChris Lattner     return Error(Err, "Linking globals named '" + Src->getName() +
433fc61de39SChris Lattner                  "': symbol multiply defined!");
434fc61de39SChris Lattner   }
43531fc4f95SAnton Korobeynikov 
43631fc4f95SAnton Korobeynikov   // Check visibility
437*4a9b18d0SRafael Espindola   if (Dest && Src->getVisibility() != Dest->getVisibility() &&
438*4a9b18d0SRafael Espindola       !Src->isDeclaration() && !Dest->isDeclaration() &&
439*4a9b18d0SRafael Espindola       !Src->hasAvailableExternallyLinkage() &&
440*4a9b18d0SRafael Espindola       !Dest->hasAvailableExternallyLinkage())
44131fc4f95SAnton Korobeynikov       return Error(Err, "Linking globals named '" + Src->getName() +
44231fc4f95SAnton Korobeynikov                    "': symbols have different visibilities!");
443fc61de39SChris Lattner   return false;
444fc61de39SChris Lattner }
445361e513dSReid Spencer 
4465c310be0SDevang Patel // Insert all of the named mdnoes in Src into the Dest module.
44735351901SDan Gohman static void LinkNamedMDNodes(Module *Dest, Module *Src,
44835351901SDan Gohman                              ValueToValueMapTy &ValueMap) {
4495c310be0SDevang Patel   for (Module::const_named_metadata_iterator I = Src->named_metadata_begin(),
4505c310be0SDevang Patel          E = Src->named_metadata_end(); I != E; ++I) {
4515c310be0SDevang Patel     const NamedMDNode *SrcNMD = I;
4522637cc1aSDan Gohman     NamedMDNode *DestNMD = Dest->getOrInsertNamedMetadata(SrcNMD->getName());
4535c310be0SDevang Patel     // Add Src elements into Dest node.
4549b493028SChris Lattner     for (unsigned i = 0, e = SrcNMD->getNumOperands(); i != e; ++i)
45535351901SDan Gohman       DestNMD->addOperand(cast<MDNode>(MapValue(SrcNMD->getOperand(i),
45643f8d164SChris Lattner                                                 ValueMap)));
4575c310be0SDevang Patel   }
4585c310be0SDevang Patel }
4595c310be0SDevang Patel 
460361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge
461361e513dSReid Spencer // them into the dest module.
462f6439246SAnton Korobeynikov static bool LinkGlobals(Module *Dest, const Module *Src,
463a2095034SDan Gohman                         ValueToValueMapTy &ValueMap,
464361e513dSReid Spencer                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
465361e513dSReid Spencer                         std::string *Err) {
46634fc5a0eSChris Lattner   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
46734fc5a0eSChris Lattner 
468361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
469177a3008SChris Lattner   for (Module::const_global_iterator I = Src->global_begin(),
470177a3008SChris Lattner        E = Src->global_end(); I != E; ++I) {
471f6439246SAnton Korobeynikov     const GlobalVariable *SGV = I;
472e79f4c77SAnton Korobeynikov     GlobalValue *DGV = 0;
473e79f4c77SAnton Korobeynikov 
4745ed50b61SBill Wendling     // Check to see if may have to link the global with the global, alias or
47534fc5a0eSChris Lattner     // function.
4766de96a1bSRafael Espindola     if (SGV->hasName() && !SGV->hasLocalLinkage())
4775ed50b61SBill Wendling       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SGV->getName()));
478361e513dSReid Spencer 
479c08e7a00SChris Lattner     // If we found a global with the same name in the dest module, but it has
480c08e7a00SChris Lattner     // internal linkage, we are really not doing any linkage here.
4816de96a1bSRafael Espindola     if (DGV && DGV->hasLocalLinkage())
482c08e7a00SChris Lattner       DGV = 0;
483c08e7a00SChris Lattner 
484e79f4c77SAnton Korobeynikov     // If types don't agree due to opaque types, try to resolve them.
48534fc5a0eSChris Lattner     if (DGV && DGV->getType() != SGV->getType())
4868aa89e41SChris Lattner       RecursiveResolveTypes(SGV->getType(), DGV->getType());
487e79f4c77SAnton Korobeynikov 
4885e79a610SDan Gohman     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
4895e79a610SDan Gohman             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
490361e513dSReid Spencer            "Global must either be external or have an initializer!");
491361e513dSReid Spencer 
4921b9633d7SChris Lattner     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
4931b9633d7SChris Lattner     bool LinkFromSrc = false;
494fc61de39SChris Lattner     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
495fc61de39SChris Lattner       return true;
496361e513dSReid Spencer 
4970ead7a50SChris Lattner     if (DGV == 0) {
498361e513dSReid Spencer       // No linking to be performed, simply create an identical version of the
499361e513dSReid Spencer       // symbol over in the dest module... the initializer will be filled in
50034fc5a0eSChris Lattner       // later by LinkGlobalInits.
501361e513dSReid Spencer       GlobalVariable *NewDGV =
502b17f3294SOwen Anderson         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
503361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
504b17f3294SOwen Anderson                            SGV->getName(), 0, false,
505b32a9ef0SChris Lattner                            SGV->getType()->getAddressSpace());
5062dc36535SReid Spencer       // Propagate alignment, visibility and section info.
5073aaaa0b2SReid Spencer       CopyGVAttributes(NewDGV, SGV);
508dd924e4eSAndrew Lenharth 
509361e513dSReid Spencer       // If the LLVM runtime renamed the global, but it is an externally visible
510361e513dSReid Spencer       // symbol, DGV must be an existing global with internal linkage.  Rename
511361e513dSReid Spencer       // it.
5126de96a1bSRafael Espindola       if (!NewDGV->hasLocalLinkage() && NewDGV->getName() != SGV->getName())
513361e513dSReid Spencer         ForceRenaming(NewDGV, SGV->getName());
514361e513dSReid Spencer 
5150ead7a50SChris Lattner       // Make sure to remember this mapping.
51666a6271cSAnton Korobeynikov       ValueMap[SGV] = NewDGV;
51766a6271cSAnton Korobeynikov 
51834fc5a0eSChris Lattner       // Keep track that this is an appending variable.
519361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
520361e513dSReid Spencer         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
5210ead7a50SChris Lattner       continue;
5220ead7a50SChris Lattner     }
5230ead7a50SChris Lattner 
524489e505aSRafael Espindola     bool HasUnnamedAddr = SGV->hasUnnamedAddr() && DGV->hasUnnamedAddr();
525489e505aSRafael Espindola 
5260ead7a50SChris Lattner     // If the visibilities of the symbols disagree and the destination is a
5270ead7a50SChris Lattner     // prototype, take the visibility of its input.
5280ead7a50SChris Lattner     if (DGV->isDeclaration())
5290ead7a50SChris Lattner       DGV->setVisibility(SGV->getVisibility());
5300ead7a50SChris Lattner 
5310ead7a50SChris Lattner     if (DGV->hasAppendingLinkage()) {
532361e513dSReid Spencer       // No linking is performed yet.  Just insert a new copy of the global, and
533361e513dSReid Spencer       // keep track of the fact that it is an appending variable in the
534361e513dSReid Spencer       // AppendingVars map.  The name is cleared out so that no linkage is
535361e513dSReid Spencer       // performed.
536361e513dSReid Spencer       GlobalVariable *NewDGV =
537b17f3294SOwen Anderson         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
538361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
539b17f3294SOwen Anderson                            "", 0, false,
540b32a9ef0SChris Lattner                            SGV->getType()->getAddressSpace());
541361e513dSReid Spencer 
542e8a3e74bSAnton Korobeynikov       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
5433aaaa0b2SReid Spencer       NewDGV->setAlignment(DGV->getAlignment());
544e8a3e74bSAnton Korobeynikov       // Propagate alignment, section and visibility info.
5453aaaa0b2SReid Spencer       CopyGVAttributes(NewDGV, SGV);
546dd924e4eSAndrew Lenharth 
547361e513dSReid Spencer       // Make sure to remember this mapping...
54866a6271cSAnton Korobeynikov       ValueMap[SGV] = NewDGV;
549361e513dSReid Spencer 
550361e513dSReid Spencer       // Keep track that this is an appending variable...
551361e513dSReid Spencer       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
5520ead7a50SChris Lattner       continue;
5530ead7a50SChris Lattner     }
5540ead7a50SChris Lattner 
5550ead7a50SChris Lattner     if (LinkFromSrc) {
5560ead7a50SChris Lattner       if (isa<GlobalAlias>(DGV))
557eeb5ca6fSAnton Korobeynikov         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
558eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
559dd924e4eSAndrew Lenharth 
5600074ea3aSAnton Korobeynikov       // If the types don't match, and if we are to link from the source, nuke
56134fc5a0eSChris Lattner       // DGV and create a new one of the appropriate type.  Note that the thing
56234fc5a0eSChris Lattner       // we are replacing may be a function (if a prototype, weak, etc) or a
56334fc5a0eSChris Lattner       // global variable.
564fc61de39SChris Lattner       GlobalVariable *NewDGV =
565b17f3294SOwen Anderson         new GlobalVariable(*Dest, SGV->getType()->getElementType(),
5665948fdf6SOwen Anderson                            SGV->isConstant(), NewLinkage, /*init*/0,
567b17f3294SOwen Anderson                            DGV->getName(), 0, false,
568b32a9ef0SChris Lattner                            SGV->getType()->getAddressSpace());
56934fc5a0eSChris Lattner 
570489e505aSRafael Espindola       // Set the unnamed_addr.
571489e505aSRafael Espindola       NewDGV->setUnnamedAddr(HasUnnamedAddr);
572489e505aSRafael Espindola 
57334fc5a0eSChris Lattner       // Propagate alignment, section, and visibility info.
57434fc5a0eSChris Lattner       CopyGVAttributes(NewDGV, SGV);
575487375e9SOwen Anderson       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
576fac7b595SOwen Anderson                                                               DGV->getType()));
57734fc5a0eSChris Lattner 
57834fc5a0eSChris Lattner       // DGV will conflict with NewDGV because they both had the same
579f6439246SAnton Korobeynikov       // name. We must erase this now so ForceRenaming doesn't assert
580f6439246SAnton Korobeynikov       // because DGV might not have internal linkage.
58134fc5a0eSChris Lattner       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
58234fc5a0eSChris Lattner         Var->eraseFromParent();
58334fc5a0eSChris Lattner       else
58434fc5a0eSChris Lattner         cast<Function>(DGV)->eraseFromParent();
585f6439246SAnton Korobeynikov 
58634fc5a0eSChris Lattner       // If the symbol table renamed the global, but it is an externally visible
58734fc5a0eSChris Lattner       // symbol, DGV must be an existing global with internal linkage.  Rename.
5886de96a1bSRafael Espindola       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasLocalLinkage())
589f6439246SAnton Korobeynikov         ForceRenaming(NewDGV, SGV->getName());
590f6439246SAnton Korobeynikov 
5910ead7a50SChris Lattner       // Inherit const as appropriate.
59234fc5a0eSChris Lattner       NewDGV->setConstant(SGV->isConstant());
593fc61de39SChris Lattner 
5940ead7a50SChris Lattner       // Make sure to remember this mapping.
5950ead7a50SChris Lattner       ValueMap[SGV] = NewDGV;
5960ead7a50SChris Lattner       continue;
5970ead7a50SChris Lattner     }
598f6439246SAnton Korobeynikov 
59934fc5a0eSChris Lattner     // Not "link from source", keep the one in the DestModule and remap the
60034fc5a0eSChris Lattner     // input onto it.
60134fc5a0eSChris Lattner 
60234fc5a0eSChris Lattner     // Special case for const propagation.
60334fc5a0eSChris Lattner     if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
60434fc5a0eSChris Lattner       if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
60534fc5a0eSChris Lattner         DGVar->setConstant(true);
60634fc5a0eSChris Lattner 
607006659f0SAnton Korobeynikov     // SGV is global, but DGV is alias.
608006659f0SAnton Korobeynikov     if (isa<GlobalAlias>(DGV)) {
609006659f0SAnton Korobeynikov       // The only valid mappings are:
610006659f0SAnton Korobeynikov       // - SGV is external declaration, which is effectively a no-op.
611006659f0SAnton Korobeynikov       // - SGV is weak, when we just need to throw SGV out.
612d725c991SDuncan Sands       if (!SGV->isDeclaration() && !SGV->isWeakForLinker())
6130ead7a50SChris Lattner         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
6140ead7a50SChris Lattner                      "': symbol multiple defined");
615006659f0SAnton Korobeynikov     }
6160ead7a50SChris Lattner 
617489e505aSRafael Espindola     // Set calculated linkage and unnamed_addr
61834fc5a0eSChris Lattner     DGV->setLinkage(NewLinkage);
619489e505aSRafael Espindola     DGV->setUnnamedAddr(HasUnnamedAddr);
62034fc5a0eSChris Lattner 
62134fc5a0eSChris Lattner     // Make sure to remember this mapping...
622487375e9SOwen Anderson     ValueMap[SGV] = ConstantExpr::getBitCast(DGV, SGV->getType());
623361e513dSReid Spencer   }
624361e513dSReid Spencer   return false;
625361e513dSReid Spencer }
626361e513dSReid Spencer 
627dac5fa94SAnton Korobeynikov static GlobalValue::LinkageTypes
628dac5fa94SAnton Korobeynikov CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
62912da8ce3SDuncan Sands   GlobalValue::LinkageTypes SL = SGV->getLinkage();
63012da8ce3SDuncan Sands   GlobalValue::LinkageTypes DL = DGV->getLinkage();
63112da8ce3SDuncan Sands   if (SL == GlobalValue::ExternalLinkage || DL == GlobalValue::ExternalLinkage)
632dac5fa94SAnton Korobeynikov     return GlobalValue::ExternalLinkage;
63312da8ce3SDuncan Sands   else if (SL == GlobalValue::WeakAnyLinkage ||
63412da8ce3SDuncan Sands            DL == GlobalValue::WeakAnyLinkage)
63512da8ce3SDuncan Sands     return GlobalValue::WeakAnyLinkage;
63612da8ce3SDuncan Sands   else if (SL == GlobalValue::WeakODRLinkage ||
63712da8ce3SDuncan Sands            DL == GlobalValue::WeakODRLinkage)
63812da8ce3SDuncan Sands     return GlobalValue::WeakODRLinkage;
63912da8ce3SDuncan Sands   else if (SL == GlobalValue::InternalLinkage &&
64012da8ce3SDuncan Sands            DL == GlobalValue::InternalLinkage)
641dac5fa94SAnton Korobeynikov     return GlobalValue::InternalLinkage;
642a3c6f6bfSBill Wendling   else if (SL == GlobalValue::LinkerPrivateLinkage &&
643a3c6f6bfSBill Wendling            DL == GlobalValue::LinkerPrivateLinkage)
644a3c6f6bfSBill Wendling     return GlobalValue::LinkerPrivateLinkage;
6453aeedd1eSBill Wendling   else if (SL == GlobalValue::LinkerPrivateWeakLinkage &&
6463aeedd1eSBill Wendling            DL == GlobalValue::LinkerPrivateWeakLinkage)
6473aeedd1eSBill Wendling     return GlobalValue::LinkerPrivateWeakLinkage;
6483aeedd1eSBill Wendling   else if (SL == GlobalValue::LinkerPrivateWeakDefAutoLinkage &&
6493aeedd1eSBill Wendling            DL == GlobalValue::LinkerPrivateWeakDefAutoLinkage)
6503aeedd1eSBill Wendling     return GlobalValue::LinkerPrivateWeakDefAutoLinkage;
6516de96a1bSRafael Espindola   else {
65212da8ce3SDuncan Sands     assert (SL == GlobalValue::PrivateLinkage &&
65312da8ce3SDuncan Sands             DL == GlobalValue::PrivateLinkage && "Unexpected linkage type");
6546de96a1bSRafael Espindola     return GlobalValue::PrivateLinkage;
655dac5fa94SAnton Korobeynikov   }
656dac5fa94SAnton Korobeynikov }
657dac5fa94SAnton Korobeynikov 
658b00c9c0dSLauro Ramos Venancio // LinkAlias - Loop through the alias in the src module and link them into the
659dac5fa94SAnton Korobeynikov // dest module. We're assuming, that all functions/global variables were already
660dac5fa94SAnton Korobeynikov // linked in.
6612e13597fSAnton Korobeynikov static bool LinkAlias(Module *Dest, const Module *Src,
662a2095034SDan Gohman                       ValueToValueMapTy &ValueMap,
6632e13597fSAnton Korobeynikov                       std::string *Err) {
664b00c9c0dSLauro Ramos Venancio   // Loop over all alias in the src module
665b00c9c0dSLauro Ramos Venancio   for (Module::const_alias_iterator I = Src->alias_begin(),
666b00c9c0dSLauro Ramos Venancio          E = Src->alias_end(); I != E; ++I) {
667dac5fa94SAnton Korobeynikov     const GlobalAlias *SGA = I;
668dac5fa94SAnton Korobeynikov     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
669dac5fa94SAnton Korobeynikov     GlobalAlias *NewGA = NULL;
670b00c9c0dSLauro Ramos Venancio 
671dac5fa94SAnton Korobeynikov     // Globals were already linked, thus we can just query ValueMap for variant
672acbdaa24SAnton Korobeynikov     // of SAliasee in Dest.
673a2095034SDan Gohman     ValueToValueMapTy::const_iterator VMI = ValueMap.find(SAliasee);
674d48ed17dSTed Kremenek     assert(VMI != ValueMap.end() && "Aliasee not linked");
675d48ed17dSTed Kremenek     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
676acbdaa24SAnton Korobeynikov     GlobalValue* DGV = NULL;
677b00c9c0dSLauro Ramos Venancio 
678e73bc890SRafael Espindola     // Fixup aliases to bitcasts.  Note that aliases to GEPs are still broken
679e73bc890SRafael Espindola     // by this, but aliases to GEPs are broken to a lot of other things, so
680e73bc890SRafael Espindola     // it's less important.
681e73bc890SRafael Espindola     Constant *DAliaseeConst = DAliasee;
682e73bc890SRafael Espindola     if (SGA->getType() != DAliasee->getType())
683e73bc890SRafael Espindola       DAliaseeConst = ConstantExpr::getBitCast(DAliasee, SGA->getType());
684e73bc890SRafael Espindola 
685dac5fa94SAnton Korobeynikov     // Try to find something 'similar' to SGA in destination module.
6866de96a1bSRafael Espindola     if (!DGV && !SGA->hasLocalLinkage()) {
687acbdaa24SAnton Korobeynikov       DGV = Dest->getNamedAlias(SGA->getName());
688acbdaa24SAnton Korobeynikov 
689dac5fa94SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
690acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
691683ed3d9SChris Lattner         RecursiveResolveTypes(SGA->getType(), DGV->getType());
692acbdaa24SAnton Korobeynikov     }
6932e13597fSAnton Korobeynikov 
6946de96a1bSRafael Espindola     if (!DGV && !SGA->hasLocalLinkage()) {
695acbdaa24SAnton Korobeynikov       DGV = Dest->getGlobalVariable(SGA->getName());
696acbdaa24SAnton Korobeynikov 
697acbdaa24SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
698acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
699683ed3d9SChris Lattner         RecursiveResolveTypes(SGA->getType(), DGV->getType());
700acbdaa24SAnton Korobeynikov     }
701acbdaa24SAnton Korobeynikov 
7026de96a1bSRafael Espindola     if (!DGV && !SGA->hasLocalLinkage()) {
703acbdaa24SAnton Korobeynikov       DGV = Dest->getFunction(SGA->getName());
704acbdaa24SAnton Korobeynikov 
705acbdaa24SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
706acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
707683ed3d9SChris Lattner         RecursiveResolveTypes(SGA->getType(), DGV->getType());
708acbdaa24SAnton Korobeynikov     }
709acbdaa24SAnton Korobeynikov 
710acbdaa24SAnton Korobeynikov     // No linking to be performed on internal stuff.
7116de96a1bSRafael Espindola     if (DGV && DGV->hasLocalLinkage())
712acbdaa24SAnton Korobeynikov       DGV = NULL;
713acbdaa24SAnton Korobeynikov 
714acbdaa24SAnton Korobeynikov     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
715acbdaa24SAnton Korobeynikov       // Types are known to be the same, check whether aliasees equal. As
716dac5fa94SAnton Korobeynikov       // globals are already linked we just need query ValueMap to find the
717dac5fa94SAnton Korobeynikov       // mapping.
718dac5fa94SAnton Korobeynikov       if (DAliasee == DGA->getAliasedGlobal()) {
719dac5fa94SAnton Korobeynikov         // This is just two copies of the same alias. Propagate linkage, if
720dac5fa94SAnton Korobeynikov         // necessary.
721dac5fa94SAnton Korobeynikov         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
722dac5fa94SAnton Korobeynikov 
723dac5fa94SAnton Korobeynikov         NewGA = DGA;
724dac5fa94SAnton Korobeynikov         // Proceed to 'common' steps
725dac5fa94SAnton Korobeynikov       } else
726eeb5ca6fSAnton Korobeynikov         return Error(Err, "Alias Collision on '"  + SGA->getName()+
727eeb5ca6fSAnton Korobeynikov                      "': aliases have different aliasees");
728acbdaa24SAnton Korobeynikov     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
7299cd0b50fSAnton Korobeynikov       // The only allowed way is to link alias with external declaration or weak
7309cd0b50fSAnton Korobeynikov       // symbol..
731d725c991SDuncan Sands       if (DGVar->isDeclaration() || DGVar->isWeakForLinker()) {
732510fc32dSAnton Korobeynikov         // But only if aliasee is global too...
733510fc32dSAnton Korobeynikov         if (!isa<GlobalVariable>(DAliasee))
734510fc32dSAnton Korobeynikov           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
735510fc32dSAnton Korobeynikov                        "': aliasee is not global variable");
736510fc32dSAnton Korobeynikov 
737dac5fa94SAnton Korobeynikov         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
738e73bc890SRafael Espindola                                 SGA->getName(), DAliaseeConst, Dest);
739dac5fa94SAnton Korobeynikov         CopyGVAttributes(NewGA, SGA);
740dac5fa94SAnton Korobeynikov 
741dac5fa94SAnton Korobeynikov         // Any uses of DGV need to change to NewGA, with cast, if needed.
742acbdaa24SAnton Korobeynikov         if (SGA->getType() != DGVar->getType())
743487375e9SOwen Anderson           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
744acbdaa24SAnton Korobeynikov                                                              DGVar->getType()));
745dac5fa94SAnton Korobeynikov         else
746acbdaa24SAnton Korobeynikov           DGVar->replaceAllUsesWith(NewGA);
747dac5fa94SAnton Korobeynikov 
748acbdaa24SAnton Korobeynikov         // DGVar will conflict with NewGA because they both had the same
749dac5fa94SAnton Korobeynikov         // name. We must erase this now so ForceRenaming doesn't assert
750dac5fa94SAnton Korobeynikov         // because DGV might not have internal linkage.
751acbdaa24SAnton Korobeynikov         DGVar->eraseFromParent();
752dac5fa94SAnton Korobeynikov 
753dac5fa94SAnton Korobeynikov         // Proceed to 'common' steps
754dac5fa94SAnton Korobeynikov       } else
755eeb5ca6fSAnton Korobeynikov         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
756eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
757acbdaa24SAnton Korobeynikov     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
7589cd0b50fSAnton Korobeynikov       // The only allowed way is to link alias with external declaration or weak
7599cd0b50fSAnton Korobeynikov       // symbol...
760d725c991SDuncan Sands       if (DF->isDeclaration() || DF->isWeakForLinker()) {
761510fc32dSAnton Korobeynikov         // But only if aliasee is function too...
762510fc32dSAnton Korobeynikov         if (!isa<Function>(DAliasee))
763510fc32dSAnton Korobeynikov           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
764510fc32dSAnton Korobeynikov                        "': aliasee is not function");
765510fc32dSAnton Korobeynikov 
76624f65c3aSAnton Korobeynikov         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
767e73bc890SRafael Espindola                                 SGA->getName(), DAliaseeConst, Dest);
76824f65c3aSAnton Korobeynikov         CopyGVAttributes(NewGA, SGA);
76924f65c3aSAnton Korobeynikov 
77024f65c3aSAnton Korobeynikov         // Any uses of DF need to change to NewGA, with cast, if needed.
77124f65c3aSAnton Korobeynikov         if (SGA->getType() != DF->getType())
772487375e9SOwen Anderson           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
77324f65c3aSAnton Korobeynikov                                                           DF->getType()));
77424f65c3aSAnton Korobeynikov         else
77524f65c3aSAnton Korobeynikov           DF->replaceAllUsesWith(NewGA);
77624f65c3aSAnton Korobeynikov 
77724f65c3aSAnton Korobeynikov         // DF will conflict with NewGA because they both had the same
77824f65c3aSAnton Korobeynikov         // name. We must erase this now so ForceRenaming doesn't assert
77924f65c3aSAnton Korobeynikov         // because DF might not have internal linkage.
78024f65c3aSAnton Korobeynikov         DF->eraseFromParent();
78124f65c3aSAnton Korobeynikov 
78224f65c3aSAnton Korobeynikov         // Proceed to 'common' steps
78324f65c3aSAnton Korobeynikov       } else
784eeb5ca6fSAnton Korobeynikov         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
785eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
786dac5fa94SAnton Korobeynikov     } else {
787acbdaa24SAnton Korobeynikov       // No linking to be performed, simply create an identical version of the
788acbdaa24SAnton Korobeynikov       // alias over in the dest module...
789dac5fa94SAnton Korobeynikov       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
790e73bc890SRafael Espindola                               SGA->getName(), DAliaseeConst, Dest);
791dac5fa94SAnton Korobeynikov       CopyGVAttributes(NewGA, SGA);
792dac5fa94SAnton Korobeynikov 
793dac5fa94SAnton Korobeynikov       // Proceed to 'common' steps
794b00c9c0dSLauro Ramos Venancio     }
795dac5fa94SAnton Korobeynikov 
796dac5fa94SAnton Korobeynikov     assert(NewGA && "No alias was created in destination module!");
797dac5fa94SAnton Korobeynikov 
798d5160da5SAnton Korobeynikov     // If the symbol table renamed the alias, but it is an externally visible
799acbdaa24SAnton Korobeynikov     // symbol, DGA must be an global value with internal linkage. Rename it.
800dac5fa94SAnton Korobeynikov     if (NewGA->getName() != SGA->getName() &&
8016de96a1bSRafael Espindola         !NewGA->hasLocalLinkage())
802dac5fa94SAnton Korobeynikov       ForceRenaming(NewGA, SGA->getName());
803dac5fa94SAnton Korobeynikov 
804dac5fa94SAnton Korobeynikov     // Remember this mapping so uses in the source module get remapped
805a2095034SDan Gohman     // later by MapValue.
80666a6271cSAnton Korobeynikov     ValueMap[SGA] = NewGA;
807dac5fa94SAnton Korobeynikov   }
808dac5fa94SAnton Korobeynikov 
809b00c9c0dSLauro Ramos Venancio   return false;
810b00c9c0dSLauro Ramos Venancio }
811b00c9c0dSLauro Ramos Venancio 
812361e513dSReid Spencer 
813361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all
814361e513dSReid Spencer // globals that may be referenced are in Dest.
815361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src,
816a2095034SDan Gohman                             ValueToValueMapTy &ValueMap,
817361e513dSReid Spencer                             std::string *Err) {
818361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
81944ab8aefSChris Lattner   for (Module::const_global_iterator I = Src->global_begin(),
82044ab8aefSChris Lattner        E = Src->global_end(); I != E; ++I) {
821361e513dSReid Spencer     const GlobalVariable *SGV = I;
822361e513dSReid Spencer 
823361e513dSReid Spencer     if (SGV->hasInitializer()) {      // Only process initialized GV's
82443f8d164SChris Lattner       // Figure out what the initializer looks like in the dest module.
825361e513dSReid Spencer       Constant *SInit =
82643f8d164SChris Lattner         cast<Constant>(MapValue(SGV->getInitializer(), ValueMap));
827006659f0SAnton Korobeynikov       // Grab destination global variable or alias.
828006659f0SAnton Korobeynikov       GlobalValue *DGV = cast<GlobalValue>(ValueMap[SGV]->stripPointerCasts());
829361e513dSReid Spencer 
8305ed50b61SBill Wendling       // If dest if global variable, check that initializers match.
831006659f0SAnton Korobeynikov       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
832006659f0SAnton Korobeynikov         if (DGVar->hasInitializer()) {
8335ed50b61SBill Wendling           if (SGV->hasExternalLinkage()) {
834006659f0SAnton Korobeynikov             if (DGVar->getInitializer() != SInit)
835006659f0SAnton Korobeynikov               return Error(Err, "Global Variable Collision on '" +
836006659f0SAnton Korobeynikov                            SGV->getName() +
837eeb5ca6fSAnton Korobeynikov                            "': global variables have different initializers");
838d725c991SDuncan Sands           } else if (DGVar->isWeakForLinker()) {
839361e513dSReid Spencer             // Nothing is required, mapped values will take the new global
840361e513dSReid Spencer             // automatically.
841d725c991SDuncan Sands           } else if (SGV->isWeakForLinker()) {
842361e513dSReid Spencer             // Nothing is required, mapped values will take the new global
843361e513dSReid Spencer             // automatically.
844006659f0SAnton Korobeynikov           } else if (DGVar->hasAppendingLinkage()) {
845fbcc663cSTorok Edwin             llvm_unreachable("Appending linkage unimplemented!");
846361e513dSReid Spencer           } else {
847fbcc663cSTorok Edwin             llvm_unreachable("Unknown linkage!");
848361e513dSReid Spencer           }
849361e513dSReid Spencer         } else {
850361e513dSReid Spencer           // Copy the initializer over now...
851006659f0SAnton Korobeynikov           DGVar->setInitializer(SInit);
852006659f0SAnton Korobeynikov         }
853006659f0SAnton Korobeynikov       } else {
854006659f0SAnton Korobeynikov         // Destination is alias, the only valid situation is when source is
855006659f0SAnton Korobeynikov         // weak. Also, note, that we already checked linkage in LinkGlobals(),
856006659f0SAnton Korobeynikov         // thus we assert here.
857006659f0SAnton Korobeynikov         // FIXME: Should we weaken this assumption, 'dereference' alias and
858006659f0SAnton Korobeynikov         // check for initializer of aliasee?
859d725c991SDuncan Sands         assert(SGV->isWeakForLinker());
860361e513dSReid Spencer       }
861361e513dSReid Spencer     }
862361e513dSReid Spencer   }
863361e513dSReid Spencer   return false;
864361e513dSReid Spencer }
865361e513dSReid Spencer 
866361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules,
867361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes
868361e513dSReid Spencer // to the Dest function...
869361e513dSReid Spencer //
870361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src,
871a2095034SDan Gohman                                ValueToValueMapTy &ValueMap,
872361e513dSReid Spencer                                std::string *Err) {
87334fc5a0eSChris Lattner   ValueSymbolTable &DestSymTab = Dest->getValueSymbolTable();
87434fc5a0eSChris Lattner 
875d3ba7d9bSReid Spencer   // Loop over all of the functions in the src module, mapping them over
876361e513dSReid Spencer   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
877361e513dSReid Spencer     const Function *SF = I;   // SrcFunction
8781bb56dedSAnton Korobeynikov     GlobalValue *DGV = 0;
879228a5f18SChris Lattner 
88034fc5a0eSChris Lattner     // Check to see if may have to link the function with the global, alias or
88134fc5a0eSChris Lattner     // function.
8826de96a1bSRafael Espindola     if (SF->hasName() && !SF->hasLocalLinkage())
883e03eecb7SDaniel Dunbar       DGV = cast_or_null<GlobalValue>(DestSymTab.lookup(SF->getName()));
884361e513dSReid Spencer 
885c08e7a00SChris Lattner     // If we found a global with the same name in the dest module, but it has
886c08e7a00SChris Lattner     // internal linkage, we are really not doing any linkage here.
8876de96a1bSRafael Espindola     if (DGV && DGV->hasLocalLinkage())
888c08e7a00SChris Lattner       DGV = 0;
889c08e7a00SChris Lattner 
8901bb56dedSAnton Korobeynikov     // If types don't agree due to opaque types, try to resolve them.
89134fc5a0eSChris Lattner     if (DGV && DGV->getType() != SF->getType())
8921bb56dedSAnton Korobeynikov       RecursiveResolveTypes(SF->getType(), DGV->getType());
8931bb56dedSAnton Korobeynikov 
8940ead7a50SChris Lattner     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
8950ead7a50SChris Lattner     bool LinkFromSrc = false;
8960ead7a50SChris Lattner     if (GetLinkageResult(DGV, SF, NewLinkage, LinkFromSrc, Err))
8970ead7a50SChris Lattner       return true;
8980ead7a50SChris Lattner 
899228a5f18SChris Lattner     // If there is no linkage to be performed, just bring over SF without
900228a5f18SChris Lattner     // modifying it.
9011bb56dedSAnton Korobeynikov     if (DGV == 0) {
902228a5f18SChris Lattner       // Function does not already exist, simply insert an function signature
903228a5f18SChris Lattner       // identical to SF into the dest module.
904228a5f18SChris Lattner       Function *NewDF = Function::Create(SF->getFunctionType(),
905228a5f18SChris Lattner                                          SF->getLinkage(),
906228a5f18SChris Lattner                                          SF->getName(), Dest);
907228a5f18SChris Lattner       CopyGVAttributes(NewDF, SF);
908ec7441b3SChris Lattner 
909228a5f18SChris Lattner       // If the LLVM runtime renamed the function, but it is an externally
910228a5f18SChris Lattner       // visible symbol, DF must be an existing function with internal linkage.
911228a5f18SChris Lattner       // Rename it.
9126de96a1bSRafael Espindola       if (!NewDF->hasLocalLinkage() && NewDF->getName() != SF->getName())
913228a5f18SChris Lattner         ForceRenaming(NewDF, SF->getName());
914228a5f18SChris Lattner 
915228a5f18SChris Lattner       // ... and remember this mapping...
916228a5f18SChris Lattner       ValueMap[SF] = NewDF;
917228a5f18SChris Lattner       continue;
9180ead7a50SChris Lattner     }
9190ead7a50SChris Lattner 
9200ead7a50SChris Lattner     // If the visibilities of the symbols disagree and the destination is a
9210ead7a50SChris Lattner     // prototype, take the visibility of its input.
9220ead7a50SChris Lattner     if (DGV->isDeclaration())
9230ead7a50SChris Lattner       DGV->setVisibility(SF->getVisibility());
9240ead7a50SChris Lattner 
9250ead7a50SChris Lattner     if (LinkFromSrc) {
9260ead7a50SChris Lattner       if (isa<GlobalAlias>(DGV))
9271bb56dedSAnton Korobeynikov         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
9281bb56dedSAnton Korobeynikov                      "': symbol multiple defined");
9291bb56dedSAnton Korobeynikov 
9303aaaa0b2SReid Spencer       // We have a definition of the same name but different type in the
9313aaaa0b2SReid Spencer       // source module. Copy the prototype to the destination and replace
9323aaaa0b2SReid Spencer       // uses of the destination's prototype with the new prototype.
9330ead7a50SChris Lattner       Function *NewDF = Function::Create(SF->getFunctionType(), NewLinkage,
9343aaaa0b2SReid Spencer                                          SF->getName(), Dest);
9353aaaa0b2SReid Spencer       CopyGVAttributes(NewDF, SF);
9363aaaa0b2SReid Spencer 
9373aaaa0b2SReid Spencer       // Any uses of DF need to change to NewDF, with cast
938487375e9SOwen Anderson       DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF,
939fac7b595SOwen Anderson                                                               DGV->getType()));
9403aaaa0b2SReid Spencer 
9413aaaa0b2SReid Spencer       // DF will conflict with NewDF because they both had the same. We must
9423aaaa0b2SReid Spencer       // erase this now so ForceRenaming doesn't assert because DF might
9433aaaa0b2SReid Spencer       // not have internal linkage.
9440ead7a50SChris Lattner       if (GlobalVariable *Var = dyn_cast<GlobalVariable>(DGV))
9450ead7a50SChris Lattner         Var->eraseFromParent();
9460ead7a50SChris Lattner       else
9470ead7a50SChris Lattner         cast<Function>(DGV)->eraseFromParent();
9483aaaa0b2SReid Spencer 
9493aaaa0b2SReid Spencer       // If the symbol table renamed the function, but it is an externally
9503aaaa0b2SReid Spencer       // visible symbol, DF must be an existing function with internal
9513aaaa0b2SReid Spencer       // linkage.  Rename it.
9526de96a1bSRafael Espindola       if (NewDF->getName() != SF->getName() && !NewDF->hasLocalLinkage())
9533aaaa0b2SReid Spencer         ForceRenaming(NewDF, SF->getName());
9543aaaa0b2SReid Spencer 
9553aaaa0b2SReid Spencer       // Remember this mapping so uses in the source module get remapped
956a2095034SDan Gohman       // later by MapValue.
9573aaaa0b2SReid Spencer       ValueMap[SF] = NewDF;
958228a5f18SChris Lattner       continue;
959228a5f18SChris Lattner     }
960361e513dSReid Spencer 
9610ead7a50SChris Lattner     // Not "link from source", keep the one in the DestModule and remap the
9620ead7a50SChris Lattner     // input onto it.
9630ead7a50SChris Lattner 
9640ead7a50SChris Lattner     if (isa<GlobalAlias>(DGV)) {
9650ead7a50SChris Lattner       // The only valid mappings are:
9660ead7a50SChris Lattner       // - SF is external declaration, which is effectively a no-op.
9670ead7a50SChris Lattner       // - SF is weak, when we just need to throw SF out.
968d725c991SDuncan Sands       if (!SF->isDeclaration() && !SF->isWeakForLinker())
9690ead7a50SChris Lattner         return Error(Err, "Function-Alias Collision on '" + SF->getName() +
9700ead7a50SChris Lattner                      "': symbol multiple defined");
97177e8ac4dSChris Lattner     }
97277e8ac4dSChris Lattner 
9730ead7a50SChris Lattner     // Set calculated linkage
9740ead7a50SChris Lattner     DGV->setLinkage(NewLinkage);
97577e8ac4dSChris Lattner 
9760ead7a50SChris Lattner     // Make sure to remember this mapping.
977487375e9SOwen Anderson     ValueMap[SF] = ConstantExpr::getBitCast(DGV, SF->getType());
978361e513dSReid Spencer   }
979361e513dSReid Spencer   return false;
980361e513dSReid Spencer }
981361e513dSReid Spencer 
982361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and
983361e513dSReid Spencer // fix up references to values.  At this point we know that Dest is an external
984361e513dSReid Spencer // function, and that Src is not.
9852f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src,
986a2095034SDan Gohman                              ValueToValueMapTy &ValueMap,
987361e513dSReid Spencer                              std::string *Err) {
9885301e7c6SReid Spencer   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
989361e513dSReid Spencer 
9907391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
991531f9e92SChris Lattner   Function::arg_iterator DI = Dest->arg_begin();
992531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
993361e513dSReid Spencer        I != E; ++I, ++DI) {
9947629b71dSOwen Anderson     DI->setName(I->getName());  // Copy the name information over...
995361e513dSReid Spencer 
996361e513dSReid Spencer     // Add a mapping to our local map
99766a6271cSAnton Korobeynikov     ValueMap[I] = DI;
998361e513dSReid Spencer   }
999361e513dSReid Spencer 
10002f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
10012f0557d0SChris Lattner   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1002361e513dSReid Spencer 
1003361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
1004361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
1005361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
100643f8d164SChris Lattner   // functions and patch them up to point to the local versions.
1007361e513dSReid Spencer   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
100843f8d164SChris Lattner     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
100943f8d164SChris Lattner       RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries);
10107391dde1SChris Lattner 
10117391dde1SChris Lattner   // There is no need to map the arguments anymore.
101244ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
101344ab8aefSChris Lattner        I != E; ++I)
10143aaaa0b2SReid Spencer     ValueMap.erase(I);
1015361e513dSReid Spencer 
1016361e513dSReid Spencer   return false;
1017361e513dSReid Spencer }
1018361e513dSReid Spencer 
1019361e513dSReid Spencer 
1020361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the
1021361e513dSReid Spencer // source module into the DestModule.  This consists basically of copying the
1022361e513dSReid Spencer // function over and fixing up references to values.
10232f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src,
1024a2095034SDan Gohman                                ValueToValueMapTy &ValueMap,
1025361e513dSReid Spencer                                std::string *Err) {
1026361e513dSReid Spencer 
102790246aa7SReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
102890246aa7SReid Spencer   // go
10292f0557d0SChris Lattner   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
10305301e7c6SReid Spencer     if (!SF->isDeclaration()) {               // No body if function is external
1031d53bd2daSChris Lattner       Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1032361e513dSReid Spencer 
1033361e513dSReid Spencer       // DF not external SF external?
1034d53bd2daSChris Lattner       if (DF && DF->isDeclaration())
1035361e513dSReid Spencer         // Only provide the function body if there isn't one already.
1036361e513dSReid Spencer         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1037361e513dSReid Spencer           return true;
103890246aa7SReid Spencer     }
1039361e513dSReid Spencer   }
1040361e513dSReid Spencer   return false;
1041361e513dSReid Spencer }
1042361e513dSReid Spencer 
1043361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them
1044361e513dSReid Spencer // together now.  Return true on error.
1045361e513dSReid Spencer static bool LinkAppendingVars(Module *M,
1046361e513dSReid Spencer                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1047361e513dSReid Spencer                               std::string *ErrorMsg) {
1048361e513dSReid Spencer   if (AppendingVars.empty()) return false; // Nothing to do.
1049361e513dSReid Spencer 
1050361e513dSReid Spencer   // Loop over the multimap of appending vars, processing any variables with the
1051361e513dSReid Spencer   // same name, forming a new appending global variable with both of the
1052361e513dSReid Spencer   // initializers merged together, then rewrite references to the old variables
1053361e513dSReid Spencer   // and delete them.
1054361e513dSReid Spencer   std::vector<Constant*> Inits;
1055361e513dSReid Spencer   while (AppendingVars.size() > 1) {
1056361e513dSReid Spencer     // Get the first two elements in the map...
1057361e513dSReid Spencer     std::multimap<std::string,
1058361e513dSReid Spencer       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1059361e513dSReid Spencer 
1060361e513dSReid Spencer     // If the first two elements are for different names, there is no pair...
1061361e513dSReid Spencer     // Otherwise there is a pair, so link them together...
1062361e513dSReid Spencer     if (First->first == Second->first) {
1063361e513dSReid Spencer       GlobalVariable *G1 = First->second, *G2 = Second->second;
1064361e513dSReid Spencer       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1065361e513dSReid Spencer       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1066361e513dSReid Spencer 
1067361e513dSReid Spencer       // Check to see that they two arrays agree on type...
1068361e513dSReid Spencer       if (T1->getElementType() != T2->getElementType())
1069361e513dSReid Spencer         return Error(ErrorMsg,
1070361e513dSReid Spencer          "Appending variables with different element types need to be linked!");
1071361e513dSReid Spencer       if (G1->isConstant() != G2->isConstant())
1072361e513dSReid Spencer         return Error(ErrorMsg,
1073361e513dSReid Spencer                      "Appending variables linked with different const'ness!");
1074361e513dSReid Spencer 
107585703e37SLauro Ramos Venancio       if (G1->getAlignment() != G2->getAlignment())
107685703e37SLauro Ramos Venancio         return Error(ErrorMsg,
107785703e37SLauro Ramos Venancio          "Appending variables with different alignment need to be linked!");
107885703e37SLauro Ramos Venancio 
107985703e37SLauro Ramos Venancio       if (G1->getVisibility() != G2->getVisibility())
108085703e37SLauro Ramos Venancio         return Error(ErrorMsg,
108185703e37SLauro Ramos Venancio          "Appending variables with different visibility need to be linked!");
108285703e37SLauro Ramos Venancio 
108385703e37SLauro Ramos Venancio       if (G1->getSection() != G2->getSection())
108485703e37SLauro Ramos Venancio         return Error(ErrorMsg,
108585703e37SLauro Ramos Venancio          "Appending variables with different section name need to be linked!");
108685703e37SLauro Ramos Venancio 
1087361e513dSReid Spencer       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
10884056ca95SOwen Anderson       ArrayType *NewType = ArrayType::get(T1->getElementType(),
1089fac7b595SOwen Anderson                                                          NewSize);
1090361e513dSReid Spencer 
1091d490d4f0SChris Lattner       G1->setName("");   // Clear G1's name in case of a conflict!
1092d490d4f0SChris Lattner 
1093361e513dSReid Spencer       // Create the new global variable...
1094361e513dSReid Spencer       GlobalVariable *NG =
1095b17f3294SOwen Anderson         new GlobalVariable(*M, NewType, G1->isConstant(), G1->getLinkage(),
1096b17f3294SOwen Anderson                            /*init*/0, First->first, 0, G1->isThreadLocal(),
1097b32a9ef0SChris Lattner                            G1->getType()->getAddressSpace());
1098361e513dSReid Spencer 
109985703e37SLauro Ramos Venancio       // Propagate alignment, visibility and section info.
110085703e37SLauro Ramos Venancio       CopyGVAttributes(NG, G1);
110185703e37SLauro Ramos Venancio 
1102361e513dSReid Spencer       // Merge the initializer...
1103361e513dSReid Spencer       Inits.reserve(NewSize);
1104361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1105361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1106361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
1107361e513dSReid Spencer       } else {
1108361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
11095a1acd99SOwen Anderson         Constant *CV = Constant::getNullValue(T1->getElementType());
1110361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1111361e513dSReid Spencer           Inits.push_back(CV);
1112361e513dSReid Spencer       }
1113361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1114361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1115361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
1116361e513dSReid Spencer       } else {
1117361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
11185a1acd99SOwen Anderson         Constant *CV = Constant::getNullValue(T2->getElementType());
1119361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1120361e513dSReid Spencer           Inits.push_back(CV);
1121361e513dSReid Spencer       }
1122c2c7932cSOwen Anderson       NG->setInitializer(ConstantArray::get(NewType, Inits));
1123361e513dSReid Spencer       Inits.clear();
1124361e513dSReid Spencer 
1125361e513dSReid Spencer       // Replace any uses of the two global variables with uses of the new
1126361e513dSReid Spencer       // global...
1127361e513dSReid Spencer 
1128361e513dSReid Spencer       // FIXME: This should rewrite simple/straight-forward uses such as
1129361e513dSReid Spencer       // getelementptr instructions to not use the Cast!
1130487375e9SOwen Anderson       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1131fac7b595SOwen Anderson                              G1->getType()));
1132487375e9SOwen Anderson       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG,
1133fac7b595SOwen Anderson                              G2->getType()));
1134361e513dSReid Spencer 
1135361e513dSReid Spencer       // Remove the two globals from the module now...
1136361e513dSReid Spencer       M->getGlobalList().erase(G1);
1137361e513dSReid Spencer       M->getGlobalList().erase(G2);
1138361e513dSReid Spencer 
1139361e513dSReid Spencer       // Put the new global into the AppendingVars map so that we can handle
1140361e513dSReid Spencer       // linking of more than two vars...
1141361e513dSReid Spencer       Second->second = NG;
1142361e513dSReid Spencer     }
1143361e513dSReid Spencer     AppendingVars.erase(First);
1144361e513dSReid Spencer   }
1145361e513dSReid Spencer 
1146361e513dSReid Spencer   return false;
1147361e513dSReid Spencer }
1148361e513dSReid Spencer 
11492609888fSAnton Korobeynikov static bool ResolveAliases(Module *Dest) {
11502609888fSAnton Korobeynikov   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1151e6d90f5aSAnton Korobeynikov        I != E; ++I)
11522c4a34aeSDavid Chisnall     // We can't sue resolveGlobalAlias here because we need to preserve
11532c4a34aeSDavid Chisnall     // bitcasts and GEPs.
11542c4a34aeSDavid Chisnall     if (const Constant *C = I->getAliasee()) {
11552c4a34aeSDavid Chisnall       while (dyn_cast<GlobalAlias>(C))
11562c4a34aeSDavid Chisnall         C = cast<GlobalAlias>(C)->getAliasee();
11572c4a34aeSDavid Chisnall       const GlobalValue *GV = dyn_cast<GlobalValue>(C);
11582c4a34aeSDavid Chisnall       if (C != I && !(GV && GV->isDeclaration()))
11592c4a34aeSDavid Chisnall         I->replaceAllUsesWith(const_cast<Constant*>(C));
11602c4a34aeSDavid Chisnall     }
11612609888fSAnton Korobeynikov 
11622609888fSAnton Korobeynikov   return false;
11632609888fSAnton Korobeynikov }
1164361e513dSReid Spencer 
1165361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting
1166361e513dSReid Spencer // left module modified to be the composite of the two input modules.  If an
1167361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1168361e513dSReid Spencer // the problem.  Upon failure, the Dest module could be in a modified state, and
1169361e513dSReid Spencer // shouldn't be relied on to be consistent.
1170c4e31534SReid Spencer bool
1171c4e31534SReid Spencer Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1172361e513dSReid Spencer   assert(Dest != 0 && "Invalid Destination module");
1173361e513dSReid Spencer   assert(Src  != 0 && "Invalid Source Module");
1174361e513dSReid Spencer 
11757f3bd82aSChris Lattner   if (Dest->getDataLayout().empty()) {
11767f3bd82aSChris Lattner     if (!Src->getDataLayout().empty()) {
117778bddc38SChris Lattner       Dest->setDataLayout(Src->getDataLayout());
11787f3bd82aSChris Lattner     } else {
11793ac38e99SReid Spencer       std::string DataLayout;
11803ac38e99SReid Spencer 
1181bddf51bcSAnton Korobeynikov       if (Dest->getEndianness() == Module::AnyEndianness) {
11823ac38e99SReid Spencer         if (Src->getEndianness() == Module::BigEndian)
11833ac38e99SReid Spencer           DataLayout.append("E");
11843ac38e99SReid Spencer         else if (Src->getEndianness() == Module::LittleEndian)
11853ac38e99SReid Spencer           DataLayout.append("e");
1186bddf51bcSAnton Korobeynikov       }
1187bddf51bcSAnton Korobeynikov 
1188bddf51bcSAnton Korobeynikov       if (Dest->getPointerSize() == Module::AnyPointerSize) {
11893ac38e99SReid Spencer         if (Src->getPointerSize() == Module::Pointer64)
11903ac38e99SReid Spencer           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
11913ac38e99SReid Spencer         else if (Src->getPointerSize() == Module::Pointer32)
11923ac38e99SReid Spencer           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1193bddf51bcSAnton Korobeynikov       }
11943ac38e99SReid Spencer       Dest->setDataLayout(DataLayout);
11957f3bd82aSChris Lattner     }
11967f3bd82aSChris Lattner   }
1197361e513dSReid Spencer 
119890c2df5bSChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
11997f3bd82aSChris Lattner   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
12007f3bd82aSChris Lattner     Dest->setTargetTriple(Src->getTargetTriple());
12017f3bd82aSChris Lattner 
12027f3bd82aSChris Lattner   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
12037f3bd82aSChris Lattner       Src->getDataLayout() != Dest->getDataLayout())
1204b25de3ffSChris Lattner     errs() << "WARNING: Linking two modules of different data layouts!\n";
1205b7f5916eSChris Lattner   if (!Src->getTargetTriple().empty() &&
1206e240995eSChris Lattner       Dest->getTargetTriple() != Src->getTargetTriple()) {
1207e240995eSChris Lattner     errs() << "WARNING: Linking two modules of different target triples: ";
1208e240995eSChris Lattner     if (!Src->getModuleIdentifier().empty())
1209e240995eSChris Lattner       errs() << Src->getModuleIdentifier() << ": ";
1210e240995eSChris Lattner     errs() << "'" << Src->getTargetTriple() << "' and '"
1211e240995eSChris Lattner            << Dest->getTargetTriple() << "'\n";
1212e240995eSChris Lattner   }
1213361e513dSReid Spencer 
121490c2df5bSChris Lattner   // Append the module inline asm string.
12158ebd2164SChris Lattner   if (!Src->getModuleInlineAsm().empty()) {
12168ebd2164SChris Lattner     if (Dest->getModuleInlineAsm().empty())
12178ebd2164SChris Lattner       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1218dd2d3fafSChris Lattner     else
12198ebd2164SChris Lattner       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
12208ebd2164SChris Lattner                                Src->getModuleInlineAsm());
1221dd2d3fafSChris Lattner   }
1222dd2d3fafSChris Lattner 
1223361e513dSReid Spencer   // Update the destination module's dependent libraries list with the libraries
1224361e513dSReid Spencer   // from the source module. There's no opportunity for duplicates here as the
1225361e513dSReid Spencer   // Module ensures that duplicate insertions are discarded.
122690c2df5bSChris Lattner   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
122790c2df5bSChris Lattner        SI != SE; ++SI)
1228361e513dSReid Spencer     Dest->addLibrary(*SI);
1229361e513dSReid Spencer 
1230361e513dSReid Spencer   // LinkTypes - Go through the symbol table of the Src module and see if any
1231361e513dSReid Spencer   // types are named in the src module that are not named in the Dst module.
1232361e513dSReid Spencer   // Make sure there are no type name conflicts.
1233d3ba7d9bSReid Spencer   if (LinkTypes(Dest, Src, ErrorMsg))
1234d3ba7d9bSReid Spencer     return true;
1235361e513dSReid Spencer 
1236361e513dSReid Spencer   // ValueMap - Mapping of values from what they used to be in Src, to what they
1237a2095034SDan Gohman   // are now in Dest.  ValueToValueMapTy is a ValueMap, which involves some
1238a2095034SDan Gohman   // overhead due to the use of Value handles which the Linker doesn't actually
1239a2095034SDan Gohman   // need, but this allows us to reuse the ValueMapper code.
1240a2095034SDan Gohman   ValueToValueMapTy ValueMap;
1241361e513dSReid Spencer 
1242361e513dSReid Spencer   // AppendingVars - Keep track of global variables in the destination module
1243361e513dSReid Spencer   // with appending linkage.  After the module is linked together, they are
1244361e513dSReid Spencer   // appended and the module is rewritten.
1245361e513dSReid Spencer   std::multimap<std::string, GlobalVariable *> AppendingVars;
124644ab8aefSChris Lattner   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
124744ab8aefSChris Lattner        I != E; ++I) {
1248361e513dSReid Spencer     // Add all of the appending globals already in the Dest module to
1249361e513dSReid Spencer     // AppendingVars.
1250361e513dSReid Spencer     if (I->hasAppendingLinkage())
1251361e513dSReid Spencer       AppendingVars.insert(std::make_pair(I->getName(), I));
1252361e513dSReid Spencer   }
1253361e513dSReid Spencer 
1254361e513dSReid Spencer   // Insert all of the globals in src into the Dest module... without linking
1255361e513dSReid Spencer   // initializers (which could refer to functions not yet mapped over).
12563aaaa0b2SReid Spencer   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1257361e513dSReid Spencer     return true;
1258361e513dSReid Spencer 
1259361e513dSReid Spencer   // Link the functions together between the two modules, without doing function
1260361e513dSReid Spencer   // bodies... this just adds external function prototypes to the Dest
1261361e513dSReid Spencer   // function...  We do this so that when we begin processing function bodies,
1262361e513dSReid Spencer   // all of the global values that may be referenced are available in our
1263361e513dSReid Spencer   // ValueMap.
12643aaaa0b2SReid Spencer   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1265361e513dSReid Spencer     return true;
1266361e513dSReid Spencer 
12672e13597fSAnton Korobeynikov   // If there were any alias, link them now. We really need to do this now,
12682e13597fSAnton Korobeynikov   // because all of the aliases that may be referenced need to be available in
12692e13597fSAnton Korobeynikov   // ValueMap
12702e13597fSAnton Korobeynikov   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
12712e13597fSAnton Korobeynikov 
1272361e513dSReid Spencer   // Update the initializers in the Dest module now that all globals that may
1273361e513dSReid Spencer   // be referenced are in Dest.
1274361e513dSReid Spencer   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1275361e513dSReid Spencer 
1276361e513dSReid Spencer   // Link in the function bodies that are defined in the source module into the
1277361e513dSReid Spencer   // DestModule.  This consists basically of copying the function over and
1278361e513dSReid Spencer   // fixing up references to values.
1279361e513dSReid Spencer   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1280361e513dSReid Spencer 
1281361e513dSReid Spencer   // If there were any appending global variables, link them together now.
1282361e513dSReid Spencer   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1283361e513dSReid Spencer 
1284e43711d3SAnton Korobeynikov   // Resolve all uses of aliases with aliasees
1285e43711d3SAnton Korobeynikov   if (ResolveAliases(Dest)) return true;
1286e43711d3SAnton Korobeynikov 
12878ad536a9SDan Gohman   // Remap all of the named mdnoes in Src into the Dest module. We do this
12888ad536a9SDan Gohman   // after linking GlobalValues so that MDNodes that reference GlobalValues
12898ad536a9SDan Gohman   // are properly remapped.
12908ad536a9SDan Gohman   LinkNamedMDNodes(Dest, Src, ValueMap);
12918ad536a9SDan Gohman 
1292361e513dSReid Spencer   // If the source library's module id is in the dependent library list of the
1293361e513dSReid Spencer   // destination library, remove it since that module is now linked in.
1294ca93d840SMichael J. Spencer   const std::string &modId = Src->getModuleIdentifier();
1295ca93d840SMichael J. Spencer   if (!modId.empty())
1296ca93d840SMichael J. Spencer     Dest->removeLibrary(sys::path::stem(modId));
1297361e513dSReid Spencer 
1298361e513dSReid Spencer   return false;
1299361e513dSReid Spencer }
1300361e513dSReid Spencer 
1301361e513dSReid Spencer // vim: sw=2
1302