1361e513dSReid Spencer //===- 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"
22361e513dSReid Spencer #include "llvm/Module.h"
2332af9e8cSReid Spencer #include "llvm/TypeSymbolTable.h"
243aaaa0b2SReid Spencer #include "llvm/ValueSymbolTable.h"
25361e513dSReid Spencer #include "llvm/Instructions.h"
26361e513dSReid Spencer #include "llvm/Assembly/Writer.h"
277339b8dbSBill Wendling #include "llvm/Support/Streams.h"
28361e513dSReid Spencer #include "llvm/System/Path.h"
2930c0f336SBill Wendling #include <sstream>
30361e513dSReid Spencer using namespace llvm;
31361e513dSReid Spencer 
32361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true.
33361e513dSReid Spencer // This just makes error return conditions a little bit simpler...
34361e513dSReid Spencer static inline bool Error(std::string *E, const std::string &Message) {
35361e513dSReid Spencer   if (E) *E = Message;
36361e513dSReid Spencer   return true;
37361e513dSReid Spencer }
38361e513dSReid Spencer 
392c4f9a48SReid Spencer // ToStr - Simple wrapper function to convert a type to a string.
40361e513dSReid Spencer static std::string ToStr(const Type *Ty, const Module *M) {
41361e513dSReid Spencer   std::ostringstream OS;
42361e513dSReid Spencer   WriteTypeSymbolic(OS, Ty, M);
43361e513dSReid Spencer   return OS.str();
44361e513dSReid Spencer }
45361e513dSReid Spencer 
46361e513dSReid Spencer //
47361e513dSReid Spencer // Function: ResolveTypes()
48361e513dSReid Spencer //
49361e513dSReid Spencer // Description:
50361e513dSReid Spencer //  Attempt to link the two specified types together.
51361e513dSReid Spencer //
52361e513dSReid Spencer // Inputs:
53361e513dSReid Spencer //  DestTy - The type to which we wish to resolve.
54361e513dSReid Spencer //  SrcTy  - The original type which we want to resolve.
55361e513dSReid Spencer //
56361e513dSReid Spencer // Outputs:
57361e513dSReid Spencer //  DestST - The symbol table in which the new type should be placed.
58361e513dSReid Spencer //
59361e513dSReid Spencer // Return value:
60361e513dSReid Spencer //  true  - There is an error and the types cannot yet be linked.
61361e513dSReid Spencer //  false - No errors.
62361e513dSReid Spencer //
63361e513dSReid Spencer static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
64*e9bb8552SChris Lattner                          TypeSymbolTable *DestST) {
65361e513dSReid Spencer   if (DestTy == SrcTy) return false;       // If already equal, noop
66361e513dSReid Spencer 
67361e513dSReid Spencer   // Does the type already exist in the module?
68361e513dSReid Spencer   if (DestTy && !isa<OpaqueType>(DestTy)) {  // Yup, the type already exists...
69361e513dSReid Spencer     if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70361e513dSReid Spencer       const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
71361e513dSReid Spencer     } else {
72361e513dSReid Spencer       return true;  // Cannot link types... neither is opaque and not-equal
73361e513dSReid Spencer     }
74361e513dSReid Spencer   } else {                       // Type not in dest module.  Add it now.
75361e513dSReid Spencer     if (DestTy)                  // Type _is_ in module, just opaque...
76361e513dSReid Spencer       const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77361e513dSReid Spencer                            ->refineAbstractTypeTo(SrcTy);
78361e513dSReid Spencer   }
79361e513dSReid Spencer   return false;
80361e513dSReid Spencer }
81361e513dSReid Spencer 
82361e513dSReid Spencer static const FunctionType *getFT(const PATypeHolder &TH) {
83361e513dSReid Spencer   return cast<FunctionType>(TH.get());
84361e513dSReid Spencer }
85361e513dSReid Spencer static const StructType *getST(const PATypeHolder &TH) {
86361e513dSReid Spencer   return cast<StructType>(TH.get());
87361e513dSReid Spencer }
88361e513dSReid Spencer 
89361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it
90361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types
91361e513dSReid Spencer // are compatible.
92361e513dSReid Spencer static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
93361e513dSReid Spencer                                    const PATypeHolder &SrcTy,
9432af9e8cSReid Spencer                                    TypeSymbolTable *DestST,
95361e513dSReid Spencer                 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
96361e513dSReid Spencer   const Type *SrcTyT = SrcTy.get();
97361e513dSReid Spencer   const Type *DestTyT = DestTy.get();
98361e513dSReid Spencer   if (DestTyT == SrcTyT) return false;       // If already equal, noop
99361e513dSReid Spencer 
100361e513dSReid Spencer   // If we found our opaque type, resolve it now!
101361e513dSReid Spencer   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
102*e9bb8552SChris Lattner     return ResolveTypes(DestTyT, SrcTyT, DestST);
103361e513dSReid Spencer 
104361e513dSReid Spencer   // Two types cannot be resolved together if they are of different primitive
105361e513dSReid Spencer   // type.  For example, we cannot resolve an int to a float.
106361e513dSReid Spencer   if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
107361e513dSReid Spencer 
108361e513dSReid Spencer   // Otherwise, resolve the used type used by this derived type...
109361e513dSReid Spencer   switch (DestTyT->getTypeID()) {
1107a9c62baSReid Spencer   case Type::IntegerTyID: {
1117a9c62baSReid Spencer     if (cast<IntegerType>(DestTyT)->getBitWidth() !=
1127a9c62baSReid Spencer         cast<IntegerType>(SrcTyT)->getBitWidth())
1137a9c62baSReid Spencer       return true;
1147a9c62baSReid Spencer     return false;
1157a9c62baSReid Spencer   }
116361e513dSReid Spencer   case Type::FunctionTyID: {
117361e513dSReid Spencer     if (cast<FunctionType>(DestTyT)->isVarArg() !=
118361e513dSReid Spencer         cast<FunctionType>(SrcTyT)->isVarArg() ||
119361e513dSReid Spencer         cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
120361e513dSReid Spencer         cast<FunctionType>(SrcTyT)->getNumContainedTypes())
121361e513dSReid Spencer       return true;
122361e513dSReid Spencer     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
123361e513dSReid Spencer       if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
124*e9bb8552SChris Lattner                                  getFT(SrcTy)->getContainedType(i), DestST,
125361e513dSReid Spencer                                  Pointers))
126361e513dSReid Spencer         return true;
127361e513dSReid Spencer     return false;
128361e513dSReid Spencer   }
129361e513dSReid Spencer   case Type::StructTyID: {
130361e513dSReid Spencer     if (getST(DestTy)->getNumContainedTypes() !=
131361e513dSReid Spencer         getST(SrcTy)->getNumContainedTypes()) return 1;
132361e513dSReid Spencer     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
133361e513dSReid Spencer       if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
134*e9bb8552SChris Lattner                                  getST(SrcTy)->getContainedType(i), DestST,
135361e513dSReid Spencer                                  Pointers))
136361e513dSReid Spencer         return true;
137361e513dSReid Spencer     return false;
138361e513dSReid Spencer   }
139361e513dSReid Spencer   case Type::ArrayTyID: {
140361e513dSReid Spencer     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
141361e513dSReid Spencer     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
142361e513dSReid Spencer     if (DAT->getNumElements() != SAT->getNumElements()) return true;
143361e513dSReid Spencer     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
144*e9bb8552SChris Lattner                                   DestST, Pointers);
145361e513dSReid Spencer   }
146361e513dSReid Spencer   case Type::PointerTyID: {
147361e513dSReid Spencer     // If this is a pointer type, check to see if we have already seen it.  If
148361e513dSReid Spencer     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
149361e513dSReid Spencer     // an associative container for this search, because the type pointers (keys
150361e513dSReid Spencer     // in the container) change whenever types get resolved...
151361e513dSReid Spencer     for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
152361e513dSReid Spencer       if (Pointers[i].first == DestTy)
153361e513dSReid Spencer         return Pointers[i].second != SrcTy;
154361e513dSReid Spencer 
155361e513dSReid Spencer     // Otherwise, add the current pointers to the vector to stop recursion on
156361e513dSReid Spencer     // this pair.
157361e513dSReid Spencer     Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
158361e513dSReid Spencer     bool Result =
159361e513dSReid Spencer       RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
160361e513dSReid Spencer                              cast<PointerType>(SrcTy.get())->getElementType(),
161*e9bb8552SChris Lattner                              DestST, Pointers);
162361e513dSReid Spencer     Pointers.pop_back();
163361e513dSReid Spencer     return Result;
164361e513dSReid Spencer   }
165361e513dSReid Spencer   default: assert(0 && "Unexpected type!"); return true;
166361e513dSReid Spencer   }
167361e513dSReid Spencer }
168361e513dSReid Spencer 
169361e513dSReid Spencer static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
170361e513dSReid Spencer                                   const PATypeHolder &SrcTy,
171*e9bb8552SChris Lattner                                   TypeSymbolTable *DestST){
172361e513dSReid Spencer   std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
173*e9bb8552SChris Lattner   return RecursiveResolveTypesI(DestTy, SrcTy, DestST, PointerTypes);
174361e513dSReid Spencer }
175361e513dSReid Spencer 
176361e513dSReid Spencer 
177361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any
178361e513dSReid Spencer // types are named in the src module that are not named in the Dst module.
179361e513dSReid Spencer // Make sure there are no type name conflicts.
180361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
18132af9e8cSReid Spencer         TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
18232af9e8cSReid Spencer   const TypeSymbolTable *SrcST  = &Src->getTypeSymbolTable();
183361e513dSReid Spencer 
184361e513dSReid Spencer   // Look for a type plane for Type's...
18532af9e8cSReid Spencer   TypeSymbolTable::const_iterator TI = SrcST->begin();
18632af9e8cSReid Spencer   TypeSymbolTable::const_iterator TE = SrcST->end();
187361e513dSReid Spencer   if (TI == TE) return false;  // No named types, do nothing.
188361e513dSReid Spencer 
189361e513dSReid Spencer   // Some types cannot be resolved immediately because they depend on other
190361e513dSReid Spencer   // types being resolved to each other first.  This contains a list of types we
191361e513dSReid Spencer   // are waiting to recheck.
192361e513dSReid Spencer   std::vector<std::string> DelayedTypesToResolve;
193361e513dSReid Spencer 
194361e513dSReid Spencer   for ( ; TI != TE; ++TI ) {
195361e513dSReid Spencer     const std::string &Name = TI->first;
196361e513dSReid Spencer     const Type *RHS = TI->second;
197361e513dSReid Spencer 
198361e513dSReid Spencer     // Check to see if this type name is already in the dest module...
19932af9e8cSReid Spencer     Type *Entry = DestST->lookup(Name);
200361e513dSReid Spencer 
201*e9bb8552SChris Lattner     if (Entry == 0 && !Name.empty())
202*e9bb8552SChris Lattner       DestST->insert(Name, const_cast<Type*>(RHS));
203*e9bb8552SChris Lattner     else if (ResolveTypes(Entry, RHS, DestST)) {
204361e513dSReid Spencer       // They look different, save the types 'till later to resolve.
205361e513dSReid Spencer       DelayedTypesToResolve.push_back(Name);
206361e513dSReid Spencer     }
207361e513dSReid Spencer   }
208361e513dSReid Spencer 
209361e513dSReid Spencer   // Iteratively resolve types while we can...
210361e513dSReid Spencer   while (!DelayedTypesToResolve.empty()) {
211361e513dSReid Spencer     // Loop over all of the types, attempting to resolve them if possible...
212361e513dSReid Spencer     unsigned OldSize = DelayedTypesToResolve.size();
213361e513dSReid Spencer 
214361e513dSReid Spencer     // Try direct resolution by name...
215361e513dSReid Spencer     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
216361e513dSReid Spencer       const std::string &Name = DelayedTypesToResolve[i];
21732af9e8cSReid Spencer       Type *T1 = SrcST->lookup(Name);
21832af9e8cSReid Spencer       Type *T2 = DestST->lookup(Name);
219*e9bb8552SChris Lattner       if (!ResolveTypes(T2, T1, DestST)) {
220361e513dSReid Spencer         // We are making progress!
221361e513dSReid Spencer         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
222361e513dSReid Spencer         --i;
223361e513dSReid Spencer       }
224361e513dSReid Spencer     }
225361e513dSReid Spencer 
226361e513dSReid Spencer     // Did we not eliminate any types?
227361e513dSReid Spencer     if (DelayedTypesToResolve.size() == OldSize) {
228361e513dSReid Spencer       // Attempt to resolve subelements of types.  This allows us to merge these
229361e513dSReid Spencer       // two types: { int* } and { opaque* }
230361e513dSReid Spencer       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
231361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve[i];
23232af9e8cSReid Spencer         PATypeHolder T1(SrcST->lookup(Name));
23332af9e8cSReid Spencer         PATypeHolder T2(DestST->lookup(Name));
234361e513dSReid Spencer 
235*e9bb8552SChris Lattner         if (!RecursiveResolveTypes(T2, T1, DestST)) {
236361e513dSReid Spencer           // We are making progress!
237361e513dSReid Spencer           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
238361e513dSReid Spencer 
239361e513dSReid Spencer           // Go back to the main loop, perhaps we can resolve directly by name
240361e513dSReid Spencer           // now...
241361e513dSReid Spencer           break;
242361e513dSReid Spencer         }
243361e513dSReid Spencer       }
244361e513dSReid Spencer 
245361e513dSReid Spencer       // If we STILL cannot resolve the types, then there is something wrong.
246361e513dSReid Spencer       if (DelayedTypesToResolve.size() == OldSize) {
247361e513dSReid Spencer         // Remove the symbol name from the destination.
248361e513dSReid Spencer         DelayedTypesToResolve.pop_back();
249361e513dSReid Spencer       }
250361e513dSReid Spencer     }
251361e513dSReid Spencer   }
252361e513dSReid Spencer 
253361e513dSReid Spencer 
254361e513dSReid Spencer   return false;
255361e513dSReid Spencer }
256361e513dSReid Spencer 
257361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) {
258361e513dSReid Spencer   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
259361e513dSReid Spencer        I != E; ++I) {
260f3baad3eSBill Wendling     cerr << " Fr: " << (void*)I->first << " ";
261361e513dSReid Spencer     I->first->dump();
262f3baad3eSBill Wendling     cerr << " To: " << (void*)I->second << " ";
263361e513dSReid Spencer     I->second->dump();
264f3baad3eSBill Wendling     cerr << "\n";
265361e513dSReid Spencer   }
266361e513dSReid Spencer }
267361e513dSReid Spencer 
268361e513dSReid Spencer 
269d3ba7d9bSReid Spencer // RemapOperand - Use ValueMap to convert constants from one module to another.
270361e513dSReid Spencer static Value *RemapOperand(const Value *In,
2717391dde1SChris Lattner                            std::map<const Value*, Value*> &ValueMap) {
2727391dde1SChris Lattner   std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
2733aaaa0b2SReid Spencer   if (I != ValueMap.end())
2743aaaa0b2SReid Spencer     return I->second;
275361e513dSReid Spencer 
276d3ba7d9bSReid Spencer   // Check to see if it's a constant that we are interested in transforming.
277c7745926SChris Lattner   Value *Result = 0;
278361e513dSReid Spencer   if (const Constant *CPV = dyn_cast<Constant>(In)) {
279361e513dSReid Spencer     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
2807a9c62baSReid Spencer         isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
2817391dde1SChris Lattner       return const_cast<Constant*>(CPV);   // Simple constants stay identical.
282361e513dSReid Spencer 
283361e513dSReid Spencer     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
284361e513dSReid Spencer       std::vector<Constant*> Operands(CPA->getNumOperands());
285361e513dSReid Spencer       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
2867391dde1SChris Lattner         Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
287361e513dSReid Spencer       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
288361e513dSReid Spencer     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
289361e513dSReid Spencer       std::vector<Constant*> Operands(CPS->getNumOperands());
290361e513dSReid Spencer       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
2917391dde1SChris Lattner         Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
292361e513dSReid Spencer       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
293361e513dSReid Spencer     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
294361e513dSReid Spencer       Result = const_cast<Constant*>(CPV);
295d84d35baSReid Spencer     } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
29693bde9cbSChris Lattner       std::vector<Constant*> Operands(CP->getNumOperands());
29793bde9cbSChris Lattner       for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
29893bde9cbSChris Lattner         Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
299d84d35baSReid Spencer       Result = ConstantVector::get(Operands);
300361e513dSReid Spencer     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
30119247f36SChris Lattner       std::vector<Constant*> Ops;
30219247f36SChris Lattner       for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
30319247f36SChris Lattner         Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
30419247f36SChris Lattner       Result = CE->getWithOperands(Ops);
305d3ba7d9bSReid Spencer     } else if (isa<GlobalValue>(CPV)) {
306d3ba7d9bSReid Spencer       assert(0 && "Unmapped global?");
307361e513dSReid Spencer     } else {
308361e513dSReid Spencer       assert(0 && "Unknown type of derived type constant value!");
309361e513dSReid Spencer     }
310c7745926SChris Lattner   } else if (isa<InlineAsm>(In)) {
311c7745926SChris Lattner     Result = const_cast<Value*>(In);
312c7745926SChris Lattner   }
313361e513dSReid Spencer 
314d3ba7d9bSReid Spencer   // Cache the mapping in our local map structure
315c7745926SChris Lattner   if (Result) {
31666a6271cSAnton Korobeynikov     ValueMap[In] = Result;
317361e513dSReid Spencer     return Result;
318361e513dSReid Spencer   }
319361e513dSReid Spencer 
32090246aa7SReid Spencer 
321f3baad3eSBill Wendling   cerr << "LinkModules ValueMap: \n";
3227391dde1SChris Lattner   PrintMap(ValueMap);
323361e513dSReid Spencer 
324f3baad3eSBill Wendling   cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
325361e513dSReid Spencer   assert(0 && "Couldn't remap value!");
326361e513dSReid Spencer   return 0;
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))) {
33890246aa7SReid Spencer     assert(ConflictGV->hasInternalLinkage() &&
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) {
367fc61de39SChris Lattner   assert((!Dest || !Src->hasInternalLinkage()) &&
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()) {
383e06036d2SAndrew Lenharth       //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();
400ce4396bcSDale Johannesen   } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
401ce4396bcSDale Johannesen              Src->hasCommonLinkage()) {
402ce4396bcSDale Johannesen     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
403ce4396bcSDale Johannesen     // or DLL* linkage.
404ce4396bcSDale Johannesen     if ((Dest->hasLinkOnceLinkage() &&
405ce4396bcSDale Johannesen           (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
40612c94949SAnton Korobeynikov         Dest->hasExternalWeakLinkage()) {
407fc61de39SChris Lattner       LinkFromSrc = true;
408fc61de39SChris Lattner       LT = Src->getLinkage();
409fc61de39SChris Lattner     } else {
410fc61de39SChris Lattner       LinkFromSrc = false;
411fc61de39SChris Lattner       LT = Dest->getLinkage();
412fc61de39SChris Lattner     }
413ce4396bcSDale Johannesen   } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
414ce4396bcSDale Johannesen              Dest->hasCommonLinkage()) {
41512c94949SAnton Korobeynikov     // At this point we know that Src has External* or DLL* linkage.
41612c94949SAnton Korobeynikov     if (Src->hasExternalWeakLinkage()) {
41712c94949SAnton Korobeynikov       LinkFromSrc = false;
41812c94949SAnton Korobeynikov       LT = Dest->getLinkage();
41912c94949SAnton Korobeynikov     } else {
420fc61de39SChris Lattner       LinkFromSrc = true;
421fc61de39SChris Lattner       LT = GlobalValue::ExternalLinkage;
42212c94949SAnton Korobeynikov     }
423fc61de39SChris Lattner   } else {
424d61d39ecSAnton Korobeynikov     assert((Dest->hasExternalLinkage() ||
425d61d39ecSAnton Korobeynikov             Dest->hasDLLImportLinkage() ||
42612c94949SAnton Korobeynikov             Dest->hasDLLExportLinkage() ||
42712c94949SAnton Korobeynikov             Dest->hasExternalWeakLinkage()) &&
428d61d39ecSAnton Korobeynikov            (Src->hasExternalLinkage() ||
429d61d39ecSAnton Korobeynikov             Src->hasDLLImportLinkage() ||
43012c94949SAnton Korobeynikov             Src->hasDLLExportLinkage() ||
43112c94949SAnton Korobeynikov             Src->hasExternalWeakLinkage()) &&
432fc61de39SChris Lattner            "Unexpected linkage type!");
433fc61de39SChris Lattner     return Error(Err, "Linking globals named '" + Src->getName() +
434fc61de39SChris Lattner                  "': symbol multiply defined!");
435fc61de39SChris Lattner   }
43631fc4f95SAnton Korobeynikov 
43731fc4f95SAnton Korobeynikov   // Check visibility
43831fc4f95SAnton Korobeynikov   if (Dest && Src->getVisibility() != Dest->getVisibility())
4391cc79985SChris Lattner     if (!Src->isDeclaration() && !Dest->isDeclaration())
44031fc4f95SAnton Korobeynikov       return Error(Err, "Linking globals named '" + Src->getName() +
44131fc4f95SAnton Korobeynikov                    "': symbols have different visibilities!");
442fc61de39SChris Lattner   return false;
443fc61de39SChris Lattner }
444361e513dSReid Spencer 
445361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge
446361e513dSReid Spencer // them into the dest module.
447f6439246SAnton Korobeynikov static bool LinkGlobals(Module *Dest, const Module *Src,
448361e513dSReid Spencer                         std::map<const Value*, Value*> &ValueMap,
449361e513dSReid Spencer                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
450361e513dSReid Spencer                         std::string *Err) {
451361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
452f6439246SAnton Korobeynikov   for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
45344ab8aefSChris Lattner        I != E; ++I) {
454f6439246SAnton Korobeynikov     const GlobalVariable *SGV = I;
455e79f4c77SAnton Korobeynikov     GlobalValue *DGV = 0;
456e79f4c77SAnton Korobeynikov 
457e79f4c77SAnton Korobeynikov     // Check to see if may have to link the global with the global
4583aaaa0b2SReid Spencer     if (SGV->hasName() && !SGV->hasInternalLinkage()) {
4593aaaa0b2SReid Spencer       DGV = Dest->getGlobalVariable(SGV->getName());
4603aaaa0b2SReid Spencer       if (DGV && DGV->getType() != SGV->getType())
461fc61de39SChris Lattner         // If types don't agree due to opaque types, try to resolve them.
4623aaaa0b2SReid Spencer         RecursiveResolveTypes(SGV->getType(), DGV->getType(),
463*e9bb8552SChris Lattner                               &Dest->getTypeSymbolTable());
464361e513dSReid Spencer     }
465361e513dSReid Spencer 
466e79f4c77SAnton Korobeynikov     // Check to see if may have to link the global with the alias
467715ef43cSAnton Korobeynikov     if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
468e79f4c77SAnton Korobeynikov       DGV = Dest->getNamedAlias(SGV->getName());
469e79f4c77SAnton Korobeynikov       if (DGV && DGV->getType() != SGV->getType())
470e79f4c77SAnton Korobeynikov         // If types don't agree due to opaque types, try to resolve them.
471e79f4c77SAnton Korobeynikov         RecursiveResolveTypes(SGV->getType(), DGV->getType(),
472*e9bb8552SChris Lattner                               &Dest->getTypeSymbolTable());
473e79f4c77SAnton Korobeynikov     }
474e79f4c77SAnton Korobeynikov 
475fc61de39SChris Lattner     if (DGV && DGV->hasInternalLinkage())
476fc61de39SChris Lattner       DGV = 0;
477fc61de39SChris Lattner 
4785e79a610SDan Gohman     assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
4795e79a610SDan Gohman             SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
480361e513dSReid Spencer            "Global must either be external or have an initializer!");
481361e513dSReid Spencer 
4821b9633d7SChris Lattner     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
4831b9633d7SChris Lattner     bool LinkFromSrc = false;
484fc61de39SChris Lattner     if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
485fc61de39SChris Lattner       return true;
486361e513dSReid Spencer 
487fc61de39SChris Lattner     if (!DGV) {
488361e513dSReid Spencer       // No linking to be performed, simply create an identical version of the
489361e513dSReid Spencer       // symbol over in the dest module... the initializer will be filled in
490361e513dSReid Spencer       // later by LinkGlobalInits...
491361e513dSReid Spencer       GlobalVariable *NewDGV =
492361e513dSReid Spencer         new GlobalVariable(SGV->getType()->getElementType(),
493361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
4940074ea3aSAnton Korobeynikov                            SGV->getName(), Dest);
4952dc36535SReid Spencer       // Propagate alignment, visibility and section info.
4963aaaa0b2SReid Spencer       CopyGVAttributes(NewDGV, SGV);
497dd924e4eSAndrew Lenharth 
498361e513dSReid Spencer       // If the LLVM runtime renamed the global, but it is an externally visible
499361e513dSReid Spencer       // symbol, DGV must be an existing global with internal linkage.  Rename
500361e513dSReid Spencer       // it.
501361e513dSReid Spencer       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
502361e513dSReid Spencer         ForceRenaming(NewDGV, SGV->getName());
503361e513dSReid Spencer 
504361e513dSReid Spencer       // Make sure to remember this mapping...
50566a6271cSAnton Korobeynikov       ValueMap[SGV] = NewDGV;
50666a6271cSAnton Korobeynikov 
507361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
508361e513dSReid Spencer         // Keep track that this is an appending variable...
509361e513dSReid Spencer         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
510fc61de39SChris Lattner     } else if (DGV->hasAppendingLinkage()) {
511361e513dSReid Spencer       // No linking is performed yet.  Just insert a new copy of the global, and
512361e513dSReid Spencer       // keep track of the fact that it is an appending variable in the
513361e513dSReid Spencer       // AppendingVars map.  The name is cleared out so that no linkage is
514361e513dSReid Spencer       // performed.
515361e513dSReid Spencer       GlobalVariable *NewDGV =
516361e513dSReid Spencer         new GlobalVariable(SGV->getType()->getElementType(),
517361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
5180074ea3aSAnton Korobeynikov                            "", Dest);
519361e513dSReid Spencer 
520e8a3e74bSAnton Korobeynikov       // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
5213aaaa0b2SReid Spencer       NewDGV->setAlignment(DGV->getAlignment());
522e8a3e74bSAnton Korobeynikov       // Propagate alignment, section and visibility info.
5233aaaa0b2SReid Spencer       CopyGVAttributes(NewDGV, SGV);
524dd924e4eSAndrew Lenharth 
525361e513dSReid Spencer       // Make sure to remember this mapping...
52666a6271cSAnton Korobeynikov       ValueMap[SGV] = NewDGV;
527361e513dSReid Spencer 
528361e513dSReid Spencer       // Keep track that this is an appending variable...
529361e513dSReid Spencer       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
530e79f4c77SAnton Korobeynikov     } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
531e79f4c77SAnton Korobeynikov       // SGV is global, but DGV is alias. The only valid mapping is when SGV is
532e79f4c77SAnton Korobeynikov       // external declaration, which is effectively a no-op. Also make sure
53366a6271cSAnton Korobeynikov       // linkage calculation was correct.
534e79f4c77SAnton Korobeynikov       if (SGV->isDeclaration() && !LinkFromSrc) {
535e79f4c77SAnton Korobeynikov         // Make sure to remember this mapping...
53666a6271cSAnton Korobeynikov         ValueMap[SGV] = DGA;
537e79f4c77SAnton Korobeynikov       } else
538eeb5ca6fSAnton Korobeynikov         return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
539eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
540e79f4c77SAnton Korobeynikov     } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
54166a6271cSAnton Korobeynikov       // Otherwise, perform the global-global mapping as instructed by
54266a6271cSAnton Korobeynikov       // GetLinkageResult.
543f6439246SAnton Korobeynikov       if (LinkFromSrc) {
5442dc36535SReid Spencer         // Propagate alignment, section, and visibility info.
545e79f4c77SAnton Korobeynikov         CopyGVAttributes(DGVar, SGV);
546dd924e4eSAndrew Lenharth 
5470074ea3aSAnton Korobeynikov         // If the types don't match, and if we are to link from the source, nuke
5480074ea3aSAnton Korobeynikov         // DGV and create a new one of the appropriate type.
549e79f4c77SAnton Korobeynikov         if (SGV->getType() != DGVar->getType()) {
550fc61de39SChris Lattner           GlobalVariable *NewDGV =
551fc61de39SChris Lattner             new GlobalVariable(SGV->getType()->getElementType(),
552e79f4c77SAnton Korobeynikov                                DGVar->isConstant(), DGVar->getLinkage(),
553e79f4c77SAnton Korobeynikov                                /*init*/0, DGVar->getName(), Dest);
554e79f4c77SAnton Korobeynikov           CopyGVAttributes(NewDGV, DGVar);
555f6439246SAnton Korobeynikov           DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
556e79f4c77SAnton Korobeynikov                                                            DGVar->getType()));
557e79f4c77SAnton Korobeynikov           // DGVar will conflict with NewDGV because they both had the same
558f6439246SAnton Korobeynikov           // name. We must erase this now so ForceRenaming doesn't assert
559f6439246SAnton Korobeynikov           // because DGV might not have internal linkage.
560e79f4c77SAnton Korobeynikov           DGVar->eraseFromParent();
561f6439246SAnton Korobeynikov 
562f6439246SAnton Korobeynikov           // If the symbol table renamed the global, but it is an externally
563f6439246SAnton Korobeynikov           // visible symbol, DGV must be an existing global with internal
564f6439246SAnton Korobeynikov           // linkage. Rename it.
565f6439246SAnton Korobeynikov           if (NewDGV->getName() != SGV->getName() &&
566f6439246SAnton Korobeynikov               !NewDGV->hasInternalLinkage())
567f6439246SAnton Korobeynikov             ForceRenaming(NewDGV, SGV->getName());
568f6439246SAnton Korobeynikov 
569e79f4c77SAnton Korobeynikov           DGVar = NewDGV;
570fc61de39SChris Lattner         }
571fc61de39SChris Lattner 
572fc61de39SChris Lattner         // Inherit const as appropriate
573e79f4c77SAnton Korobeynikov         DGVar->setConstant(SGV->isConstant());
574f6439246SAnton Korobeynikov 
575f6439246SAnton Korobeynikov         // Set initializer to zero, so we can link the stuff later
576e79f4c77SAnton Korobeynikov         DGVar->setInitializer(0);
577fc61de39SChris Lattner       } else {
578f6439246SAnton Korobeynikov         // Special case for const propagation
579e79f4c77SAnton Korobeynikov         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
580e79f4c77SAnton Korobeynikov           DGVar->setConstant(true);
581fc61de39SChris Lattner       }
582fc61de39SChris Lattner 
583f6439246SAnton Korobeynikov       // Set calculated linkage
584e79f4c77SAnton Korobeynikov       DGVar->setLinkage(NewLinkage);
585f6439246SAnton Korobeynikov 
586f6439246SAnton Korobeynikov       // Make sure to remember this mapping...
58766a6271cSAnton Korobeynikov       ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
588361e513dSReid Spencer     }
589361e513dSReid Spencer   }
590361e513dSReid Spencer   return false;
591361e513dSReid Spencer }
592361e513dSReid Spencer 
593dac5fa94SAnton Korobeynikov static GlobalValue::LinkageTypes
594dac5fa94SAnton Korobeynikov CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
595dac5fa94SAnton Korobeynikov   if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
596dac5fa94SAnton Korobeynikov     return GlobalValue::ExternalLinkage;
597dac5fa94SAnton Korobeynikov   else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
598dac5fa94SAnton Korobeynikov     return GlobalValue::WeakLinkage;
599dac5fa94SAnton Korobeynikov   else {
600dac5fa94SAnton Korobeynikov     assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
601dac5fa94SAnton Korobeynikov            "Unexpected linkage type");
602dac5fa94SAnton Korobeynikov     return GlobalValue::InternalLinkage;
603dac5fa94SAnton Korobeynikov   }
604dac5fa94SAnton Korobeynikov }
605dac5fa94SAnton Korobeynikov 
606b00c9c0dSLauro Ramos Venancio // LinkAlias - Loop through the alias in the src module and link them into the
607dac5fa94SAnton Korobeynikov // dest module. We're assuming, that all functions/global variables were already
608dac5fa94SAnton Korobeynikov // linked in.
6092e13597fSAnton Korobeynikov static bool LinkAlias(Module *Dest, const Module *Src,
6102e13597fSAnton Korobeynikov                       std::map<const Value*, Value*> &ValueMap,
6112e13597fSAnton Korobeynikov                       std::string *Err) {
612b00c9c0dSLauro Ramos Venancio   // Loop over all alias in the src module
613b00c9c0dSLauro Ramos Venancio   for (Module::const_alias_iterator I = Src->alias_begin(),
614b00c9c0dSLauro Ramos Venancio          E = Src->alias_end(); I != E; ++I) {
615dac5fa94SAnton Korobeynikov     const GlobalAlias *SGA = I;
616dac5fa94SAnton Korobeynikov     const GlobalValue *SAliasee = SGA->getAliasedGlobal();
617dac5fa94SAnton Korobeynikov     GlobalAlias *NewGA = NULL;
618b00c9c0dSLauro Ramos Venancio 
619dac5fa94SAnton Korobeynikov     // Globals were already linked, thus we can just query ValueMap for variant
620acbdaa24SAnton Korobeynikov     // of SAliasee in Dest.
621d48ed17dSTed Kremenek     std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
622d48ed17dSTed Kremenek     assert(VMI != ValueMap.end() && "Aliasee not linked");
623d48ed17dSTed Kremenek     GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
624acbdaa24SAnton Korobeynikov     GlobalValue* DGV = NULL;
625b00c9c0dSLauro Ramos Venancio 
626dac5fa94SAnton Korobeynikov     // Try to find something 'similar' to SGA in destination module.
627acbdaa24SAnton Korobeynikov     if (!DGV && !SGA->hasInternalLinkage()) {
628acbdaa24SAnton Korobeynikov       DGV = Dest->getNamedAlias(SGA->getName());
629acbdaa24SAnton Korobeynikov 
630dac5fa94SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
631acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
632acbdaa24SAnton Korobeynikov         if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
633*e9bb8552SChris Lattner                                   &Dest->getTypeSymbolTable()))
634eeb5ca6fSAnton Korobeynikov           return Error(Err, "Alias Collision on '" + SGA->getName()+
635eeb5ca6fSAnton Korobeynikov                        "': aliases have different types");
636acbdaa24SAnton Korobeynikov     }
6372e13597fSAnton Korobeynikov 
638acbdaa24SAnton Korobeynikov     if (!DGV && !SGA->hasInternalLinkage()) {
639acbdaa24SAnton Korobeynikov       DGV = Dest->getGlobalVariable(SGA->getName());
640acbdaa24SAnton Korobeynikov 
641acbdaa24SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
642acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
643acbdaa24SAnton Korobeynikov         if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
644*e9bb8552SChris Lattner                                   &Dest->getTypeSymbolTable()))
645acbdaa24SAnton Korobeynikov           return Error(Err, "Alias Collision on '" + SGA->getName()+
646acbdaa24SAnton Korobeynikov                        "': aliases have different types");
647acbdaa24SAnton Korobeynikov     }
648acbdaa24SAnton Korobeynikov 
649acbdaa24SAnton Korobeynikov     if (!DGV && !SGA->hasInternalLinkage()) {
650acbdaa24SAnton Korobeynikov       DGV = Dest->getFunction(SGA->getName());
651acbdaa24SAnton Korobeynikov 
652acbdaa24SAnton Korobeynikov       // If types don't agree due to opaque types, try to resolve them.
653acbdaa24SAnton Korobeynikov       if (DGV && DGV->getType() != SGA->getType())
654acbdaa24SAnton Korobeynikov         if (RecursiveResolveTypes(SGA->getType(), DGV->getType(),
655*e9bb8552SChris Lattner                                   &Dest->getTypeSymbolTable()))
656acbdaa24SAnton Korobeynikov           return Error(Err, "Alias Collision on '" + SGA->getName()+
657acbdaa24SAnton Korobeynikov                        "': aliases have different types");
658acbdaa24SAnton Korobeynikov     }
659acbdaa24SAnton Korobeynikov 
660acbdaa24SAnton Korobeynikov     // No linking to be performed on internal stuff.
661acbdaa24SAnton Korobeynikov     if (DGV && DGV->hasInternalLinkage())
662acbdaa24SAnton Korobeynikov       DGV = NULL;
663acbdaa24SAnton Korobeynikov 
664acbdaa24SAnton Korobeynikov     if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
665acbdaa24SAnton Korobeynikov       // Types are known to be the same, check whether aliasees equal. As
666dac5fa94SAnton Korobeynikov       // globals are already linked we just need query ValueMap to find the
667dac5fa94SAnton Korobeynikov       // mapping.
668dac5fa94SAnton Korobeynikov       if (DAliasee == DGA->getAliasedGlobal()) {
669dac5fa94SAnton Korobeynikov         // This is just two copies of the same alias. Propagate linkage, if
670dac5fa94SAnton Korobeynikov         // necessary.
671dac5fa94SAnton Korobeynikov         DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
672dac5fa94SAnton Korobeynikov 
673dac5fa94SAnton Korobeynikov         NewGA = DGA;
674dac5fa94SAnton Korobeynikov         // Proceed to 'common' steps
675dac5fa94SAnton Korobeynikov       } else
676eeb5ca6fSAnton Korobeynikov         return Error(Err, "Alias Collision on '"  + SGA->getName()+
677eeb5ca6fSAnton Korobeynikov                      "': aliases have different aliasees");
678acbdaa24SAnton Korobeynikov     } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
679dac5fa94SAnton Korobeynikov       // The only allowed way is to link alias with external declaration.
680acbdaa24SAnton Korobeynikov       if (DGVar->isDeclaration()) {
681510fc32dSAnton Korobeynikov         // But only if aliasee is global too...
682510fc32dSAnton Korobeynikov         if (!isa<GlobalVariable>(DAliasee))
683510fc32dSAnton Korobeynikov           return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
684510fc32dSAnton Korobeynikov                        "': aliasee is not global variable");
685510fc32dSAnton Korobeynikov 
686dac5fa94SAnton Korobeynikov         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
687dac5fa94SAnton Korobeynikov                                 SGA->getName(), DAliasee, Dest);
688dac5fa94SAnton Korobeynikov         CopyGVAttributes(NewGA, SGA);
689dac5fa94SAnton Korobeynikov 
690dac5fa94SAnton Korobeynikov         // Any uses of DGV need to change to NewGA, with cast, if needed.
691acbdaa24SAnton Korobeynikov         if (SGA->getType() != DGVar->getType())
692acbdaa24SAnton Korobeynikov           DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
693acbdaa24SAnton Korobeynikov                                                              DGVar->getType()));
694dac5fa94SAnton Korobeynikov         else
695acbdaa24SAnton Korobeynikov           DGVar->replaceAllUsesWith(NewGA);
696dac5fa94SAnton Korobeynikov 
697acbdaa24SAnton Korobeynikov         // DGVar will conflict with NewGA because they both had the same
698dac5fa94SAnton Korobeynikov         // name. We must erase this now so ForceRenaming doesn't assert
699dac5fa94SAnton Korobeynikov         // because DGV might not have internal linkage.
700acbdaa24SAnton Korobeynikov         DGVar->eraseFromParent();
701dac5fa94SAnton Korobeynikov 
702dac5fa94SAnton Korobeynikov         // Proceed to 'common' steps
703dac5fa94SAnton Korobeynikov       } else
704eeb5ca6fSAnton Korobeynikov         return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
705eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
706acbdaa24SAnton Korobeynikov     } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
70724f65c3aSAnton Korobeynikov       // The only allowed way is to link alias with external declaration.
70824f65c3aSAnton Korobeynikov       if (DF->isDeclaration()) {
709510fc32dSAnton Korobeynikov         // But only if aliasee is function too...
710510fc32dSAnton Korobeynikov         if (!isa<Function>(DAliasee))
711510fc32dSAnton Korobeynikov           return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
712510fc32dSAnton Korobeynikov                        "': aliasee is not function");
713510fc32dSAnton Korobeynikov 
71424f65c3aSAnton Korobeynikov         NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
71524f65c3aSAnton Korobeynikov                                 SGA->getName(), DAliasee, Dest);
71624f65c3aSAnton Korobeynikov         CopyGVAttributes(NewGA, SGA);
71724f65c3aSAnton Korobeynikov 
71824f65c3aSAnton Korobeynikov         // Any uses of DF need to change to NewGA, with cast, if needed.
71924f65c3aSAnton Korobeynikov         if (SGA->getType() != DF->getType())
72024f65c3aSAnton Korobeynikov           DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
72124f65c3aSAnton Korobeynikov                                                           DF->getType()));
72224f65c3aSAnton Korobeynikov         else
72324f65c3aSAnton Korobeynikov           DF->replaceAllUsesWith(NewGA);
72424f65c3aSAnton Korobeynikov 
72524f65c3aSAnton Korobeynikov         // DF will conflict with NewGA because they both had the same
72624f65c3aSAnton Korobeynikov         // name. We must erase this now so ForceRenaming doesn't assert
72724f65c3aSAnton Korobeynikov         // because DF might not have internal linkage.
72824f65c3aSAnton Korobeynikov         DF->eraseFromParent();
72924f65c3aSAnton Korobeynikov 
73024f65c3aSAnton Korobeynikov         // Proceed to 'common' steps
73124f65c3aSAnton Korobeynikov       } else
732eeb5ca6fSAnton Korobeynikov         return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
733eeb5ca6fSAnton Korobeynikov                      "': symbol multiple defined");
734dac5fa94SAnton Korobeynikov     } else {
735acbdaa24SAnton Korobeynikov       // No linking to be performed, simply create an identical version of the
736acbdaa24SAnton Korobeynikov       // alias over in the dest module...
737dac5fa94SAnton Korobeynikov 
738dac5fa94SAnton Korobeynikov       NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
739dac5fa94SAnton Korobeynikov                               SGA->getName(), DAliasee, Dest);
740dac5fa94SAnton Korobeynikov       CopyGVAttributes(NewGA, SGA);
741dac5fa94SAnton Korobeynikov 
742dac5fa94SAnton Korobeynikov       // Proceed to 'common' steps
743b00c9c0dSLauro Ramos Venancio     }
744dac5fa94SAnton Korobeynikov 
745dac5fa94SAnton Korobeynikov     assert(NewGA && "No alias was created in destination module!");
746dac5fa94SAnton Korobeynikov 
747d5160da5SAnton Korobeynikov     // If the symbol table renamed the alias, but it is an externally visible
748acbdaa24SAnton Korobeynikov     // symbol, DGA must be an global value with internal linkage. Rename it.
749dac5fa94SAnton Korobeynikov     if (NewGA->getName() != SGA->getName() &&
750dac5fa94SAnton Korobeynikov         !NewGA->hasInternalLinkage())
751dac5fa94SAnton Korobeynikov       ForceRenaming(NewGA, SGA->getName());
752dac5fa94SAnton Korobeynikov 
753dac5fa94SAnton Korobeynikov     // Remember this mapping so uses in the source module get remapped
754dac5fa94SAnton Korobeynikov     // later by RemapOperand.
75566a6271cSAnton Korobeynikov     ValueMap[SGA] = NewGA;
756dac5fa94SAnton Korobeynikov   }
757dac5fa94SAnton Korobeynikov 
758b00c9c0dSLauro Ramos Venancio   return false;
759b00c9c0dSLauro Ramos Venancio }
760b00c9c0dSLauro Ramos Venancio 
761361e513dSReid Spencer 
762361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all
763361e513dSReid Spencer // globals that may be referenced are in Dest.
764361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src,
765361e513dSReid Spencer                             std::map<const Value*, Value*> &ValueMap,
766361e513dSReid Spencer                             std::string *Err) {
767361e513dSReid Spencer 
768361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
76944ab8aefSChris Lattner   for (Module::const_global_iterator I = Src->global_begin(),
77044ab8aefSChris Lattner        E = Src->global_end(); I != E; ++I) {
771361e513dSReid Spencer     const GlobalVariable *SGV = I;
772361e513dSReid Spencer 
773361e513dSReid Spencer     if (SGV->hasInitializer()) {      // Only process initialized GV's
774361e513dSReid Spencer       // Figure out what the initializer looks like in the dest module...
775361e513dSReid Spencer       Constant *SInit =
7767391dde1SChris Lattner         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
777361e513dSReid Spencer 
778fc2edad4SAnton Korobeynikov       GlobalVariable *DGV =
779fc2edad4SAnton Korobeynikov         cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
780361e513dSReid Spencer       if (DGV->hasInitializer()) {
781361e513dSReid Spencer         if (SGV->hasExternalLinkage()) {
782361e513dSReid Spencer           if (DGV->getInitializer() != SInit)
783eeb5ca6fSAnton Korobeynikov             return Error(Err, "Global Variable Collision on '" + SGV->getName() +
784eeb5ca6fSAnton Korobeynikov                          "': global variables have different initializers");
785ce4396bcSDale Johannesen         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
786ce4396bcSDale Johannesen                    DGV->hasCommonLinkage()) {
787361e513dSReid Spencer           // Nothing is required, mapped values will take the new global
788361e513dSReid Spencer           // automatically.
789ce4396bcSDale Johannesen         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
790ce4396bcSDale Johannesen                    SGV->hasCommonLinkage()) {
791361e513dSReid Spencer           // Nothing is required, mapped values will take the new global
792361e513dSReid Spencer           // automatically.
793361e513dSReid Spencer         } else if (DGV->hasAppendingLinkage()) {
794361e513dSReid Spencer           assert(0 && "Appending linkage unimplemented!");
795361e513dSReid Spencer         } else {
796361e513dSReid Spencer           assert(0 && "Unknown linkage!");
797361e513dSReid Spencer         }
798361e513dSReid Spencer       } else {
799361e513dSReid Spencer         // Copy the initializer over now...
800361e513dSReid Spencer         DGV->setInitializer(SInit);
801361e513dSReid Spencer       }
802361e513dSReid Spencer     }
803361e513dSReid Spencer   }
804361e513dSReid Spencer   return false;
805361e513dSReid Spencer }
806361e513dSReid Spencer 
807361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules,
808361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes
809361e513dSReid Spencer // to the Dest function...
810361e513dSReid Spencer //
811361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src,
812361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
813361e513dSReid Spencer                                std::string *Err) {
814d3ba7d9bSReid Spencer   // Loop over all of the functions in the src module, mapping them over
815361e513dSReid Spencer   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
816361e513dSReid Spencer     const Function *SF = I;   // SrcFunction
817228a5f18SChris Lattner 
818361e513dSReid Spencer     Function *DF = 0;
819228a5f18SChris Lattner 
820228a5f18SChris Lattner     // If this function is internal or has no name, it doesn't participate in
821228a5f18SChris Lattner     // linkage.
82290246aa7SReid Spencer     if (SF->hasName() && !SF->hasInternalLinkage()) {
82390246aa7SReid Spencer       // Check to see if may have to link the function.
8243aaaa0b2SReid Spencer       DF = Dest->getFunction(SF->getName());
825228a5f18SChris Lattner       if (DF && DF->hasInternalLinkage())
826228a5f18SChris Lattner         DF = 0;
827361e513dSReid Spencer     }
828361e513dSReid Spencer 
829228a5f18SChris Lattner     // If there is no linkage to be performed, just bring over SF without
830228a5f18SChris Lattner     // modifying it.
831228a5f18SChris Lattner     if (DF == 0) {
832228a5f18SChris Lattner       // Function does not already exist, simply insert an function signature
833228a5f18SChris Lattner       // identical to SF into the dest module.
834228a5f18SChris Lattner       Function *NewDF = Function::Create(SF->getFunctionType(),
835228a5f18SChris Lattner                                          SF->getLinkage(),
836228a5f18SChris Lattner                                          SF->getName(), Dest);
837228a5f18SChris Lattner       CopyGVAttributes(NewDF, SF);
838ec7441b3SChris Lattner 
839228a5f18SChris Lattner       // If the LLVM runtime renamed the function, but it is an externally
840228a5f18SChris Lattner       // visible symbol, DF must be an existing function with internal linkage.
841228a5f18SChris Lattner       // Rename it.
842228a5f18SChris Lattner       if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
843228a5f18SChris Lattner         ForceRenaming(NewDF, SF->getName());
844228a5f18SChris Lattner 
845228a5f18SChris Lattner       // ... and remember this mapping...
846228a5f18SChris Lattner       ValueMap[SF] = NewDF;
847228a5f18SChris Lattner       continue;
848228a5f18SChris Lattner     }
849228a5f18SChris Lattner 
850228a5f18SChris Lattner 
851228a5f18SChris Lattner     // If types don't agree because of opaque, try to resolve them.
852228a5f18SChris Lattner     if (SF->getType() != DF->getType())
853228a5f18SChris Lattner       RecursiveResolveTypes(SF->getType(), DF->getType(),
854*e9bb8552SChris Lattner                             &Dest->getTypeSymbolTable());
855228a5f18SChris Lattner 
856228a5f18SChris Lattner     // Check visibility, merging if a definition overrides a prototype.
857228a5f18SChris Lattner     if (SF->getVisibility() != DF->getVisibility()) {
8581cc79985SChris Lattner       // If one is a prototype, ignore its visibility.  Prototypes are always
8591cc79985SChris Lattner       // overridden by the definition.
8601cc79985SChris Lattner       if (!SF->isDeclaration() && !DF->isDeclaration())
86131fc4f95SAnton Korobeynikov         return Error(Err, "Linking functions named '" + SF->getName() +
86231fc4f95SAnton Korobeynikov                      "': symbols have different visibilities!");
86331fc4f95SAnton Korobeynikov 
864ec7441b3SChris Lattner       // Otherwise, replace the visibility of DF if DF is a prototype.
865ec7441b3SChris Lattner       if (DF->isDeclaration())
866ec7441b3SChris Lattner         DF->setVisibility(SF->getVisibility());
867ec7441b3SChris Lattner     }
8684f00f531SAnton Korobeynikov 
869228a5f18SChris Lattner     if (DF->getType() != SF->getType()) {
8703aaaa0b2SReid Spencer       if (DF->isDeclaration() && !SF->isDeclaration()) {
8713aaaa0b2SReid Spencer         // We have a definition of the same name but different type in the
8723aaaa0b2SReid Spencer         // source module. Copy the prototype to the destination and replace
8733aaaa0b2SReid Spencer         // uses of the destination's prototype with the new prototype.
874697e94ccSGabor Greif         Function *NewDF = Function::Create(SF->getFunctionType(),
875697e94ccSGabor Greif                                            SF->getLinkage(),
8763aaaa0b2SReid Spencer                                            SF->getName(), Dest);
8773aaaa0b2SReid Spencer         CopyGVAttributes(NewDF, SF);
8783aaaa0b2SReid Spencer 
8793aaaa0b2SReid Spencer         // Any uses of DF need to change to NewDF, with cast
8803aaaa0b2SReid Spencer         DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
8813aaaa0b2SReid Spencer 
8823aaaa0b2SReid Spencer         // DF will conflict with NewDF because they both had the same. We must
8833aaaa0b2SReid Spencer         // erase this now so ForceRenaming doesn't assert because DF might
8843aaaa0b2SReid Spencer         // not have internal linkage.
8853aaaa0b2SReid Spencer         DF->eraseFromParent();
8863aaaa0b2SReid Spencer 
8873aaaa0b2SReid Spencer         // If the symbol table renamed the function, but it is an externally
8883aaaa0b2SReid Spencer         // visible symbol, DF must be an existing function with internal
8893aaaa0b2SReid Spencer         // linkage.  Rename it.
8903aaaa0b2SReid Spencer         if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
8913aaaa0b2SReid Spencer           ForceRenaming(NewDF, SF->getName());
8923aaaa0b2SReid Spencer 
8933aaaa0b2SReid Spencer         // Remember this mapping so uses in the source module get remapped
8943aaaa0b2SReid Spencer         // later by RemapOperand.
8953aaaa0b2SReid Spencer         ValueMap[SF] = NewDF;
8963aaaa0b2SReid Spencer       } else if (SF->isDeclaration()) {
8973aaaa0b2SReid Spencer         // We have two functions of the same name but different type and the
8983aaaa0b2SReid Spencer         // source is a declaration while the destination is not. Any use of
8993aaaa0b2SReid Spencer         // the source must be mapped to the destination, with a cast.
9003aaaa0b2SReid Spencer         ValueMap[SF] = ConstantExpr::getBitCast(DF, SF->getType());
9013aaaa0b2SReid Spencer       } else {
9023aaaa0b2SReid Spencer         // We have two functions of the same name but different types and they
9033aaaa0b2SReid Spencer         // are both definitions. This is an error.
9043aaaa0b2SReid Spencer         return Error(Err, "Function '" + DF->getName() + "' defined as both '" +
9053aaaa0b2SReid Spencer                      ToStr(SF->getFunctionType(), Src) + "' and '" +
9063aaaa0b2SReid Spencer                      ToStr(DF->getFunctionType(), Dest) + "'");
9073aaaa0b2SReid Spencer       }
908228a5f18SChris Lattner       continue;
909228a5f18SChris Lattner     }
910361e513dSReid Spencer 
911228a5f18SChris Lattner     if (SF->isDeclaration()) {
9123aaaa0b2SReid Spencer       // If SF is a declaration or if both SF & DF are declarations, just link
9133aaaa0b2SReid Spencer       // the declarations, we aren't adding anything.
914d61d39ecSAnton Korobeynikov       if (SF->hasDLLImportLinkage()) {
9155301e7c6SReid Spencer         if (DF->isDeclaration()) {
91677e8ac4dSChris Lattner           ValueMap[SF] = DF;
917d61d39ecSAnton Korobeynikov           DF->setLinkage(SF->getLinkage());
918d61d39ecSAnton Korobeynikov         }
919d61d39ecSAnton Korobeynikov       } else {
92066a6271cSAnton Korobeynikov         ValueMap[SF] = DF;
921d61d39ecSAnton Korobeynikov       }
92277e8ac4dSChris Lattner       continue;
92377e8ac4dSChris Lattner     }
92477e8ac4dSChris Lattner 
92577e8ac4dSChris Lattner     // If DF is external but SF is not, link the external functions, update
92677e8ac4dSChris Lattner     // linkage qualifiers.
92777e8ac4dSChris Lattner     if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
928361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
929361e513dSReid Spencer       DF->setLinkage(SF->getLinkage());
93077e8ac4dSChris Lattner       continue;
93177e8ac4dSChris Lattner     }
93277e8ac4dSChris Lattner 
93312c94949SAnton Korobeynikov     // At this point we know that DF has LinkOnce, Weak, or External* linkage.
93477e8ac4dSChris Lattner     if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
93577e8ac4dSChris Lattner         SF->hasCommonLinkage()) {
93666a6271cSAnton Korobeynikov       ValueMap[SF] = DF;
937361e513dSReid Spencer 
938361e513dSReid Spencer       // Linkonce+Weak = Weak
93912c94949SAnton Korobeynikov       // *+External Weak = *
940ce4396bcSDale Johannesen       if ((DF->hasLinkOnceLinkage() &&
941ce4396bcSDale Johannesen               (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
94212c94949SAnton Korobeynikov           DF->hasExternalWeakLinkage())
943361e513dSReid Spencer         DF->setLinkage(SF->getLinkage());
94477e8ac4dSChris Lattner       continue;
94577e8ac4dSChris Lattner     }
94677e8ac4dSChris Lattner 
94777e8ac4dSChris Lattner     if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
948ce4396bcSDale Johannesen         DF->hasCommonLinkage()) {
94912c94949SAnton Korobeynikov       // At this point we know that SF has LinkOnce or External* linkage.
95066a6271cSAnton Korobeynikov       ValueMap[SF] = DF;
95177e8ac4dSChris Lattner 
95277e8ac4dSChris Lattner       // If the source function has stronger linkage than the destination,
95377e8ac4dSChris Lattner       // its body and linkage should override ours.
95477e8ac4dSChris Lattner       if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
95577e8ac4dSChris Lattner         // Don't inherit linkonce & external weak linkage.
956361e513dSReid Spencer         DF->setLinkage(SF->getLinkage());
95777e8ac4dSChris Lattner         DF->deleteBody();
95877e8ac4dSChris Lattner       }
95977e8ac4dSChris Lattner       continue;
96077e8ac4dSChris Lattner     }
96177e8ac4dSChris Lattner 
96277e8ac4dSChris Lattner     if (SF->getLinkage() != DF->getLinkage())
963361e513dSReid Spencer       return Error(Err, "Functions named '" + SF->getName() +
964361e513dSReid Spencer                    "' have different linkage specifiers!");
96577e8ac4dSChris Lattner 
96677e8ac4dSChris Lattner     // The function is defined identically in both modules!
96777e8ac4dSChris Lattner     if (SF->hasExternalLinkage())
968361e513dSReid Spencer       return Error(Err, "Function '" +
969361e513dSReid Spencer                    ToStr(SF->getFunctionType(), Src) + "':\"" +
970361e513dSReid Spencer                    SF->getName() + "\" - Function is already defined!");
971361e513dSReid Spencer     assert(0 && "Unknown linkage configuration found!");
972361e513dSReid Spencer   }
973361e513dSReid Spencer   return false;
974361e513dSReid Spencer }
975361e513dSReid Spencer 
976361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and
977361e513dSReid Spencer // fix up references to values.  At this point we know that Dest is an external
978361e513dSReid Spencer // function, and that Src is not.
9792f0557d0SChris Lattner static bool LinkFunctionBody(Function *Dest, Function *Src,
9803aaaa0b2SReid Spencer                              std::map<const Value*, Value*> &ValueMap,
981361e513dSReid Spencer                              std::string *Err) {
9825301e7c6SReid Spencer   assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
983361e513dSReid Spencer 
9847391dde1SChris Lattner   // Go through and convert function arguments over, remembering the mapping.
985531f9e92SChris Lattner   Function::arg_iterator DI = Dest->arg_begin();
986531f9e92SChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
987361e513dSReid Spencer        I != E; ++I, ++DI) {
9887629b71dSOwen Anderson     DI->setName(I->getName());  // Copy the name information over...
989361e513dSReid Spencer 
990361e513dSReid Spencer     // Add a mapping to our local map
99166a6271cSAnton Korobeynikov     ValueMap[I] = DI;
992361e513dSReid Spencer   }
993361e513dSReid Spencer 
9942f0557d0SChris Lattner   // Splice the body of the source function into the dest function.
9952f0557d0SChris Lattner   Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
996361e513dSReid Spencer 
997361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
998361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
999361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
1000361e513dSReid Spencer   // functions and patch them up to point to the local versions...
1001361e513dSReid Spencer   //
1002361e513dSReid Spencer   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1003361e513dSReid Spencer     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1004361e513dSReid Spencer       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1005361e513dSReid Spencer            OI != OE; ++OI)
10062f0557d0SChris Lattner         if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
10073aaaa0b2SReid Spencer           *OI = RemapOperand(*OI, ValueMap);
10087391dde1SChris Lattner 
10097391dde1SChris Lattner   // There is no need to map the arguments anymore.
101044ab8aefSChris Lattner   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
101144ab8aefSChris Lattner        I != E; ++I)
10123aaaa0b2SReid Spencer     ValueMap.erase(I);
1013361e513dSReid Spencer 
1014361e513dSReid Spencer   return false;
1015361e513dSReid Spencer }
1016361e513dSReid Spencer 
1017361e513dSReid Spencer 
1018361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the
1019361e513dSReid Spencer // source module into the DestModule.  This consists basically of copying the
1020361e513dSReid Spencer // function over and fixing up references to values.
10212f0557d0SChris Lattner static bool LinkFunctionBodies(Module *Dest, Module *Src,
1022361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
1023361e513dSReid Spencer                                std::string *Err) {
1024361e513dSReid Spencer 
102590246aa7SReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
102690246aa7SReid Spencer   // go
10272f0557d0SChris Lattner   for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
10285301e7c6SReid Spencer     if (!SF->isDeclaration()) {               // No body if function is external
1029361e513dSReid Spencer       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
1030361e513dSReid Spencer 
1031361e513dSReid Spencer       // DF not external SF external?
10323aaaa0b2SReid Spencer       if (DF->isDeclaration())
1033361e513dSReid Spencer         // Only provide the function body if there isn't one already.
1034361e513dSReid Spencer         if (LinkFunctionBody(DF, SF, ValueMap, Err))
1035361e513dSReid Spencer           return true;
103690246aa7SReid Spencer     }
1037361e513dSReid Spencer   }
1038361e513dSReid Spencer   return false;
1039361e513dSReid Spencer }
1040361e513dSReid Spencer 
1041361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them
1042361e513dSReid Spencer // together now.  Return true on error.
1043361e513dSReid Spencer static bool LinkAppendingVars(Module *M,
1044361e513dSReid Spencer                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
1045361e513dSReid Spencer                               std::string *ErrorMsg) {
1046361e513dSReid Spencer   if (AppendingVars.empty()) return false; // Nothing to do.
1047361e513dSReid Spencer 
1048361e513dSReid Spencer   // Loop over the multimap of appending vars, processing any variables with the
1049361e513dSReid Spencer   // same name, forming a new appending global variable with both of the
1050361e513dSReid Spencer   // initializers merged together, then rewrite references to the old variables
1051361e513dSReid Spencer   // and delete them.
1052361e513dSReid Spencer   std::vector<Constant*> Inits;
1053361e513dSReid Spencer   while (AppendingVars.size() > 1) {
1054361e513dSReid Spencer     // Get the first two elements in the map...
1055361e513dSReid Spencer     std::multimap<std::string,
1056361e513dSReid Spencer       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1057361e513dSReid Spencer 
1058361e513dSReid Spencer     // If the first two elements are for different names, there is no pair...
1059361e513dSReid Spencer     // Otherwise there is a pair, so link them together...
1060361e513dSReid Spencer     if (First->first == Second->first) {
1061361e513dSReid Spencer       GlobalVariable *G1 = First->second, *G2 = Second->second;
1062361e513dSReid Spencer       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1063361e513dSReid Spencer       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1064361e513dSReid Spencer 
1065361e513dSReid Spencer       // Check to see that they two arrays agree on type...
1066361e513dSReid Spencer       if (T1->getElementType() != T2->getElementType())
1067361e513dSReid Spencer         return Error(ErrorMsg,
1068361e513dSReid Spencer          "Appending variables with different element types need to be linked!");
1069361e513dSReid Spencer       if (G1->isConstant() != G2->isConstant())
1070361e513dSReid Spencer         return Error(ErrorMsg,
1071361e513dSReid Spencer                      "Appending variables linked with different const'ness!");
1072361e513dSReid Spencer 
107385703e37SLauro Ramos Venancio       if (G1->getAlignment() != G2->getAlignment())
107485703e37SLauro Ramos Venancio         return Error(ErrorMsg,
107585703e37SLauro Ramos Venancio          "Appending variables with different alignment need to be linked!");
107685703e37SLauro Ramos Venancio 
107785703e37SLauro Ramos Venancio       if (G1->getVisibility() != G2->getVisibility())
107885703e37SLauro Ramos Venancio         return Error(ErrorMsg,
107985703e37SLauro Ramos Venancio          "Appending variables with different visibility need to be linked!");
108085703e37SLauro Ramos Venancio 
108185703e37SLauro Ramos Venancio       if (G1->getSection() != G2->getSection())
108285703e37SLauro Ramos Venancio         return Error(ErrorMsg,
108385703e37SLauro Ramos Venancio          "Appending variables with different section name need to be linked!");
108485703e37SLauro Ramos Venancio 
1085361e513dSReid Spencer       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1086361e513dSReid Spencer       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1087361e513dSReid Spencer 
1088d490d4f0SChris Lattner       G1->setName("");   // Clear G1's name in case of a conflict!
1089d490d4f0SChris Lattner 
1090361e513dSReid Spencer       // Create the new global variable...
1091361e513dSReid Spencer       GlobalVariable *NG =
1092361e513dSReid Spencer         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1093749e4668SLauro Ramos Venancio                            /*init*/0, First->first, M, G1->isThreadLocal());
1094361e513dSReid Spencer 
109585703e37SLauro Ramos Venancio       // Propagate alignment, visibility and section info.
109685703e37SLauro Ramos Venancio       CopyGVAttributes(NG, G1);
109785703e37SLauro Ramos Venancio 
1098361e513dSReid Spencer       // Merge the initializer...
1099361e513dSReid Spencer       Inits.reserve(NewSize);
1100361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1101361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1102361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
1103361e513dSReid Spencer       } else {
1104361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1105361e513dSReid Spencer         Constant *CV = Constant::getNullValue(T1->getElementType());
1106361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1107361e513dSReid Spencer           Inits.push_back(CV);
1108361e513dSReid Spencer       }
1109361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1110361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1111361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
1112361e513dSReid Spencer       } else {
1113361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1114361e513dSReid Spencer         Constant *CV = Constant::getNullValue(T2->getElementType());
1115361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1116361e513dSReid Spencer           Inits.push_back(CV);
1117361e513dSReid Spencer       }
1118361e513dSReid Spencer       NG->setInitializer(ConstantArray::get(NewType, Inits));
1119361e513dSReid Spencer       Inits.clear();
1120361e513dSReid Spencer 
1121361e513dSReid Spencer       // Replace any uses of the two global variables with uses of the new
1122361e513dSReid Spencer       // global...
1123361e513dSReid Spencer 
1124361e513dSReid Spencer       // FIXME: This should rewrite simple/straight-forward uses such as
1125361e513dSReid Spencer       // getelementptr instructions to not use the Cast!
1126b341b086SReid Spencer       G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1127b341b086SReid Spencer       G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
1128361e513dSReid Spencer 
1129361e513dSReid Spencer       // Remove the two globals from the module now...
1130361e513dSReid Spencer       M->getGlobalList().erase(G1);
1131361e513dSReid Spencer       M->getGlobalList().erase(G2);
1132361e513dSReid Spencer 
1133361e513dSReid Spencer       // Put the new global into the AppendingVars map so that we can handle
1134361e513dSReid Spencer       // linking of more than two vars...
1135361e513dSReid Spencer       Second->second = NG;
1136361e513dSReid Spencer     }
1137361e513dSReid Spencer     AppendingVars.erase(First);
1138361e513dSReid Spencer   }
1139361e513dSReid Spencer 
1140361e513dSReid Spencer   return false;
1141361e513dSReid Spencer }
1142361e513dSReid Spencer 
11432609888fSAnton Korobeynikov static bool ResolveAliases(Module *Dest) {
11442609888fSAnton Korobeynikov   for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1145e6d90f5aSAnton Korobeynikov        I != E; ++I)
1146e6d90f5aSAnton Korobeynikov     if (const GlobalValue *GV = I->resolveAliasedGlobal())
11472609888fSAnton Korobeynikov       if (!GV->isDeclaration())
1148e6d90f5aSAnton Korobeynikov         I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
11492609888fSAnton Korobeynikov 
11502609888fSAnton Korobeynikov   return false;
11512609888fSAnton Korobeynikov }
1152361e513dSReid Spencer 
1153361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting
1154361e513dSReid Spencer // left module modified to be the composite of the two input modules.  If an
1155361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1156361e513dSReid Spencer // the problem.  Upon failure, the Dest module could be in a modified state, and
1157361e513dSReid Spencer // shouldn't be relied on to be consistent.
1158c4e31534SReid Spencer bool
1159c4e31534SReid Spencer Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1160361e513dSReid Spencer   assert(Dest != 0 && "Invalid Destination module");
1161361e513dSReid Spencer   assert(Src  != 0 && "Invalid Source Module");
1162361e513dSReid Spencer 
11637f3bd82aSChris Lattner   if (Dest->getDataLayout().empty()) {
11647f3bd82aSChris Lattner     if (!Src->getDataLayout().empty()) {
116578bddc38SChris Lattner       Dest->setDataLayout(Src->getDataLayout());
11667f3bd82aSChris Lattner     } else {
11673ac38e99SReid Spencer       std::string DataLayout;
11683ac38e99SReid Spencer 
1169bddf51bcSAnton Korobeynikov       if (Dest->getEndianness() == Module::AnyEndianness) {
11703ac38e99SReid Spencer         if (Src->getEndianness() == Module::BigEndian)
11713ac38e99SReid Spencer           DataLayout.append("E");
11723ac38e99SReid Spencer         else if (Src->getEndianness() == Module::LittleEndian)
11733ac38e99SReid Spencer           DataLayout.append("e");
1174bddf51bcSAnton Korobeynikov       }
1175bddf51bcSAnton Korobeynikov 
1176bddf51bcSAnton Korobeynikov       if (Dest->getPointerSize() == Module::AnyPointerSize) {
11773ac38e99SReid Spencer         if (Src->getPointerSize() == Module::Pointer64)
11783ac38e99SReid Spencer           DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
11793ac38e99SReid Spencer         else if (Src->getPointerSize() == Module::Pointer32)
11803ac38e99SReid Spencer           DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1181bddf51bcSAnton Korobeynikov       }
11823ac38e99SReid Spencer       Dest->setDataLayout(DataLayout);
11837f3bd82aSChris Lattner     }
11847f3bd82aSChris Lattner   }
1185361e513dSReid Spencer 
118690c2df5bSChris Lattner   // Copy the target triple from the source to dest if the dest's is empty.
11877f3bd82aSChris Lattner   if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
11887f3bd82aSChris Lattner     Dest->setTargetTriple(Src->getTargetTriple());
11897f3bd82aSChris Lattner 
11907f3bd82aSChris Lattner   if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
11917f3bd82aSChris Lattner       Src->getDataLayout() != Dest->getDataLayout())
11923ac38e99SReid Spencer     cerr << "WARNING: Linking two modules of different data layouts!\n";
1193b7f5916eSChris Lattner   if (!Src->getTargetTriple().empty() &&
1194b7f5916eSChris Lattner       Dest->getTargetTriple() != Src->getTargetTriple())
1195f3baad3eSBill Wendling     cerr << "WARNING: Linking two modules of different target triples!\n";
1196361e513dSReid Spencer 
119790c2df5bSChris Lattner   // Append the module inline asm string.
11988ebd2164SChris Lattner   if (!Src->getModuleInlineAsm().empty()) {
11998ebd2164SChris Lattner     if (Dest->getModuleInlineAsm().empty())
12008ebd2164SChris Lattner       Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1201dd2d3fafSChris Lattner     else
12028ebd2164SChris Lattner       Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
12038ebd2164SChris Lattner                                Src->getModuleInlineAsm());
1204dd2d3fafSChris Lattner   }
1205dd2d3fafSChris Lattner 
1206361e513dSReid Spencer   // Update the destination module's dependent libraries list with the libraries
1207361e513dSReid Spencer   // from the source module. There's no opportunity for duplicates here as the
1208361e513dSReid Spencer   // Module ensures that duplicate insertions are discarded.
120990c2df5bSChris Lattner   for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
121090c2df5bSChris Lattner        SI != SE; ++SI)
1211361e513dSReid Spencer     Dest->addLibrary(*SI);
1212361e513dSReid Spencer 
1213361e513dSReid Spencer   // LinkTypes - Go through the symbol table of the Src module and see if any
1214361e513dSReid Spencer   // types are named in the src module that are not named in the Dst module.
1215361e513dSReid Spencer   // Make sure there are no type name conflicts.
1216d3ba7d9bSReid Spencer   if (LinkTypes(Dest, Src, ErrorMsg))
1217d3ba7d9bSReid Spencer     return true;
1218361e513dSReid Spencer 
1219361e513dSReid Spencer   // ValueMap - Mapping of values from what they used to be in Src, to what they
1220361e513dSReid Spencer   // are now in Dest.
1221361e513dSReid Spencer   std::map<const Value*, Value*> ValueMap;
1222361e513dSReid Spencer 
1223361e513dSReid Spencer   // AppendingVars - Keep track of global variables in the destination module
1224361e513dSReid Spencer   // with appending linkage.  After the module is linked together, they are
1225361e513dSReid Spencer   // appended and the module is rewritten.
1226361e513dSReid Spencer   std::multimap<std::string, GlobalVariable *> AppendingVars;
122744ab8aefSChris Lattner   for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
122844ab8aefSChris Lattner        I != E; ++I) {
1229361e513dSReid Spencer     // Add all of the appending globals already in the Dest module to
1230361e513dSReid Spencer     // AppendingVars.
1231361e513dSReid Spencer     if (I->hasAppendingLinkage())
1232361e513dSReid Spencer       AppendingVars.insert(std::make_pair(I->getName(), I));
1233361e513dSReid Spencer   }
1234361e513dSReid Spencer 
1235361e513dSReid Spencer   // Insert all of the globals in src into the Dest module... without linking
1236361e513dSReid Spencer   // initializers (which could refer to functions not yet mapped over).
12373aaaa0b2SReid Spencer   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1238361e513dSReid Spencer     return true;
1239361e513dSReid Spencer 
1240361e513dSReid Spencer   // Link the functions together between the two modules, without doing function
1241361e513dSReid Spencer   // bodies... this just adds external function prototypes to the Dest
1242361e513dSReid Spencer   // function...  We do this so that when we begin processing function bodies,
1243361e513dSReid Spencer   // all of the global values that may be referenced are available in our
1244361e513dSReid Spencer   // ValueMap.
12453aaaa0b2SReid Spencer   if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1246361e513dSReid Spencer     return true;
1247361e513dSReid Spencer 
12482e13597fSAnton Korobeynikov   // If there were any alias, link them now. We really need to do this now,
12492e13597fSAnton Korobeynikov   // because all of the aliases that may be referenced need to be available in
12502e13597fSAnton Korobeynikov   // ValueMap
12512e13597fSAnton Korobeynikov   if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
12522e13597fSAnton Korobeynikov 
1253361e513dSReid Spencer   // Update the initializers in the Dest module now that all globals that may
1254361e513dSReid Spencer   // be referenced are in Dest.
1255361e513dSReid Spencer   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1256361e513dSReid Spencer 
1257361e513dSReid Spencer   // Link in the function bodies that are defined in the source module into the
1258361e513dSReid Spencer   // DestModule.  This consists basically of copying the function over and
1259361e513dSReid Spencer   // fixing up references to values.
1260361e513dSReid Spencer   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1261361e513dSReid Spencer 
1262361e513dSReid Spencer   // If there were any appending global variables, link them together now.
1263361e513dSReid Spencer   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1264361e513dSReid Spencer 
1265e43711d3SAnton Korobeynikov   // Resolve all uses of aliases with aliasees
1266e43711d3SAnton Korobeynikov   if (ResolveAliases(Dest)) return true;
1267e43711d3SAnton Korobeynikov 
1268361e513dSReid Spencer   // If the source library's module id is in the dependent library list of the
1269361e513dSReid Spencer   // destination library, remove it since that module is now linked in.
1270361e513dSReid Spencer   sys::Path modId;
1271c9c0473fSReid Spencer   modId.set(Src->getModuleIdentifier());
1272361e513dSReid Spencer   if (!modId.isEmpty())
1273361e513dSReid Spencer     Dest->removeLibrary(modId.getBasename());
1274361e513dSReid Spencer 
1275361e513dSReid Spencer   return false;
1276361e513dSReid Spencer }
1277361e513dSReid Spencer 
1278361e513dSReid Spencer // vim: sw=2
1279