1361e513dSReid Spencer //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2361e513dSReid Spencer //
3361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4361e513dSReid Spencer //
5361e513dSReid Spencer // This file was developed by the LLVM research group and is distributed under
6361e513dSReid Spencer // the University of Illinois Open Source 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 
19*9b0ddbbeSReid Spencer #include "llvm/Linker.h"
20361e513dSReid Spencer #include "llvm/Constants.h"
21361e513dSReid Spencer #include "llvm/DerivedTypes.h"
22361e513dSReid Spencer #include "llvm/Module.h"
23361e513dSReid Spencer #include "llvm/SymbolTable.h"
24361e513dSReid Spencer #include "llvm/Instructions.h"
25361e513dSReid Spencer #include "llvm/Assembly/Writer.h"
26361e513dSReid Spencer #include "llvm/System/Path.h"
27361e513dSReid Spencer #include <iostream>
28361e513dSReid Spencer #include <sstream>
29361e513dSReid Spencer using namespace llvm;
30361e513dSReid Spencer 
31361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true.
32361e513dSReid Spencer // This just makes error return conditions a little bit simpler...
33361e513dSReid Spencer //
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 
39361e513dSReid Spencer static std::string ToStr(const Type *Ty, const Module *M) {
40361e513dSReid Spencer   std::ostringstream OS;
41361e513dSReid Spencer   WriteTypeSymbolic(OS, Ty, M);
42361e513dSReid Spencer   return OS.str();
43361e513dSReid Spencer }
44361e513dSReid Spencer 
45361e513dSReid Spencer //
46361e513dSReid Spencer // Function: ResolveTypes()
47361e513dSReid Spencer //
48361e513dSReid Spencer // Description:
49361e513dSReid Spencer //  Attempt to link the two specified types together.
50361e513dSReid Spencer //
51361e513dSReid Spencer // Inputs:
52361e513dSReid Spencer //  DestTy - The type to which we wish to resolve.
53361e513dSReid Spencer //  SrcTy  - The original type which we want to resolve.
54361e513dSReid Spencer //  Name   - The name of the type.
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,
64361e513dSReid Spencer                          SymbolTable *DestST, const std::string &Name) {
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     else if (!Name.empty())
79361e513dSReid Spencer       DestST->insert(Name, const_cast<Type*>(SrcTy));
80361e513dSReid Spencer   }
81361e513dSReid Spencer   return false;
82361e513dSReid Spencer }
83361e513dSReid Spencer 
84361e513dSReid Spencer static const FunctionType *getFT(const PATypeHolder &TH) {
85361e513dSReid Spencer   return cast<FunctionType>(TH.get());
86361e513dSReid Spencer }
87361e513dSReid Spencer static const StructType *getST(const PATypeHolder &TH) {
88361e513dSReid Spencer   return cast<StructType>(TH.get());
89361e513dSReid Spencer }
90361e513dSReid Spencer 
91361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it
92361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types
93361e513dSReid Spencer // are compatible.
94361e513dSReid Spencer //
95361e513dSReid Spencer static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
96361e513dSReid Spencer                                    const PATypeHolder &SrcTy,
97361e513dSReid Spencer                                    SymbolTable *DestST, const std::string &Name,
98361e513dSReid Spencer                 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
99361e513dSReid Spencer   const Type *SrcTyT = SrcTy.get();
100361e513dSReid Spencer   const Type *DestTyT = DestTy.get();
101361e513dSReid Spencer   if (DestTyT == SrcTyT) return false;       // If already equal, noop
102361e513dSReid Spencer 
103361e513dSReid Spencer   // If we found our opaque type, resolve it now!
104361e513dSReid Spencer   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
105361e513dSReid Spencer     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
106361e513dSReid Spencer 
107361e513dSReid Spencer   // Two types cannot be resolved together if they are of different primitive
108361e513dSReid Spencer   // type.  For example, we cannot resolve an int to a float.
109361e513dSReid Spencer   if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
110361e513dSReid Spencer 
111361e513dSReid Spencer   // Otherwise, resolve the used type used by this derived type...
112361e513dSReid Spencer   switch (DestTyT->getTypeID()) {
113361e513dSReid Spencer   case Type::FunctionTyID: {
114361e513dSReid Spencer     if (cast<FunctionType>(DestTyT)->isVarArg() !=
115361e513dSReid Spencer         cast<FunctionType>(SrcTyT)->isVarArg() ||
116361e513dSReid Spencer         cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
117361e513dSReid Spencer         cast<FunctionType>(SrcTyT)->getNumContainedTypes())
118361e513dSReid Spencer       return true;
119361e513dSReid Spencer     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
120361e513dSReid Spencer       if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
121361e513dSReid Spencer                                  getFT(SrcTy)->getContainedType(i), DestST, "",
122361e513dSReid Spencer                                  Pointers))
123361e513dSReid Spencer         return true;
124361e513dSReid Spencer     return false;
125361e513dSReid Spencer   }
126361e513dSReid Spencer   case Type::StructTyID: {
127361e513dSReid Spencer     if (getST(DestTy)->getNumContainedTypes() !=
128361e513dSReid Spencer         getST(SrcTy)->getNumContainedTypes()) return 1;
129361e513dSReid Spencer     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
130361e513dSReid Spencer       if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
131361e513dSReid Spencer                                  getST(SrcTy)->getContainedType(i), DestST, "",
132361e513dSReid Spencer                                  Pointers))
133361e513dSReid Spencer         return true;
134361e513dSReid Spencer     return false;
135361e513dSReid Spencer   }
136361e513dSReid Spencer   case Type::ArrayTyID: {
137361e513dSReid Spencer     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
138361e513dSReid Spencer     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
139361e513dSReid Spencer     if (DAT->getNumElements() != SAT->getNumElements()) return true;
140361e513dSReid Spencer     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
141361e513dSReid Spencer                                   DestST, "", Pointers);
142361e513dSReid Spencer   }
143361e513dSReid Spencer   case Type::PointerTyID: {
144361e513dSReid Spencer     // If this is a pointer type, check to see if we have already seen it.  If
145361e513dSReid Spencer     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
146361e513dSReid Spencer     // an associative container for this search, because the type pointers (keys
147361e513dSReid Spencer     // in the container) change whenever types get resolved...
148361e513dSReid Spencer     //
149361e513dSReid Spencer     for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
150361e513dSReid Spencer       if (Pointers[i].first == DestTy)
151361e513dSReid Spencer         return Pointers[i].second != SrcTy;
152361e513dSReid Spencer 
153361e513dSReid Spencer     // Otherwise, add the current pointers to the vector to stop recursion on
154361e513dSReid Spencer     // this pair.
155361e513dSReid Spencer     Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
156361e513dSReid Spencer     bool Result =
157361e513dSReid Spencer       RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
158361e513dSReid Spencer                              cast<PointerType>(SrcTy.get())->getElementType(),
159361e513dSReid Spencer                              DestST, "", Pointers);
160361e513dSReid Spencer     Pointers.pop_back();
161361e513dSReid Spencer     return Result;
162361e513dSReid Spencer   }
163361e513dSReid Spencer   default: assert(0 && "Unexpected type!"); return true;
164361e513dSReid Spencer   }
165361e513dSReid Spencer }
166361e513dSReid Spencer 
167361e513dSReid Spencer static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
168361e513dSReid Spencer                                   const PATypeHolder &SrcTy,
169361e513dSReid Spencer                                   SymbolTable *DestST, const std::string &Name){
170361e513dSReid Spencer   std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
171361e513dSReid Spencer   return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
172361e513dSReid Spencer }
173361e513dSReid Spencer 
174361e513dSReid Spencer 
175361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any
176361e513dSReid Spencer // types are named in the src module that are not named in the Dst module.
177361e513dSReid Spencer // Make sure there are no type name conflicts.
178361e513dSReid Spencer //
179361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
180361e513dSReid Spencer   SymbolTable       *DestST = &Dest->getSymbolTable();
181361e513dSReid Spencer   const SymbolTable *SrcST  = &Src->getSymbolTable();
182361e513dSReid Spencer 
183361e513dSReid Spencer   // Look for a type plane for Type's...
184361e513dSReid Spencer   SymbolTable::type_const_iterator TI = SrcST->type_begin();
185361e513dSReid Spencer   SymbolTable::type_const_iterator TE = SrcST->type_end();
186361e513dSReid Spencer   if (TI == TE) return false;  // No named types, do nothing.
187361e513dSReid Spencer 
188361e513dSReid Spencer   // Some types cannot be resolved immediately because they depend on other
189361e513dSReid Spencer   // types being resolved to each other first.  This contains a list of types we
190361e513dSReid Spencer   // are waiting to recheck.
191361e513dSReid Spencer   std::vector<std::string> DelayedTypesToResolve;
192361e513dSReid Spencer 
193361e513dSReid Spencer   for ( ; TI != TE; ++TI ) {
194361e513dSReid Spencer     const std::string &Name = TI->first;
195361e513dSReid Spencer     const Type *RHS = TI->second;
196361e513dSReid Spencer 
197361e513dSReid Spencer     // Check to see if this type name is already in the dest module...
198361e513dSReid Spencer     Type *Entry = DestST->lookupType(Name);
199361e513dSReid Spencer 
200361e513dSReid Spencer     if (ResolveTypes(Entry, RHS, DestST, Name)) {
201361e513dSReid Spencer       // They look different, save the types 'till later to resolve.
202361e513dSReid Spencer       DelayedTypesToResolve.push_back(Name);
203361e513dSReid Spencer     }
204361e513dSReid Spencer   }
205361e513dSReid Spencer 
206361e513dSReid Spencer   // Iteratively resolve types while we can...
207361e513dSReid Spencer   while (!DelayedTypesToResolve.empty()) {
208361e513dSReid Spencer     // Loop over all of the types, attempting to resolve them if possible...
209361e513dSReid Spencer     unsigned OldSize = DelayedTypesToResolve.size();
210361e513dSReid Spencer 
211361e513dSReid Spencer     // Try direct resolution by name...
212361e513dSReid Spencer     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
213361e513dSReid Spencer       const std::string &Name = DelayedTypesToResolve[i];
214361e513dSReid Spencer       Type *T1 = SrcST->lookupType(Name);
215361e513dSReid Spencer       Type *T2 = DestST->lookupType(Name);
216361e513dSReid Spencer       if (!ResolveTypes(T2, T1, DestST, Name)) {
217361e513dSReid Spencer         // We are making progress!
218361e513dSReid Spencer         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
219361e513dSReid Spencer         --i;
220361e513dSReid Spencer       }
221361e513dSReid Spencer     }
222361e513dSReid Spencer 
223361e513dSReid Spencer     // Did we not eliminate any types?
224361e513dSReid Spencer     if (DelayedTypesToResolve.size() == OldSize) {
225361e513dSReid Spencer       // Attempt to resolve subelements of types.  This allows us to merge these
226361e513dSReid Spencer       // two types: { int* } and { opaque* }
227361e513dSReid Spencer       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
228361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve[i];
229361e513dSReid Spencer         PATypeHolder T1(SrcST->lookupType(Name));
230361e513dSReid Spencer         PATypeHolder T2(DestST->lookupType(Name));
231361e513dSReid Spencer 
232361e513dSReid Spencer         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
233361e513dSReid Spencer           // We are making progress!
234361e513dSReid Spencer           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
235361e513dSReid Spencer 
236361e513dSReid Spencer           // Go back to the main loop, perhaps we can resolve directly by name
237361e513dSReid Spencer           // now...
238361e513dSReid Spencer           break;
239361e513dSReid Spencer         }
240361e513dSReid Spencer       }
241361e513dSReid Spencer 
242361e513dSReid Spencer       // If we STILL cannot resolve the types, then there is something wrong.
243361e513dSReid Spencer       // Report the warning and delete one of the names.
244361e513dSReid Spencer       if (DelayedTypesToResolve.size() == OldSize) {
245361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve.back();
246361e513dSReid Spencer 
247361e513dSReid Spencer         const Type *T1 = SrcST->lookupType(Name);
248361e513dSReid Spencer         const Type *T2 = DestST->lookupType(Name);
249361e513dSReid Spencer         std::cerr << "WARNING: Type conflict between types named '" << Name
250361e513dSReid Spencer                   <<  "'.\n    Src='";
251361e513dSReid Spencer         WriteTypeSymbolic(std::cerr, T1, Src);
252361e513dSReid Spencer         std::cerr << "'.\n   Dest='";
253361e513dSReid Spencer         WriteTypeSymbolic(std::cerr, T2, Dest);
254361e513dSReid Spencer         std::cerr << "'\n";
255361e513dSReid Spencer 
256361e513dSReid Spencer         // Remove the symbol name from the destination.
257361e513dSReid Spencer         DelayedTypesToResolve.pop_back();
258361e513dSReid Spencer       }
259361e513dSReid Spencer     }
260361e513dSReid Spencer   }
261361e513dSReid Spencer 
262361e513dSReid Spencer 
263361e513dSReid Spencer   return false;
264361e513dSReid Spencer }
265361e513dSReid Spencer 
266361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) {
267361e513dSReid Spencer   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
268361e513dSReid Spencer        I != E; ++I) {
269361e513dSReid Spencer     std::cerr << " Fr: " << (void*)I->first << " ";
270361e513dSReid Spencer     I->first->dump();
271361e513dSReid Spencer     std::cerr << " To: " << (void*)I->second << " ";
272361e513dSReid Spencer     I->second->dump();
273361e513dSReid Spencer     std::cerr << "\n";
274361e513dSReid Spencer   }
275361e513dSReid Spencer }
276361e513dSReid Spencer 
277361e513dSReid Spencer 
278361e513dSReid Spencer // RemapOperand - Use LocalMap and GlobalMap to convert references from one
279361e513dSReid Spencer // module to another.  This is somewhat sophisticated in that it can
280361e513dSReid Spencer // automatically handle constant references correctly as well...
281361e513dSReid Spencer //
282361e513dSReid Spencer static Value *RemapOperand(const Value *In,
283361e513dSReid Spencer                            std::map<const Value*, Value*> &LocalMap,
284361e513dSReid Spencer                            std::map<const Value*, Value*> *GlobalMap) {
285361e513dSReid Spencer   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
286361e513dSReid Spencer   if (I != LocalMap.end()) return I->second;
287361e513dSReid Spencer 
288361e513dSReid Spencer   if (GlobalMap) {
289361e513dSReid Spencer     I = GlobalMap->find(In);
290361e513dSReid Spencer     if (I != GlobalMap->end()) return I->second;
291361e513dSReid Spencer   }
292361e513dSReid Spencer 
293361e513dSReid Spencer   // Check to see if it's a constant that we are interesting in transforming...
294361e513dSReid Spencer   if (const Constant *CPV = dyn_cast<Constant>(In)) {
295361e513dSReid Spencer     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
296361e513dSReid Spencer         isa<ConstantAggregateZero>(CPV))
297361e513dSReid Spencer       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
298361e513dSReid Spencer 
299361e513dSReid Spencer     Constant *Result = 0;
300361e513dSReid Spencer 
301361e513dSReid Spencer     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
302361e513dSReid Spencer       std::vector<Constant*> Operands(CPA->getNumOperands());
303361e513dSReid Spencer       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
304361e513dSReid Spencer         Operands[i] =
305361e513dSReid Spencer           cast<Constant>(RemapOperand(CPA->getOperand(i), LocalMap, GlobalMap));
306361e513dSReid Spencer       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
307361e513dSReid Spencer     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
308361e513dSReid Spencer       std::vector<Constant*> Operands(CPS->getNumOperands());
309361e513dSReid Spencer       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
310361e513dSReid Spencer         Operands[i] =
311361e513dSReid Spencer           cast<Constant>(RemapOperand(CPS->getOperand(i), LocalMap, GlobalMap));
312361e513dSReid Spencer       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
313361e513dSReid Spencer     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
314361e513dSReid Spencer       Result = const_cast<Constant*>(CPV);
315361e513dSReid Spencer     } else if (isa<GlobalValue>(CPV)) {
316361e513dSReid Spencer       Result = cast<Constant>(RemapOperand(CPV, LocalMap, GlobalMap));
317361e513dSReid Spencer     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
318361e513dSReid Spencer       if (CE->getOpcode() == Instruction::GetElementPtr) {
319361e513dSReid Spencer         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
320361e513dSReid Spencer         std::vector<Constant*> Indices;
321361e513dSReid Spencer         Indices.reserve(CE->getNumOperands()-1);
322361e513dSReid Spencer         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
323361e513dSReid Spencer           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
324361e513dSReid Spencer                                                         LocalMap, GlobalMap)));
325361e513dSReid Spencer 
326361e513dSReid Spencer         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
327361e513dSReid Spencer       } else if (CE->getNumOperands() == 1) {
328361e513dSReid Spencer         // Cast instruction
329361e513dSReid Spencer         assert(CE->getOpcode() == Instruction::Cast);
330361e513dSReid Spencer         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
331361e513dSReid Spencer         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
332361e513dSReid Spencer       } else if (CE->getNumOperands() == 3) {
333361e513dSReid Spencer         // Select instruction
334361e513dSReid Spencer         assert(CE->getOpcode() == Instruction::Select);
335361e513dSReid Spencer         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
336361e513dSReid Spencer         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
337361e513dSReid Spencer         Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
338361e513dSReid Spencer         Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
339361e513dSReid Spencer                                          cast<Constant>(V3));
340361e513dSReid Spencer       } else if (CE->getNumOperands() == 2) {
341361e513dSReid Spencer         // Binary operator...
342361e513dSReid Spencer         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
343361e513dSReid Spencer         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
344361e513dSReid Spencer 
345361e513dSReid Spencer         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
346361e513dSReid Spencer                                    cast<Constant>(V2));
347361e513dSReid Spencer       } else {
348361e513dSReid Spencer         assert(0 && "Unknown constant expr type!");
349361e513dSReid Spencer       }
350361e513dSReid Spencer 
351361e513dSReid Spencer     } else {
352361e513dSReid Spencer       assert(0 && "Unknown type of derived type constant value!");
353361e513dSReid Spencer     }
354361e513dSReid Spencer 
355361e513dSReid Spencer     // Cache the mapping in our local map structure...
356361e513dSReid Spencer     if (GlobalMap)
357361e513dSReid Spencer       GlobalMap->insert(std::make_pair(In, Result));
358361e513dSReid Spencer     else
359361e513dSReid Spencer       LocalMap.insert(std::make_pair(In, Result));
360361e513dSReid Spencer     return Result;
361361e513dSReid Spencer   }
362361e513dSReid Spencer 
363361e513dSReid Spencer   std::cerr << "XXX LocalMap: \n";
364361e513dSReid Spencer   PrintMap(LocalMap);
365361e513dSReid Spencer 
366361e513dSReid Spencer   if (GlobalMap) {
367361e513dSReid Spencer     std::cerr << "XXX GlobalMap: \n";
368361e513dSReid Spencer     PrintMap(*GlobalMap);
369361e513dSReid Spencer   }
370361e513dSReid Spencer 
371361e513dSReid Spencer   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
372361e513dSReid Spencer   assert(0 && "Couldn't remap value!");
373361e513dSReid Spencer   return 0;
374361e513dSReid Spencer }
375361e513dSReid Spencer 
376361e513dSReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
377361e513dSReid Spencer /// in the symbol table.  This is good for all clients except for us.  Go
378361e513dSReid Spencer /// through the trouble to force this back.
379361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
380361e513dSReid Spencer   assert(GV->getName() != Name && "Can't force rename to self");
381361e513dSReid Spencer   SymbolTable &ST = GV->getParent()->getSymbolTable();
382361e513dSReid Spencer 
383361e513dSReid Spencer   // If there is a conflict, rename the conflict.
384361e513dSReid Spencer   Value *ConflictVal = ST.lookup(GV->getType(), Name);
385361e513dSReid Spencer   assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
386361e513dSReid Spencer   GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
387361e513dSReid Spencer   assert(ConflictGV->hasInternalLinkage() &&
388361e513dSReid Spencer          "Not conflicting with a static global, should link instead!");
389361e513dSReid Spencer 
390361e513dSReid Spencer   ConflictGV->setName("");          // Eliminate the conflict
391361e513dSReid Spencer   GV->setName(Name);                // Force the name back
392361e513dSReid Spencer   ConflictGV->setName(Name);        // This will cause ConflictGV to get renamed
393361e513dSReid Spencer   assert(GV->getName() == Name && ConflictGV->getName() != Name &&
394361e513dSReid Spencer          "ForceRenaming didn't work");
395361e513dSReid Spencer }
396361e513dSReid Spencer 
397361e513dSReid Spencer 
398361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge
399361e513dSReid Spencer // them into the dest module.
400361e513dSReid Spencer //
401361e513dSReid Spencer static bool LinkGlobals(Module *Dest, const Module *Src,
402361e513dSReid Spencer                         std::map<const Value*, Value*> &ValueMap,
403361e513dSReid Spencer                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
404361e513dSReid Spencer                         std::map<std::string, GlobalValue*> &GlobalsByName,
405361e513dSReid Spencer                         std::string *Err) {
406361e513dSReid Spencer   // We will need a module level symbol table if the src module has a module
407361e513dSReid Spencer   // level symbol table...
408361e513dSReid Spencer   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
409361e513dSReid Spencer 
410361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
411361e513dSReid Spencer   //
412361e513dSReid Spencer   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
413361e513dSReid Spencer     const GlobalVariable *SGV = I;
414361e513dSReid Spencer     GlobalVariable *DGV = 0;
415361e513dSReid Spencer     // Check to see if may have to link the global.
416361e513dSReid Spencer     if (SGV->hasName() && !SGV->hasInternalLinkage())
417361e513dSReid Spencer       if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
418361e513dSReid Spencer                                           SGV->getType()->getElementType()))) {
419361e513dSReid Spencer         std::map<std::string, GlobalValue*>::iterator EGV =
420361e513dSReid Spencer           GlobalsByName.find(SGV->getName());
421361e513dSReid Spencer         if (EGV != GlobalsByName.end())
422361e513dSReid Spencer           DGV = dyn_cast<GlobalVariable>(EGV->second);
423361e513dSReid Spencer         if (DGV && RecursiveResolveTypes(SGV->getType(), DGV->getType(), ST, ""))
424361e513dSReid Spencer           DGV = 0;  // FIXME: gross.
425361e513dSReid Spencer       }
426361e513dSReid Spencer 
427361e513dSReid Spencer     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
428361e513dSReid Spencer            "Global must either be external or have an initializer!");
429361e513dSReid Spencer 
430361e513dSReid Spencer     bool SGExtern = SGV->isExternal();
431361e513dSReid Spencer     bool DGExtern = DGV ? DGV->isExternal() : false;
432361e513dSReid Spencer 
433361e513dSReid Spencer     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
434361e513dSReid Spencer       // No linking to be performed, simply create an identical version of the
435361e513dSReid Spencer       // symbol over in the dest module... the initializer will be filled in
436361e513dSReid Spencer       // later by LinkGlobalInits...
437361e513dSReid Spencer       //
438361e513dSReid Spencer       GlobalVariable *NewDGV =
439361e513dSReid Spencer         new GlobalVariable(SGV->getType()->getElementType(),
440361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
441361e513dSReid Spencer                            SGV->getName(), Dest);
442361e513dSReid Spencer 
443361e513dSReid Spencer       // If the LLVM runtime renamed the global, but it is an externally visible
444361e513dSReid Spencer       // symbol, DGV must be an existing global with internal linkage.  Rename
445361e513dSReid Spencer       // it.
446361e513dSReid Spencer       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
447361e513dSReid Spencer         ForceRenaming(NewDGV, SGV->getName());
448361e513dSReid Spencer 
449361e513dSReid Spencer       // Make sure to remember this mapping...
450361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, NewDGV));
451361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
452361e513dSReid Spencer         // Keep track that this is an appending variable...
453361e513dSReid Spencer         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
454361e513dSReid Spencer 
455361e513dSReid Spencer     } else if (SGV->isExternal()) {
456361e513dSReid Spencer       // If SGV is external or if both SGV & DGV are external..  Just link the
457361e513dSReid Spencer       // external globals, we aren't adding anything.
458361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
459361e513dSReid Spencer 
460361e513dSReid Spencer       // Inherit 'const' information.
461361e513dSReid Spencer       if (SGV->isConstant()) DGV->setConstant(true);
462361e513dSReid Spencer 
463361e513dSReid Spencer     } else if (DGV->isExternal()) {   // If DGV is external but SGV is not...
464361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
465361e513dSReid Spencer       DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
466361e513dSReid Spencer 
467361e513dSReid Spencer       if (DGV->isConstant() && !SGV->isConstant())
468361e513dSReid Spencer         return Error(Err, "Linking globals named '" + SGV->getName() +
469361e513dSReid Spencer                      "': declaration is const but definition is not!");
470361e513dSReid Spencer 
471361e513dSReid Spencer       // Inherit 'const' information.
472361e513dSReid Spencer       if (SGV->isConstant()) DGV->setConstant(true);
473361e513dSReid Spencer 
474361e513dSReid Spencer     } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
475361e513dSReid Spencer       // At this point we know that DGV has LinkOnce, Appending, Weak, or
476361e513dSReid Spencer       // External linkage.  If DGV is Appending, this is an error.
477361e513dSReid Spencer       if (DGV->hasAppendingLinkage())
478361e513dSReid Spencer         return Error(Err, "Linking globals named '" + SGV->getName() +
479361e513dSReid Spencer                      "' with 'weak' and 'appending' linkage is not allowed!");
480361e513dSReid Spencer 
481361e513dSReid Spencer       if (SGV->isConstant() != DGV->isConstant())
482361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
483361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
484361e513dSReid Spencer                      "' - Global variables differ in const'ness");
485361e513dSReid Spencer 
486361e513dSReid Spencer       // Otherwise, just perform the link.
487361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
488361e513dSReid Spencer 
489361e513dSReid Spencer       // Linkonce+Weak = Weak
490361e513dSReid Spencer       if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
491361e513dSReid Spencer         DGV->setLinkage(SGV->getLinkage());
492361e513dSReid Spencer 
493361e513dSReid Spencer     } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
494361e513dSReid Spencer       // At this point we know that SGV has LinkOnce, Appending, or External
495361e513dSReid Spencer       // linkage.  If SGV is Appending, this is an error.
496361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
497361e513dSReid Spencer         return Error(Err, "Linking globals named '" + SGV->getName() +
498361e513dSReid Spencer                      " ' with 'weak' and 'appending' linkage is not allowed!");
499361e513dSReid Spencer 
500361e513dSReid Spencer       if (SGV->isConstant() != DGV->isConstant())
501361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
502361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
503361e513dSReid Spencer                      "' - Global variables differ in const'ness");
504361e513dSReid Spencer 
505361e513dSReid Spencer       if (!SGV->hasLinkOnceLinkage())
506361e513dSReid Spencer         DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
507361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
508361e513dSReid Spencer 
509361e513dSReid Spencer     } else if (SGV->getLinkage() != DGV->getLinkage()) {
510361e513dSReid Spencer       return Error(Err, "Global variables named '" + SGV->getName() +
511361e513dSReid Spencer                    "' have different linkage specifiers!");
512361e513dSReid Spencer       // Inherit 'const' information.
513361e513dSReid Spencer       if (SGV->isConstant()) DGV->setConstant(true);
514361e513dSReid Spencer 
515361e513dSReid Spencer     } else if (SGV->hasExternalLinkage()) {
516361e513dSReid Spencer       // Allow linking two exactly identical external global variables...
517361e513dSReid Spencer       if (SGV->isConstant() != DGV->isConstant())
518361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
519361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
520361e513dSReid Spencer                      "' - Global variables differ in const'ness");
521361e513dSReid Spencer 
522361e513dSReid Spencer       if (SGV->getInitializer() != DGV->getInitializer())
523361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
524361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
525361e513dSReid Spencer                     "' - External linkage globals have different initializers");
526361e513dSReid Spencer 
527361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
528361e513dSReid Spencer     } else if (SGV->hasAppendingLinkage()) {
529361e513dSReid Spencer       // No linking is performed yet.  Just insert a new copy of the global, and
530361e513dSReid Spencer       // keep track of the fact that it is an appending variable in the
531361e513dSReid Spencer       // AppendingVars map.  The name is cleared out so that no linkage is
532361e513dSReid Spencer       // performed.
533361e513dSReid Spencer       GlobalVariable *NewDGV =
534361e513dSReid Spencer         new GlobalVariable(SGV->getType()->getElementType(),
535361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
536361e513dSReid Spencer                            "", Dest);
537361e513dSReid Spencer 
538361e513dSReid Spencer       // Make sure to remember this mapping...
539361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, NewDGV));
540361e513dSReid Spencer 
541361e513dSReid Spencer       // Keep track that this is an appending variable...
542361e513dSReid Spencer       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
543361e513dSReid Spencer     } else {
544361e513dSReid Spencer       assert(0 && "Unknown linkage!");
545361e513dSReid Spencer     }
546361e513dSReid Spencer   }
547361e513dSReid Spencer   return false;
548361e513dSReid Spencer }
549361e513dSReid Spencer 
550361e513dSReid Spencer 
551361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all
552361e513dSReid Spencer // globals that may be referenced are in Dest.
553361e513dSReid Spencer //
554361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src,
555361e513dSReid Spencer                             std::map<const Value*, Value*> &ValueMap,
556361e513dSReid Spencer                             std::string *Err) {
557361e513dSReid Spencer 
558361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
559361e513dSReid Spencer   //
560361e513dSReid Spencer   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
561361e513dSReid Spencer     const GlobalVariable *SGV = I;
562361e513dSReid Spencer 
563361e513dSReid Spencer     if (SGV->hasInitializer()) {      // Only process initialized GV's
564361e513dSReid Spencer       // Figure out what the initializer looks like in the dest module...
565361e513dSReid Spencer       Constant *SInit =
566361e513dSReid Spencer         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
567361e513dSReid Spencer 
568361e513dSReid Spencer       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
569361e513dSReid Spencer       if (DGV->hasInitializer()) {
570361e513dSReid Spencer         if (SGV->hasExternalLinkage()) {
571361e513dSReid Spencer           if (DGV->getInitializer() != SInit)
572361e513dSReid Spencer             return Error(Err, "Global Variable Collision on '" +
573361e513dSReid Spencer                          ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
574361e513dSReid Spencer                          " - Global variables have different initializers");
575361e513dSReid Spencer         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
576361e513dSReid Spencer           // Nothing is required, mapped values will take the new global
577361e513dSReid Spencer           // automatically.
578361e513dSReid Spencer         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
579361e513dSReid Spencer           // Nothing is required, mapped values will take the new global
580361e513dSReid Spencer           // automatically.
581361e513dSReid Spencer         } else if (DGV->hasAppendingLinkage()) {
582361e513dSReid Spencer           assert(0 && "Appending linkage unimplemented!");
583361e513dSReid Spencer         } else {
584361e513dSReid Spencer           assert(0 && "Unknown linkage!");
585361e513dSReid Spencer         }
586361e513dSReid Spencer       } else {
587361e513dSReid Spencer         // Copy the initializer over now...
588361e513dSReid Spencer         DGV->setInitializer(SInit);
589361e513dSReid Spencer       }
590361e513dSReid Spencer     }
591361e513dSReid Spencer   }
592361e513dSReid Spencer   return false;
593361e513dSReid Spencer }
594361e513dSReid Spencer 
595361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules,
596361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes
597361e513dSReid Spencer // to the Dest function...
598361e513dSReid Spencer //
599361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src,
600361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
601361e513dSReid Spencer                              std::map<std::string, GlobalValue*> &GlobalsByName,
602361e513dSReid Spencer                                std::string *Err) {
603361e513dSReid Spencer   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
604361e513dSReid Spencer 
605361e513dSReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
606361e513dSReid Spencer   // go
607361e513dSReid Spencer   //
608361e513dSReid Spencer   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
609361e513dSReid Spencer     const Function *SF = I;   // SrcFunction
610361e513dSReid Spencer     Function *DF = 0;
611361e513dSReid Spencer     if (SF->hasName() && !SF->hasInternalLinkage()) {
612361e513dSReid Spencer       // Check to see if may have to link the function.
613361e513dSReid Spencer       if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
614361e513dSReid Spencer         std::map<std::string, GlobalValue*>::iterator EF =
615361e513dSReid Spencer           GlobalsByName.find(SF->getName());
616361e513dSReid Spencer         if (EF != GlobalsByName.end())
617361e513dSReid Spencer           DF = dyn_cast<Function>(EF->second);
618361e513dSReid Spencer         if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
619361e513dSReid Spencer           DF = 0;  // FIXME: gross.
620361e513dSReid Spencer       }
621361e513dSReid Spencer     }
622361e513dSReid Spencer 
623361e513dSReid Spencer     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
624361e513dSReid Spencer       // Function does not already exist, simply insert an function signature
625361e513dSReid Spencer       // identical to SF into the dest module...
626361e513dSReid Spencer       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
627361e513dSReid Spencer                                      SF->getName(), Dest);
628361e513dSReid Spencer 
629361e513dSReid Spencer       // If the LLVM runtime renamed the function, but it is an externally
630361e513dSReid Spencer       // visible symbol, DF must be an existing function with internal linkage.
631361e513dSReid Spencer       // Rename it.
632361e513dSReid Spencer       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
633361e513dSReid Spencer         ForceRenaming(NewDF, SF->getName());
634361e513dSReid Spencer 
635361e513dSReid Spencer       // ... and remember this mapping...
636361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, NewDF));
637361e513dSReid Spencer     } else if (SF->isExternal()) {
638361e513dSReid Spencer       // If SF is external or if both SF & DF are external..  Just link the
639361e513dSReid Spencer       // external functions, we aren't adding anything.
640361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
641361e513dSReid Spencer     } else if (DF->isExternal()) {   // If DF is external but SF is not...
642361e513dSReid Spencer       // Link the external functions, update linkage qualifiers
643361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
644361e513dSReid Spencer       DF->setLinkage(SF->getLinkage());
645361e513dSReid Spencer 
646361e513dSReid Spencer     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
647361e513dSReid Spencer       // At this point we know that DF has LinkOnce, Weak, or External linkage.
648361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
649361e513dSReid Spencer 
650361e513dSReid Spencer       // Linkonce+Weak = Weak
651361e513dSReid Spencer       if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
652361e513dSReid Spencer         DF->setLinkage(SF->getLinkage());
653361e513dSReid Spencer 
654361e513dSReid Spencer     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
655361e513dSReid Spencer       // At this point we know that SF has LinkOnce or External linkage.
656361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
657361e513dSReid Spencer       if (!SF->hasLinkOnceLinkage())   // Don't inherit linkonce linkage
658361e513dSReid Spencer         DF->setLinkage(SF->getLinkage());
659361e513dSReid Spencer 
660361e513dSReid Spencer     } else if (SF->getLinkage() != DF->getLinkage()) {
661361e513dSReid Spencer       return Error(Err, "Functions named '" + SF->getName() +
662361e513dSReid Spencer                    "' have different linkage specifiers!");
663361e513dSReid Spencer     } else if (SF->hasExternalLinkage()) {
664361e513dSReid Spencer       // The function is defined in both modules!!
665361e513dSReid Spencer       return Error(Err, "Function '" +
666361e513dSReid Spencer                    ToStr(SF->getFunctionType(), Src) + "':\"" +
667361e513dSReid Spencer                    SF->getName() + "\" - Function is already defined!");
668361e513dSReid Spencer     } else {
669361e513dSReid Spencer       assert(0 && "Unknown linkage configuration found!");
670361e513dSReid Spencer     }
671361e513dSReid Spencer   }
672361e513dSReid Spencer   return false;
673361e513dSReid Spencer }
674361e513dSReid Spencer 
675361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and
676361e513dSReid Spencer // fix up references to values.  At this point we know that Dest is an external
677361e513dSReid Spencer // function, and that Src is not.
678361e513dSReid Spencer //
679361e513dSReid Spencer static bool LinkFunctionBody(Function *Dest, const Function *Src,
680361e513dSReid Spencer                              std::map<const Value*, Value*> &GlobalMap,
681361e513dSReid Spencer                              std::string *Err) {
682361e513dSReid Spencer   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
683361e513dSReid Spencer   std::map<const Value*, Value*> LocalMap;   // Map for function local values
684361e513dSReid Spencer 
685361e513dSReid Spencer   // Go through and convert function arguments over...
686361e513dSReid Spencer   Function::aiterator DI = Dest->abegin();
687361e513dSReid Spencer   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
688361e513dSReid Spencer        I != E; ++I, ++DI) {
689361e513dSReid Spencer     DI->setName(I->getName());  // Copy the name information over...
690361e513dSReid Spencer 
691361e513dSReid Spencer     // Add a mapping to our local map
692361e513dSReid Spencer     LocalMap.insert(std::make_pair(I, DI));
693361e513dSReid Spencer   }
694361e513dSReid Spencer 
695361e513dSReid Spencer   // Loop over all of the basic blocks, copying the instructions over...
696361e513dSReid Spencer   //
697361e513dSReid Spencer   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
698361e513dSReid Spencer     // Create new basic block and add to mapping and the Dest function...
699361e513dSReid Spencer     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
700361e513dSReid Spencer     LocalMap.insert(std::make_pair(I, DBB));
701361e513dSReid Spencer 
702361e513dSReid Spencer     // Loop over all of the instructions in the src basic block, copying them
703361e513dSReid Spencer     // over.  Note that this is broken in a strict sense because the cloned
704361e513dSReid Spencer     // instructions will still be referencing values in the Src module, not
705361e513dSReid Spencer     // the remapped values.  In our case, however, we will not get caught and
706361e513dSReid Spencer     // so we can delay patching the values up until later...
707361e513dSReid Spencer     //
708361e513dSReid Spencer     for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
709361e513dSReid Spencer          II != IE; ++II) {
710361e513dSReid Spencer       Instruction *DI = II->clone();
711361e513dSReid Spencer       DI->setName(II->getName());
712361e513dSReid Spencer       DBB->getInstList().push_back(DI);
713361e513dSReid Spencer       LocalMap.insert(std::make_pair(II, DI));
714361e513dSReid Spencer     }
715361e513dSReid Spencer   }
716361e513dSReid Spencer 
717361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
718361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
719361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
720361e513dSReid Spencer   // functions and patch them up to point to the local versions...
721361e513dSReid Spencer   //
722361e513dSReid Spencer   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
723361e513dSReid Spencer     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
724361e513dSReid Spencer       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
725361e513dSReid Spencer            OI != OE; ++OI)
726361e513dSReid Spencer         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
727361e513dSReid Spencer 
728361e513dSReid Spencer   return false;
729361e513dSReid Spencer }
730361e513dSReid Spencer 
731361e513dSReid Spencer 
732361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the
733361e513dSReid Spencer // source module into the DestModule.  This consists basically of copying the
734361e513dSReid Spencer // function over and fixing up references to values.
735361e513dSReid Spencer //
736361e513dSReid Spencer static bool LinkFunctionBodies(Module *Dest, const Module *Src,
737361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
738361e513dSReid Spencer                                std::string *Err) {
739361e513dSReid Spencer 
740361e513dSReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
741361e513dSReid Spencer   // go
742361e513dSReid Spencer   //
743361e513dSReid Spencer   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
744361e513dSReid Spencer     if (!SF->isExternal()) {                  // No body if function is external
745361e513dSReid Spencer       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
746361e513dSReid Spencer 
747361e513dSReid Spencer       // DF not external SF external?
748361e513dSReid Spencer       if (DF->isExternal()) {
749361e513dSReid Spencer         // Only provide the function body if there isn't one already.
750361e513dSReid Spencer         if (LinkFunctionBody(DF, SF, ValueMap, Err))
751361e513dSReid Spencer           return true;
752361e513dSReid Spencer       }
753361e513dSReid Spencer     }
754361e513dSReid Spencer   }
755361e513dSReid Spencer   return false;
756361e513dSReid Spencer }
757361e513dSReid Spencer 
758361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them
759361e513dSReid Spencer // together now.  Return true on error.
760361e513dSReid Spencer //
761361e513dSReid Spencer static bool LinkAppendingVars(Module *M,
762361e513dSReid Spencer                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
763361e513dSReid Spencer                               std::string *ErrorMsg) {
764361e513dSReid Spencer   if (AppendingVars.empty()) return false; // Nothing to do.
765361e513dSReid Spencer 
766361e513dSReid Spencer   // Loop over the multimap of appending vars, processing any variables with the
767361e513dSReid Spencer   // same name, forming a new appending global variable with both of the
768361e513dSReid Spencer   // initializers merged together, then rewrite references to the old variables
769361e513dSReid Spencer   // and delete them.
770361e513dSReid Spencer   //
771361e513dSReid Spencer   std::vector<Constant*> Inits;
772361e513dSReid Spencer   while (AppendingVars.size() > 1) {
773361e513dSReid Spencer     // Get the first two elements in the map...
774361e513dSReid Spencer     std::multimap<std::string,
775361e513dSReid Spencer       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
776361e513dSReid Spencer 
777361e513dSReid Spencer     // If the first two elements are for different names, there is no pair...
778361e513dSReid Spencer     // Otherwise there is a pair, so link them together...
779361e513dSReid Spencer     if (First->first == Second->first) {
780361e513dSReid Spencer       GlobalVariable *G1 = First->second, *G2 = Second->second;
781361e513dSReid Spencer       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
782361e513dSReid Spencer       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
783361e513dSReid Spencer 
784361e513dSReid Spencer       // Check to see that they two arrays agree on type...
785361e513dSReid Spencer       if (T1->getElementType() != T2->getElementType())
786361e513dSReid Spencer         return Error(ErrorMsg,
787361e513dSReid Spencer          "Appending variables with different element types need to be linked!");
788361e513dSReid Spencer       if (G1->isConstant() != G2->isConstant())
789361e513dSReid Spencer         return Error(ErrorMsg,
790361e513dSReid Spencer                      "Appending variables linked with different const'ness!");
791361e513dSReid Spencer 
792361e513dSReid Spencer       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
793361e513dSReid Spencer       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
794361e513dSReid Spencer 
795361e513dSReid Spencer       // Create the new global variable...
796361e513dSReid Spencer       GlobalVariable *NG =
797361e513dSReid Spencer         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
798361e513dSReid Spencer                            /*init*/0, First->first, M);
799361e513dSReid Spencer 
800361e513dSReid Spencer       // Merge the initializer...
801361e513dSReid Spencer       Inits.reserve(NewSize);
802361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
803361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
804361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
805361e513dSReid Spencer       } else {
806361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
807361e513dSReid Spencer         Constant *CV = Constant::getNullValue(T1->getElementType());
808361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
809361e513dSReid Spencer           Inits.push_back(CV);
810361e513dSReid Spencer       }
811361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
812361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
813361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
814361e513dSReid Spencer       } else {
815361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
816361e513dSReid Spencer         Constant *CV = Constant::getNullValue(T2->getElementType());
817361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
818361e513dSReid Spencer           Inits.push_back(CV);
819361e513dSReid Spencer       }
820361e513dSReid Spencer       NG->setInitializer(ConstantArray::get(NewType, Inits));
821361e513dSReid Spencer       Inits.clear();
822361e513dSReid Spencer 
823361e513dSReid Spencer       // Replace any uses of the two global variables with uses of the new
824361e513dSReid Spencer       // global...
825361e513dSReid Spencer 
826361e513dSReid Spencer       // FIXME: This should rewrite simple/straight-forward uses such as
827361e513dSReid Spencer       // getelementptr instructions to not use the Cast!
828361e513dSReid Spencer       G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
829361e513dSReid Spencer       G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
830361e513dSReid Spencer 
831361e513dSReid Spencer       // Remove the two globals from the module now...
832361e513dSReid Spencer       M->getGlobalList().erase(G1);
833361e513dSReid Spencer       M->getGlobalList().erase(G2);
834361e513dSReid Spencer 
835361e513dSReid Spencer       // Put the new global into the AppendingVars map so that we can handle
836361e513dSReid Spencer       // linking of more than two vars...
837361e513dSReid Spencer       Second->second = NG;
838361e513dSReid Spencer     }
839361e513dSReid Spencer     AppendingVars.erase(First);
840361e513dSReid Spencer   }
841361e513dSReid Spencer 
842361e513dSReid Spencer   return false;
843361e513dSReid Spencer }
844361e513dSReid Spencer 
845361e513dSReid Spencer 
846361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting
847361e513dSReid Spencer // left module modified to be the composite of the two input modules.  If an
848361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
849361e513dSReid Spencer // the problem.  Upon failure, the Dest module could be in a modified state, and
850361e513dSReid Spencer // shouldn't be relied on to be consistent.
851361e513dSReid Spencer bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
852361e513dSReid Spencer   assert(Dest != 0 && "Invalid Destination module");
853361e513dSReid Spencer   assert(Src  != 0 && "Invalid Source Module");
854361e513dSReid Spencer 
855361e513dSReid Spencer   if (Dest->getEndianness() == Module::AnyEndianness)
856361e513dSReid Spencer     Dest->setEndianness(Src->getEndianness());
857361e513dSReid Spencer   if (Dest->getPointerSize() == Module::AnyPointerSize)
858361e513dSReid Spencer     Dest->setPointerSize(Src->getPointerSize());
859361e513dSReid Spencer 
860361e513dSReid Spencer   if (Src->getEndianness() != Module::AnyEndianness &&
861361e513dSReid Spencer       Dest->getEndianness() != Src->getEndianness())
862361e513dSReid Spencer     std::cerr << "WARNING: Linking two modules of different endianness!\n";
863361e513dSReid Spencer   if (Src->getPointerSize() != Module::AnyPointerSize &&
864361e513dSReid Spencer       Dest->getPointerSize() != Src->getPointerSize())
865361e513dSReid Spencer     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
866361e513dSReid Spencer 
867361e513dSReid Spencer   // Update the destination module's dependent libraries list with the libraries
868361e513dSReid Spencer   // from the source module. There's no opportunity for duplicates here as the
869361e513dSReid Spencer   // Module ensures that duplicate insertions are discarded.
870361e513dSReid Spencer   Module::lib_iterator SI = Src->lib_begin();
871361e513dSReid Spencer   Module::lib_iterator SE = Src->lib_end();
872361e513dSReid Spencer   while ( SI != SE ) {
873361e513dSReid Spencer     Dest->addLibrary(*SI);
874361e513dSReid Spencer     ++SI;
875361e513dSReid Spencer   }
876361e513dSReid Spencer 
877361e513dSReid Spencer   // LinkTypes - Go through the symbol table of the Src module and see if any
878361e513dSReid Spencer   // types are named in the src module that are not named in the Dst module.
879361e513dSReid Spencer   // Make sure there are no type name conflicts.
880361e513dSReid Spencer   //
881361e513dSReid Spencer   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
882361e513dSReid Spencer 
883361e513dSReid Spencer   // ValueMap - Mapping of values from what they used to be in Src, to what they
884361e513dSReid Spencer   // are now in Dest.
885361e513dSReid Spencer   //
886361e513dSReid Spencer   std::map<const Value*, Value*> ValueMap;
887361e513dSReid Spencer 
888361e513dSReid Spencer   // AppendingVars - Keep track of global variables in the destination module
889361e513dSReid Spencer   // with appending linkage.  After the module is linked together, they are
890361e513dSReid Spencer   // appended and the module is rewritten.
891361e513dSReid Spencer   //
892361e513dSReid Spencer   std::multimap<std::string, GlobalVariable *> AppendingVars;
893361e513dSReid Spencer 
894361e513dSReid Spencer   // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
895361e513dSReid Spencer   // linking by separating globals by type.  Until PR411 is fixed, we replicate
896361e513dSReid Spencer   // it's functionality here.
897361e513dSReid Spencer   std::map<std::string, GlobalValue*> GlobalsByName;
898361e513dSReid Spencer 
899361e513dSReid Spencer   for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I) {
900361e513dSReid Spencer     // Add all of the appending globals already in the Dest module to
901361e513dSReid Spencer     // AppendingVars.
902361e513dSReid Spencer     if (I->hasAppendingLinkage())
903361e513dSReid Spencer       AppendingVars.insert(std::make_pair(I->getName(), I));
904361e513dSReid Spencer 
905361e513dSReid Spencer     // Keep track of all globals by name.
906361e513dSReid Spencer     if (!I->hasInternalLinkage() && I->hasName())
907361e513dSReid Spencer       GlobalsByName[I->getName()] = I;
908361e513dSReid Spencer   }
909361e513dSReid Spencer 
910361e513dSReid Spencer   // Keep track of all globals by name.
911361e513dSReid Spencer   for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
912361e513dSReid Spencer     if (!I->hasInternalLinkage() && I->hasName())
913361e513dSReid Spencer       GlobalsByName[I->getName()] = I;
914361e513dSReid Spencer 
915361e513dSReid Spencer   // Insert all of the globals in src into the Dest module... without linking
916361e513dSReid Spencer   // initializers (which could refer to functions not yet mapped over).
917361e513dSReid Spencer   //
918361e513dSReid Spencer   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
919361e513dSReid Spencer     return true;
920361e513dSReid Spencer 
921361e513dSReid Spencer   // Link the functions together between the two modules, without doing function
922361e513dSReid Spencer   // bodies... this just adds external function prototypes to the Dest
923361e513dSReid Spencer   // function...  We do this so that when we begin processing function bodies,
924361e513dSReid Spencer   // all of the global values that may be referenced are available in our
925361e513dSReid Spencer   // ValueMap.
926361e513dSReid Spencer   //
927361e513dSReid Spencer   if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
928361e513dSReid Spencer     return true;
929361e513dSReid Spencer 
930361e513dSReid Spencer   // Update the initializers in the Dest module now that all globals that may
931361e513dSReid Spencer   // be referenced are in Dest.
932361e513dSReid Spencer   //
933361e513dSReid Spencer   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
934361e513dSReid Spencer 
935361e513dSReid Spencer   // Link in the function bodies that are defined in the source module into the
936361e513dSReid Spencer   // DestModule.  This consists basically of copying the function over and
937361e513dSReid Spencer   // fixing up references to values.
938361e513dSReid Spencer   //
939361e513dSReid Spencer   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
940361e513dSReid Spencer 
941361e513dSReid Spencer   // If there were any appending global variables, link them together now.
942361e513dSReid Spencer   //
943361e513dSReid Spencer   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
944361e513dSReid Spencer 
945361e513dSReid Spencer   // If the source library's module id is in the dependent library list of the
946361e513dSReid Spencer   // destination library, remove it since that module is now linked in.
947361e513dSReid Spencer   sys::Path modId;
948361e513dSReid Spencer   modId.setFile(Src->getModuleIdentifier());
949361e513dSReid Spencer   if (!modId.isEmpty())
950361e513dSReid Spencer     Dest->removeLibrary(modId.getBasename());
951361e513dSReid Spencer 
952361e513dSReid Spencer   return false;
953361e513dSReid Spencer }
954361e513dSReid Spencer 
955361e513dSReid Spencer // vim: sw=2
956