1*361e513dSReid Spencer //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2*361e513dSReid Spencer //
3*361e513dSReid Spencer //                     The LLVM Compiler Infrastructure
4*361e513dSReid Spencer //
5*361e513dSReid Spencer // This file was developed by the LLVM research group and is distributed under
6*361e513dSReid Spencer // the University of Illinois Open Source License. See LICENSE.TXT for details.
7*361e513dSReid Spencer //
8*361e513dSReid Spencer //===----------------------------------------------------------------------===//
9*361e513dSReid Spencer //
10*361e513dSReid Spencer // This file implements the LLVM module linker.
11*361e513dSReid Spencer //
12*361e513dSReid Spencer // Specifically, this:
13*361e513dSReid Spencer //  * Merges global variables between the two modules
14*361e513dSReid Spencer //    * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15*361e513dSReid Spencer //  * Merges functions between two modules
16*361e513dSReid Spencer //
17*361e513dSReid Spencer //===----------------------------------------------------------------------===//
18*361e513dSReid Spencer 
19*361e513dSReid Spencer #include "llvm/Support/Linker.h"
20*361e513dSReid Spencer #include "llvm/Constants.h"
21*361e513dSReid Spencer #include "llvm/DerivedTypes.h"
22*361e513dSReid Spencer #include "llvm/Module.h"
23*361e513dSReid Spencer #include "llvm/SymbolTable.h"
24*361e513dSReid Spencer #include "llvm/Instructions.h"
25*361e513dSReid Spencer #include "llvm/Assembly/Writer.h"
26*361e513dSReid Spencer #include "llvm/System/Path.h"
27*361e513dSReid Spencer #include <iostream>
28*361e513dSReid Spencer #include <sstream>
29*361e513dSReid Spencer using namespace llvm;
30*361e513dSReid Spencer 
31*361e513dSReid Spencer // Error - Simple wrapper function to conditionally assign to E and return true.
32*361e513dSReid Spencer // This just makes error return conditions a little bit simpler...
33*361e513dSReid Spencer //
34*361e513dSReid Spencer static inline bool Error(std::string *E, const std::string &Message) {
35*361e513dSReid Spencer   if (E) *E = Message;
36*361e513dSReid Spencer   return true;
37*361e513dSReid Spencer }
38*361e513dSReid Spencer 
39*361e513dSReid Spencer static std::string ToStr(const Type *Ty, const Module *M) {
40*361e513dSReid Spencer   std::ostringstream OS;
41*361e513dSReid Spencer   WriteTypeSymbolic(OS, Ty, M);
42*361e513dSReid Spencer   return OS.str();
43*361e513dSReid Spencer }
44*361e513dSReid Spencer 
45*361e513dSReid Spencer //
46*361e513dSReid Spencer // Function: ResolveTypes()
47*361e513dSReid Spencer //
48*361e513dSReid Spencer // Description:
49*361e513dSReid Spencer //  Attempt to link the two specified types together.
50*361e513dSReid Spencer //
51*361e513dSReid Spencer // Inputs:
52*361e513dSReid Spencer //  DestTy - The type to which we wish to resolve.
53*361e513dSReid Spencer //  SrcTy  - The original type which we want to resolve.
54*361e513dSReid Spencer //  Name   - The name of the type.
55*361e513dSReid Spencer //
56*361e513dSReid Spencer // Outputs:
57*361e513dSReid Spencer //  DestST - The symbol table in which the new type should be placed.
58*361e513dSReid Spencer //
59*361e513dSReid Spencer // Return value:
60*361e513dSReid Spencer //  true  - There is an error and the types cannot yet be linked.
61*361e513dSReid Spencer //  false - No errors.
62*361e513dSReid Spencer //
63*361e513dSReid Spencer static bool ResolveTypes(const Type *DestTy, const Type *SrcTy,
64*361e513dSReid Spencer                          SymbolTable *DestST, const std::string &Name) {
65*361e513dSReid Spencer   if (DestTy == SrcTy) return false;       // If already equal, noop
66*361e513dSReid Spencer 
67*361e513dSReid Spencer   // Does the type already exist in the module?
68*361e513dSReid Spencer   if (DestTy && !isa<OpaqueType>(DestTy)) {  // Yup, the type already exists...
69*361e513dSReid Spencer     if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
70*361e513dSReid Spencer       const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
71*361e513dSReid Spencer     } else {
72*361e513dSReid Spencer       return true;  // Cannot link types... neither is opaque and not-equal
73*361e513dSReid Spencer     }
74*361e513dSReid Spencer   } else {                       // Type not in dest module.  Add it now.
75*361e513dSReid Spencer     if (DestTy)                  // Type _is_ in module, just opaque...
76*361e513dSReid Spencer       const_cast<OpaqueType*>(cast<OpaqueType>(DestTy))
77*361e513dSReid Spencer                            ->refineAbstractTypeTo(SrcTy);
78*361e513dSReid Spencer     else if (!Name.empty())
79*361e513dSReid Spencer       DestST->insert(Name, const_cast<Type*>(SrcTy));
80*361e513dSReid Spencer   }
81*361e513dSReid Spencer   return false;
82*361e513dSReid Spencer }
83*361e513dSReid Spencer 
84*361e513dSReid Spencer static const FunctionType *getFT(const PATypeHolder &TH) {
85*361e513dSReid Spencer   return cast<FunctionType>(TH.get());
86*361e513dSReid Spencer }
87*361e513dSReid Spencer static const StructType *getST(const PATypeHolder &TH) {
88*361e513dSReid Spencer   return cast<StructType>(TH.get());
89*361e513dSReid Spencer }
90*361e513dSReid Spencer 
91*361e513dSReid Spencer // RecursiveResolveTypes - This is just like ResolveTypes, except that it
92*361e513dSReid Spencer // recurses down into derived types, merging the used types if the parent types
93*361e513dSReid Spencer // are compatible.
94*361e513dSReid Spencer //
95*361e513dSReid Spencer static bool RecursiveResolveTypesI(const PATypeHolder &DestTy,
96*361e513dSReid Spencer                                    const PATypeHolder &SrcTy,
97*361e513dSReid Spencer                                    SymbolTable *DestST, const std::string &Name,
98*361e513dSReid Spencer                 std::vector<std::pair<PATypeHolder, PATypeHolder> > &Pointers) {
99*361e513dSReid Spencer   const Type *SrcTyT = SrcTy.get();
100*361e513dSReid Spencer   const Type *DestTyT = DestTy.get();
101*361e513dSReid Spencer   if (DestTyT == SrcTyT) return false;       // If already equal, noop
102*361e513dSReid Spencer 
103*361e513dSReid Spencer   // If we found our opaque type, resolve it now!
104*361e513dSReid Spencer   if (isa<OpaqueType>(DestTyT) || isa<OpaqueType>(SrcTyT))
105*361e513dSReid Spencer     return ResolveTypes(DestTyT, SrcTyT, DestST, Name);
106*361e513dSReid Spencer 
107*361e513dSReid Spencer   // Two types cannot be resolved together if they are of different primitive
108*361e513dSReid Spencer   // type.  For example, we cannot resolve an int to a float.
109*361e513dSReid Spencer   if (DestTyT->getTypeID() != SrcTyT->getTypeID()) return true;
110*361e513dSReid Spencer 
111*361e513dSReid Spencer   // Otherwise, resolve the used type used by this derived type...
112*361e513dSReid Spencer   switch (DestTyT->getTypeID()) {
113*361e513dSReid Spencer   case Type::FunctionTyID: {
114*361e513dSReid Spencer     if (cast<FunctionType>(DestTyT)->isVarArg() !=
115*361e513dSReid Spencer         cast<FunctionType>(SrcTyT)->isVarArg() ||
116*361e513dSReid Spencer         cast<FunctionType>(DestTyT)->getNumContainedTypes() !=
117*361e513dSReid Spencer         cast<FunctionType>(SrcTyT)->getNumContainedTypes())
118*361e513dSReid Spencer       return true;
119*361e513dSReid Spencer     for (unsigned i = 0, e = getFT(DestTy)->getNumContainedTypes(); i != e; ++i)
120*361e513dSReid Spencer       if (RecursiveResolveTypesI(getFT(DestTy)->getContainedType(i),
121*361e513dSReid Spencer                                  getFT(SrcTy)->getContainedType(i), DestST, "",
122*361e513dSReid Spencer                                  Pointers))
123*361e513dSReid Spencer         return true;
124*361e513dSReid Spencer     return false;
125*361e513dSReid Spencer   }
126*361e513dSReid Spencer   case Type::StructTyID: {
127*361e513dSReid Spencer     if (getST(DestTy)->getNumContainedTypes() !=
128*361e513dSReid Spencer         getST(SrcTy)->getNumContainedTypes()) return 1;
129*361e513dSReid Spencer     for (unsigned i = 0, e = getST(DestTy)->getNumContainedTypes(); i != e; ++i)
130*361e513dSReid Spencer       if (RecursiveResolveTypesI(getST(DestTy)->getContainedType(i),
131*361e513dSReid Spencer                                  getST(SrcTy)->getContainedType(i), DestST, "",
132*361e513dSReid Spencer                                  Pointers))
133*361e513dSReid Spencer         return true;
134*361e513dSReid Spencer     return false;
135*361e513dSReid Spencer   }
136*361e513dSReid Spencer   case Type::ArrayTyID: {
137*361e513dSReid Spencer     const ArrayType *DAT = cast<ArrayType>(DestTy.get());
138*361e513dSReid Spencer     const ArrayType *SAT = cast<ArrayType>(SrcTy.get());
139*361e513dSReid Spencer     if (DAT->getNumElements() != SAT->getNumElements()) return true;
140*361e513dSReid Spencer     return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
141*361e513dSReid Spencer                                   DestST, "", Pointers);
142*361e513dSReid Spencer   }
143*361e513dSReid Spencer   case Type::PointerTyID: {
144*361e513dSReid Spencer     // If this is a pointer type, check to see if we have already seen it.  If
145*361e513dSReid Spencer     // so, we are in a recursive branch.  Cut off the search now.  We cannot use
146*361e513dSReid Spencer     // an associative container for this search, because the type pointers (keys
147*361e513dSReid Spencer     // in the container) change whenever types get resolved...
148*361e513dSReid Spencer     //
149*361e513dSReid Spencer     for (unsigned i = 0, e = Pointers.size(); i != e; ++i)
150*361e513dSReid Spencer       if (Pointers[i].first == DestTy)
151*361e513dSReid Spencer         return Pointers[i].second != SrcTy;
152*361e513dSReid Spencer 
153*361e513dSReid Spencer     // Otherwise, add the current pointers to the vector to stop recursion on
154*361e513dSReid Spencer     // this pair.
155*361e513dSReid Spencer     Pointers.push_back(std::make_pair(DestTyT, SrcTyT));
156*361e513dSReid Spencer     bool Result =
157*361e513dSReid Spencer       RecursiveResolveTypesI(cast<PointerType>(DestTy.get())->getElementType(),
158*361e513dSReid Spencer                              cast<PointerType>(SrcTy.get())->getElementType(),
159*361e513dSReid Spencer                              DestST, "", Pointers);
160*361e513dSReid Spencer     Pointers.pop_back();
161*361e513dSReid Spencer     return Result;
162*361e513dSReid Spencer   }
163*361e513dSReid Spencer   default: assert(0 && "Unexpected type!"); return true;
164*361e513dSReid Spencer   }
165*361e513dSReid Spencer }
166*361e513dSReid Spencer 
167*361e513dSReid Spencer static bool RecursiveResolveTypes(const PATypeHolder &DestTy,
168*361e513dSReid Spencer                                   const PATypeHolder &SrcTy,
169*361e513dSReid Spencer                                   SymbolTable *DestST, const std::string &Name){
170*361e513dSReid Spencer   std::vector<std::pair<PATypeHolder, PATypeHolder> > PointerTypes;
171*361e513dSReid Spencer   return RecursiveResolveTypesI(DestTy, SrcTy, DestST, Name, PointerTypes);
172*361e513dSReid Spencer }
173*361e513dSReid Spencer 
174*361e513dSReid Spencer 
175*361e513dSReid Spencer // LinkTypes - Go through the symbol table of the Src module and see if any
176*361e513dSReid Spencer // types are named in the src module that are not named in the Dst module.
177*361e513dSReid Spencer // Make sure there are no type name conflicts.
178*361e513dSReid Spencer //
179*361e513dSReid Spencer static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
180*361e513dSReid Spencer   SymbolTable       *DestST = &Dest->getSymbolTable();
181*361e513dSReid Spencer   const SymbolTable *SrcST  = &Src->getSymbolTable();
182*361e513dSReid Spencer 
183*361e513dSReid Spencer   // Look for a type plane for Type's...
184*361e513dSReid Spencer   SymbolTable::type_const_iterator TI = SrcST->type_begin();
185*361e513dSReid Spencer   SymbolTable::type_const_iterator TE = SrcST->type_end();
186*361e513dSReid Spencer   if (TI == TE) return false;  // No named types, do nothing.
187*361e513dSReid Spencer 
188*361e513dSReid Spencer   // Some types cannot be resolved immediately because they depend on other
189*361e513dSReid Spencer   // types being resolved to each other first.  This contains a list of types we
190*361e513dSReid Spencer   // are waiting to recheck.
191*361e513dSReid Spencer   std::vector<std::string> DelayedTypesToResolve;
192*361e513dSReid Spencer 
193*361e513dSReid Spencer   for ( ; TI != TE; ++TI ) {
194*361e513dSReid Spencer     const std::string &Name = TI->first;
195*361e513dSReid Spencer     const Type *RHS = TI->second;
196*361e513dSReid Spencer 
197*361e513dSReid Spencer     // Check to see if this type name is already in the dest module...
198*361e513dSReid Spencer     Type *Entry = DestST->lookupType(Name);
199*361e513dSReid Spencer 
200*361e513dSReid Spencer     if (ResolveTypes(Entry, RHS, DestST, Name)) {
201*361e513dSReid Spencer       // They look different, save the types 'till later to resolve.
202*361e513dSReid Spencer       DelayedTypesToResolve.push_back(Name);
203*361e513dSReid Spencer     }
204*361e513dSReid Spencer   }
205*361e513dSReid Spencer 
206*361e513dSReid Spencer   // Iteratively resolve types while we can...
207*361e513dSReid Spencer   while (!DelayedTypesToResolve.empty()) {
208*361e513dSReid Spencer     // Loop over all of the types, attempting to resolve them if possible...
209*361e513dSReid Spencer     unsigned OldSize = DelayedTypesToResolve.size();
210*361e513dSReid Spencer 
211*361e513dSReid Spencer     // Try direct resolution by name...
212*361e513dSReid Spencer     for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
213*361e513dSReid Spencer       const std::string &Name = DelayedTypesToResolve[i];
214*361e513dSReid Spencer       Type *T1 = SrcST->lookupType(Name);
215*361e513dSReid Spencer       Type *T2 = DestST->lookupType(Name);
216*361e513dSReid Spencer       if (!ResolveTypes(T2, T1, DestST, Name)) {
217*361e513dSReid Spencer         // We are making progress!
218*361e513dSReid Spencer         DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
219*361e513dSReid Spencer         --i;
220*361e513dSReid Spencer       }
221*361e513dSReid Spencer     }
222*361e513dSReid Spencer 
223*361e513dSReid Spencer     // Did we not eliminate any types?
224*361e513dSReid Spencer     if (DelayedTypesToResolve.size() == OldSize) {
225*361e513dSReid Spencer       // Attempt to resolve subelements of types.  This allows us to merge these
226*361e513dSReid Spencer       // two types: { int* } and { opaque* }
227*361e513dSReid Spencer       for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
228*361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve[i];
229*361e513dSReid Spencer         PATypeHolder T1(SrcST->lookupType(Name));
230*361e513dSReid Spencer         PATypeHolder T2(DestST->lookupType(Name));
231*361e513dSReid Spencer 
232*361e513dSReid Spencer         if (!RecursiveResolveTypes(T2, T1, DestST, Name)) {
233*361e513dSReid Spencer           // We are making progress!
234*361e513dSReid Spencer           DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
235*361e513dSReid Spencer 
236*361e513dSReid Spencer           // Go back to the main loop, perhaps we can resolve directly by name
237*361e513dSReid Spencer           // now...
238*361e513dSReid Spencer           break;
239*361e513dSReid Spencer         }
240*361e513dSReid Spencer       }
241*361e513dSReid Spencer 
242*361e513dSReid Spencer       // If we STILL cannot resolve the types, then there is something wrong.
243*361e513dSReid Spencer       // Report the warning and delete one of the names.
244*361e513dSReid Spencer       if (DelayedTypesToResolve.size() == OldSize) {
245*361e513dSReid Spencer         const std::string &Name = DelayedTypesToResolve.back();
246*361e513dSReid Spencer 
247*361e513dSReid Spencer         const Type *T1 = SrcST->lookupType(Name);
248*361e513dSReid Spencer         const Type *T2 = DestST->lookupType(Name);
249*361e513dSReid Spencer         std::cerr << "WARNING: Type conflict between types named '" << Name
250*361e513dSReid Spencer                   <<  "'.\n    Src='";
251*361e513dSReid Spencer         WriteTypeSymbolic(std::cerr, T1, Src);
252*361e513dSReid Spencer         std::cerr << "'.\n   Dest='";
253*361e513dSReid Spencer         WriteTypeSymbolic(std::cerr, T2, Dest);
254*361e513dSReid Spencer         std::cerr << "'\n";
255*361e513dSReid Spencer 
256*361e513dSReid Spencer         // Remove the symbol name from the destination.
257*361e513dSReid Spencer         DelayedTypesToResolve.pop_back();
258*361e513dSReid Spencer       }
259*361e513dSReid Spencer     }
260*361e513dSReid Spencer   }
261*361e513dSReid Spencer 
262*361e513dSReid Spencer 
263*361e513dSReid Spencer   return false;
264*361e513dSReid Spencer }
265*361e513dSReid Spencer 
266*361e513dSReid Spencer static void PrintMap(const std::map<const Value*, Value*> &M) {
267*361e513dSReid Spencer   for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
268*361e513dSReid Spencer        I != E; ++I) {
269*361e513dSReid Spencer     std::cerr << " Fr: " << (void*)I->first << " ";
270*361e513dSReid Spencer     I->first->dump();
271*361e513dSReid Spencer     std::cerr << " To: " << (void*)I->second << " ";
272*361e513dSReid Spencer     I->second->dump();
273*361e513dSReid Spencer     std::cerr << "\n";
274*361e513dSReid Spencer   }
275*361e513dSReid Spencer }
276*361e513dSReid Spencer 
277*361e513dSReid Spencer 
278*361e513dSReid Spencer // RemapOperand - Use LocalMap and GlobalMap to convert references from one
279*361e513dSReid Spencer // module to another.  This is somewhat sophisticated in that it can
280*361e513dSReid Spencer // automatically handle constant references correctly as well...
281*361e513dSReid Spencer //
282*361e513dSReid Spencer static Value *RemapOperand(const Value *In,
283*361e513dSReid Spencer                            std::map<const Value*, Value*> &LocalMap,
284*361e513dSReid Spencer                            std::map<const Value*, Value*> *GlobalMap) {
285*361e513dSReid Spencer   std::map<const Value*,Value*>::const_iterator I = LocalMap.find(In);
286*361e513dSReid Spencer   if (I != LocalMap.end()) return I->second;
287*361e513dSReid Spencer 
288*361e513dSReid Spencer   if (GlobalMap) {
289*361e513dSReid Spencer     I = GlobalMap->find(In);
290*361e513dSReid Spencer     if (I != GlobalMap->end()) return I->second;
291*361e513dSReid Spencer   }
292*361e513dSReid Spencer 
293*361e513dSReid Spencer   // Check to see if it's a constant that we are interesting in transforming...
294*361e513dSReid Spencer   if (const Constant *CPV = dyn_cast<Constant>(In)) {
295*361e513dSReid Spencer     if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
296*361e513dSReid Spencer         isa<ConstantAggregateZero>(CPV))
297*361e513dSReid Spencer       return const_cast<Constant*>(CPV);   // Simple constants stay identical...
298*361e513dSReid Spencer 
299*361e513dSReid Spencer     Constant *Result = 0;
300*361e513dSReid Spencer 
301*361e513dSReid Spencer     if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
302*361e513dSReid Spencer       std::vector<Constant*> Operands(CPA->getNumOperands());
303*361e513dSReid Spencer       for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
304*361e513dSReid Spencer         Operands[i] =
305*361e513dSReid Spencer           cast<Constant>(RemapOperand(CPA->getOperand(i), LocalMap, GlobalMap));
306*361e513dSReid Spencer       Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
307*361e513dSReid Spencer     } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
308*361e513dSReid Spencer       std::vector<Constant*> Operands(CPS->getNumOperands());
309*361e513dSReid Spencer       for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
310*361e513dSReid Spencer         Operands[i] =
311*361e513dSReid Spencer           cast<Constant>(RemapOperand(CPS->getOperand(i), LocalMap, GlobalMap));
312*361e513dSReid Spencer       Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
313*361e513dSReid Spencer     } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
314*361e513dSReid Spencer       Result = const_cast<Constant*>(CPV);
315*361e513dSReid Spencer     } else if (isa<GlobalValue>(CPV)) {
316*361e513dSReid Spencer       Result = cast<Constant>(RemapOperand(CPV, LocalMap, GlobalMap));
317*361e513dSReid Spencer     } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
318*361e513dSReid Spencer       if (CE->getOpcode() == Instruction::GetElementPtr) {
319*361e513dSReid Spencer         Value *Ptr = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
320*361e513dSReid Spencer         std::vector<Constant*> Indices;
321*361e513dSReid Spencer         Indices.reserve(CE->getNumOperands()-1);
322*361e513dSReid Spencer         for (unsigned i = 1, e = CE->getNumOperands(); i != e; ++i)
323*361e513dSReid Spencer           Indices.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),
324*361e513dSReid Spencer                                                         LocalMap, GlobalMap)));
325*361e513dSReid Spencer 
326*361e513dSReid Spencer         Result = ConstantExpr::getGetElementPtr(cast<Constant>(Ptr), Indices);
327*361e513dSReid Spencer       } else if (CE->getNumOperands() == 1) {
328*361e513dSReid Spencer         // Cast instruction
329*361e513dSReid Spencer         assert(CE->getOpcode() == Instruction::Cast);
330*361e513dSReid Spencer         Value *V = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
331*361e513dSReid Spencer         Result = ConstantExpr::getCast(cast<Constant>(V), CE->getType());
332*361e513dSReid Spencer       } else if (CE->getNumOperands() == 3) {
333*361e513dSReid Spencer         // Select instruction
334*361e513dSReid Spencer         assert(CE->getOpcode() == Instruction::Select);
335*361e513dSReid Spencer         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
336*361e513dSReid Spencer         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
337*361e513dSReid Spencer         Value *V3 = RemapOperand(CE->getOperand(2), LocalMap, GlobalMap);
338*361e513dSReid Spencer         Result = ConstantExpr::getSelect(cast<Constant>(V1), cast<Constant>(V2),
339*361e513dSReid Spencer                                          cast<Constant>(V3));
340*361e513dSReid Spencer       } else if (CE->getNumOperands() == 2) {
341*361e513dSReid Spencer         // Binary operator...
342*361e513dSReid Spencer         Value *V1 = RemapOperand(CE->getOperand(0), LocalMap, GlobalMap);
343*361e513dSReid Spencer         Value *V2 = RemapOperand(CE->getOperand(1), LocalMap, GlobalMap);
344*361e513dSReid Spencer 
345*361e513dSReid Spencer         Result = ConstantExpr::get(CE->getOpcode(), cast<Constant>(V1),
346*361e513dSReid Spencer                                    cast<Constant>(V2));
347*361e513dSReid Spencer       } else {
348*361e513dSReid Spencer         assert(0 && "Unknown constant expr type!");
349*361e513dSReid Spencer       }
350*361e513dSReid Spencer 
351*361e513dSReid Spencer     } else {
352*361e513dSReid Spencer       assert(0 && "Unknown type of derived type constant value!");
353*361e513dSReid Spencer     }
354*361e513dSReid Spencer 
355*361e513dSReid Spencer     // Cache the mapping in our local map structure...
356*361e513dSReid Spencer     if (GlobalMap)
357*361e513dSReid Spencer       GlobalMap->insert(std::make_pair(In, Result));
358*361e513dSReid Spencer     else
359*361e513dSReid Spencer       LocalMap.insert(std::make_pair(In, Result));
360*361e513dSReid Spencer     return Result;
361*361e513dSReid Spencer   }
362*361e513dSReid Spencer 
363*361e513dSReid Spencer   std::cerr << "XXX LocalMap: \n";
364*361e513dSReid Spencer   PrintMap(LocalMap);
365*361e513dSReid Spencer 
366*361e513dSReid Spencer   if (GlobalMap) {
367*361e513dSReid Spencer     std::cerr << "XXX GlobalMap: \n";
368*361e513dSReid Spencer     PrintMap(*GlobalMap);
369*361e513dSReid Spencer   }
370*361e513dSReid Spencer 
371*361e513dSReid Spencer   std::cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
372*361e513dSReid Spencer   assert(0 && "Couldn't remap value!");
373*361e513dSReid Spencer   return 0;
374*361e513dSReid Spencer }
375*361e513dSReid Spencer 
376*361e513dSReid Spencer /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
377*361e513dSReid Spencer /// in the symbol table.  This is good for all clients except for us.  Go
378*361e513dSReid Spencer /// through the trouble to force this back.
379*361e513dSReid Spencer static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
380*361e513dSReid Spencer   assert(GV->getName() != Name && "Can't force rename to self");
381*361e513dSReid Spencer   SymbolTable &ST = GV->getParent()->getSymbolTable();
382*361e513dSReid Spencer 
383*361e513dSReid Spencer   // If there is a conflict, rename the conflict.
384*361e513dSReid Spencer   Value *ConflictVal = ST.lookup(GV->getType(), Name);
385*361e513dSReid Spencer   assert(ConflictVal&&"Why do we have to force rename if there is no conflic?");
386*361e513dSReid Spencer   GlobalValue *ConflictGV = cast<GlobalValue>(ConflictVal);
387*361e513dSReid Spencer   assert(ConflictGV->hasInternalLinkage() &&
388*361e513dSReid Spencer          "Not conflicting with a static global, should link instead!");
389*361e513dSReid Spencer 
390*361e513dSReid Spencer   ConflictGV->setName("");          // Eliminate the conflict
391*361e513dSReid Spencer   GV->setName(Name);                // Force the name back
392*361e513dSReid Spencer   ConflictGV->setName(Name);        // This will cause ConflictGV to get renamed
393*361e513dSReid Spencer   assert(GV->getName() == Name && ConflictGV->getName() != Name &&
394*361e513dSReid Spencer          "ForceRenaming didn't work");
395*361e513dSReid Spencer }
396*361e513dSReid Spencer 
397*361e513dSReid Spencer 
398*361e513dSReid Spencer // LinkGlobals - Loop through the global variables in the src module and merge
399*361e513dSReid Spencer // them into the dest module.
400*361e513dSReid Spencer //
401*361e513dSReid Spencer static bool LinkGlobals(Module *Dest, const Module *Src,
402*361e513dSReid Spencer                         std::map<const Value*, Value*> &ValueMap,
403*361e513dSReid Spencer                     std::multimap<std::string, GlobalVariable *> &AppendingVars,
404*361e513dSReid Spencer                         std::map<std::string, GlobalValue*> &GlobalsByName,
405*361e513dSReid Spencer                         std::string *Err) {
406*361e513dSReid Spencer   // We will need a module level symbol table if the src module has a module
407*361e513dSReid Spencer   // level symbol table...
408*361e513dSReid Spencer   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
409*361e513dSReid Spencer 
410*361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
411*361e513dSReid Spencer   //
412*361e513dSReid Spencer   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
413*361e513dSReid Spencer     const GlobalVariable *SGV = I;
414*361e513dSReid Spencer     GlobalVariable *DGV = 0;
415*361e513dSReid Spencer     // Check to see if may have to link the global.
416*361e513dSReid Spencer     if (SGV->hasName() && !SGV->hasInternalLinkage())
417*361e513dSReid Spencer       if (!(DGV = Dest->getGlobalVariable(SGV->getName(),
418*361e513dSReid Spencer                                           SGV->getType()->getElementType()))) {
419*361e513dSReid Spencer         std::map<std::string, GlobalValue*>::iterator EGV =
420*361e513dSReid Spencer           GlobalsByName.find(SGV->getName());
421*361e513dSReid Spencer         if (EGV != GlobalsByName.end())
422*361e513dSReid Spencer           DGV = dyn_cast<GlobalVariable>(EGV->second);
423*361e513dSReid Spencer         if (DGV && RecursiveResolveTypes(SGV->getType(), DGV->getType(), ST, ""))
424*361e513dSReid Spencer           DGV = 0;  // FIXME: gross.
425*361e513dSReid Spencer       }
426*361e513dSReid Spencer 
427*361e513dSReid Spencer     assert(SGV->hasInitializer() || SGV->hasExternalLinkage() &&
428*361e513dSReid Spencer            "Global must either be external or have an initializer!");
429*361e513dSReid Spencer 
430*361e513dSReid Spencer     bool SGExtern = SGV->isExternal();
431*361e513dSReid Spencer     bool DGExtern = DGV ? DGV->isExternal() : false;
432*361e513dSReid Spencer 
433*361e513dSReid Spencer     if (!DGV || DGV->hasInternalLinkage() || SGV->hasInternalLinkage()) {
434*361e513dSReid Spencer       // No linking to be performed, simply create an identical version of the
435*361e513dSReid Spencer       // symbol over in the dest module... the initializer will be filled in
436*361e513dSReid Spencer       // later by LinkGlobalInits...
437*361e513dSReid Spencer       //
438*361e513dSReid Spencer       GlobalVariable *NewDGV =
439*361e513dSReid Spencer         new GlobalVariable(SGV->getType()->getElementType(),
440*361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
441*361e513dSReid Spencer                            SGV->getName(), Dest);
442*361e513dSReid Spencer 
443*361e513dSReid Spencer       // If the LLVM runtime renamed the global, but it is an externally visible
444*361e513dSReid Spencer       // symbol, DGV must be an existing global with internal linkage.  Rename
445*361e513dSReid Spencer       // it.
446*361e513dSReid Spencer       if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
447*361e513dSReid Spencer         ForceRenaming(NewDGV, SGV->getName());
448*361e513dSReid Spencer 
449*361e513dSReid Spencer       // Make sure to remember this mapping...
450*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, NewDGV));
451*361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
452*361e513dSReid Spencer         // Keep track that this is an appending variable...
453*361e513dSReid Spencer         AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
454*361e513dSReid Spencer 
455*361e513dSReid Spencer     } else if (SGV->isExternal()) {
456*361e513dSReid Spencer       // If SGV is external or if both SGV & DGV are external..  Just link the
457*361e513dSReid Spencer       // external globals, we aren't adding anything.
458*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
459*361e513dSReid Spencer 
460*361e513dSReid Spencer       // Inherit 'const' information.
461*361e513dSReid Spencer       if (SGV->isConstant()) DGV->setConstant(true);
462*361e513dSReid Spencer 
463*361e513dSReid Spencer     } else if (DGV->isExternal()) {   // If DGV is external but SGV is not...
464*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
465*361e513dSReid Spencer       DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
466*361e513dSReid Spencer 
467*361e513dSReid Spencer       if (DGV->isConstant() && !SGV->isConstant())
468*361e513dSReid Spencer         return Error(Err, "Linking globals named '" + SGV->getName() +
469*361e513dSReid Spencer                      "': declaration is const but definition is not!");
470*361e513dSReid Spencer 
471*361e513dSReid Spencer       // Inherit 'const' information.
472*361e513dSReid Spencer       if (SGV->isConstant()) DGV->setConstant(true);
473*361e513dSReid Spencer 
474*361e513dSReid Spencer     } else if (SGV->hasWeakLinkage() || SGV->hasLinkOnceLinkage()) {
475*361e513dSReid Spencer       // At this point we know that DGV has LinkOnce, Appending, Weak, or
476*361e513dSReid Spencer       // External linkage.  If DGV is Appending, this is an error.
477*361e513dSReid Spencer       if (DGV->hasAppendingLinkage())
478*361e513dSReid Spencer         return Error(Err, "Linking globals named '" + SGV->getName() +
479*361e513dSReid Spencer                      "' with 'weak' and 'appending' linkage is not allowed!");
480*361e513dSReid Spencer 
481*361e513dSReid Spencer       if (SGV->isConstant() != DGV->isConstant())
482*361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
483*361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
484*361e513dSReid Spencer                      "' - Global variables differ in const'ness");
485*361e513dSReid Spencer 
486*361e513dSReid Spencer       // Otherwise, just perform the link.
487*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
488*361e513dSReid Spencer 
489*361e513dSReid Spencer       // Linkonce+Weak = Weak
490*361e513dSReid Spencer       if (DGV->hasLinkOnceLinkage() && SGV->hasWeakLinkage())
491*361e513dSReid Spencer         DGV->setLinkage(SGV->getLinkage());
492*361e513dSReid Spencer 
493*361e513dSReid Spencer     } else if (DGV->hasWeakLinkage() || DGV->hasLinkOnceLinkage()) {
494*361e513dSReid Spencer       // At this point we know that SGV has LinkOnce, Appending, or External
495*361e513dSReid Spencer       // linkage.  If SGV is Appending, this is an error.
496*361e513dSReid Spencer       if (SGV->hasAppendingLinkage())
497*361e513dSReid Spencer         return Error(Err, "Linking globals named '" + SGV->getName() +
498*361e513dSReid Spencer                      " ' with 'weak' and 'appending' linkage is not allowed!");
499*361e513dSReid Spencer 
500*361e513dSReid Spencer       if (SGV->isConstant() != DGV->isConstant())
501*361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
502*361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
503*361e513dSReid Spencer                      "' - Global variables differ in const'ness");
504*361e513dSReid Spencer 
505*361e513dSReid Spencer       if (!SGV->hasLinkOnceLinkage())
506*361e513dSReid Spencer         DGV->setLinkage(SGV->getLinkage());    // Inherit linkage!
507*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
508*361e513dSReid Spencer 
509*361e513dSReid Spencer     } else if (SGV->getLinkage() != DGV->getLinkage()) {
510*361e513dSReid Spencer       return Error(Err, "Global variables named '" + SGV->getName() +
511*361e513dSReid Spencer                    "' have different linkage specifiers!");
512*361e513dSReid Spencer       // Inherit 'const' information.
513*361e513dSReid Spencer       if (SGV->isConstant()) DGV->setConstant(true);
514*361e513dSReid Spencer 
515*361e513dSReid Spencer     } else if (SGV->hasExternalLinkage()) {
516*361e513dSReid Spencer       // Allow linking two exactly identical external global variables...
517*361e513dSReid Spencer       if (SGV->isConstant() != DGV->isConstant())
518*361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
519*361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
520*361e513dSReid Spencer                      "' - Global variables differ in const'ness");
521*361e513dSReid Spencer 
522*361e513dSReid Spencer       if (SGV->getInitializer() != DGV->getInitializer())
523*361e513dSReid Spencer         return Error(Err, "Global Variable Collision on '" +
524*361e513dSReid Spencer                      ToStr(SGV->getType(), Src) + " %" + SGV->getName() +
525*361e513dSReid Spencer                     "' - External linkage globals have different initializers");
526*361e513dSReid Spencer 
527*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, DGV));
528*361e513dSReid Spencer     } else if (SGV->hasAppendingLinkage()) {
529*361e513dSReid Spencer       // No linking is performed yet.  Just insert a new copy of the global, and
530*361e513dSReid Spencer       // keep track of the fact that it is an appending variable in the
531*361e513dSReid Spencer       // AppendingVars map.  The name is cleared out so that no linkage is
532*361e513dSReid Spencer       // performed.
533*361e513dSReid Spencer       GlobalVariable *NewDGV =
534*361e513dSReid Spencer         new GlobalVariable(SGV->getType()->getElementType(),
535*361e513dSReid Spencer                            SGV->isConstant(), SGV->getLinkage(), /*init*/0,
536*361e513dSReid Spencer                            "", Dest);
537*361e513dSReid Spencer 
538*361e513dSReid Spencer       // Make sure to remember this mapping...
539*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SGV, NewDGV));
540*361e513dSReid Spencer 
541*361e513dSReid Spencer       // Keep track that this is an appending variable...
542*361e513dSReid Spencer       AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
543*361e513dSReid Spencer     } else {
544*361e513dSReid Spencer       assert(0 && "Unknown linkage!");
545*361e513dSReid Spencer     }
546*361e513dSReid Spencer   }
547*361e513dSReid Spencer   return false;
548*361e513dSReid Spencer }
549*361e513dSReid Spencer 
550*361e513dSReid Spencer 
551*361e513dSReid Spencer // LinkGlobalInits - Update the initializers in the Dest module now that all
552*361e513dSReid Spencer // globals that may be referenced are in Dest.
553*361e513dSReid Spencer //
554*361e513dSReid Spencer static bool LinkGlobalInits(Module *Dest, const Module *Src,
555*361e513dSReid Spencer                             std::map<const Value*, Value*> &ValueMap,
556*361e513dSReid Spencer                             std::string *Err) {
557*361e513dSReid Spencer 
558*361e513dSReid Spencer   // Loop over all of the globals in the src module, mapping them over as we go
559*361e513dSReid Spencer   //
560*361e513dSReid Spencer   for (Module::const_giterator I = Src->gbegin(), E = Src->gend(); I != E; ++I){
561*361e513dSReid Spencer     const GlobalVariable *SGV = I;
562*361e513dSReid Spencer 
563*361e513dSReid Spencer     if (SGV->hasInitializer()) {      // Only process initialized GV's
564*361e513dSReid Spencer       // Figure out what the initializer looks like in the dest module...
565*361e513dSReid Spencer       Constant *SInit =
566*361e513dSReid Spencer         cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap, 0));
567*361e513dSReid Spencer 
568*361e513dSReid Spencer       GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[SGV]);
569*361e513dSReid Spencer       if (DGV->hasInitializer()) {
570*361e513dSReid Spencer         if (SGV->hasExternalLinkage()) {
571*361e513dSReid Spencer           if (DGV->getInitializer() != SInit)
572*361e513dSReid Spencer             return Error(Err, "Global Variable Collision on '" +
573*361e513dSReid Spencer                          ToStr(SGV->getType(), Src) +"':%"+SGV->getName()+
574*361e513dSReid Spencer                          " - Global variables have different initializers");
575*361e513dSReid Spencer         } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage()) {
576*361e513dSReid Spencer           // Nothing is required, mapped values will take the new global
577*361e513dSReid Spencer           // automatically.
578*361e513dSReid Spencer         } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage()) {
579*361e513dSReid Spencer           // Nothing is required, mapped values will take the new global
580*361e513dSReid Spencer           // automatically.
581*361e513dSReid Spencer         } else if (DGV->hasAppendingLinkage()) {
582*361e513dSReid Spencer           assert(0 && "Appending linkage unimplemented!");
583*361e513dSReid Spencer         } else {
584*361e513dSReid Spencer           assert(0 && "Unknown linkage!");
585*361e513dSReid Spencer         }
586*361e513dSReid Spencer       } else {
587*361e513dSReid Spencer         // Copy the initializer over now...
588*361e513dSReid Spencer         DGV->setInitializer(SInit);
589*361e513dSReid Spencer       }
590*361e513dSReid Spencer     }
591*361e513dSReid Spencer   }
592*361e513dSReid Spencer   return false;
593*361e513dSReid Spencer }
594*361e513dSReid Spencer 
595*361e513dSReid Spencer // LinkFunctionProtos - Link the functions together between the two modules,
596*361e513dSReid Spencer // without doing function bodies... this just adds external function prototypes
597*361e513dSReid Spencer // to the Dest function...
598*361e513dSReid Spencer //
599*361e513dSReid Spencer static bool LinkFunctionProtos(Module *Dest, const Module *Src,
600*361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
601*361e513dSReid Spencer                              std::map<std::string, GlobalValue*> &GlobalsByName,
602*361e513dSReid Spencer                                std::string *Err) {
603*361e513dSReid Spencer   SymbolTable *ST = (SymbolTable*)&Dest->getSymbolTable();
604*361e513dSReid Spencer 
605*361e513dSReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
606*361e513dSReid Spencer   // go
607*361e513dSReid Spencer   //
608*361e513dSReid Spencer   for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
609*361e513dSReid Spencer     const Function *SF = I;   // SrcFunction
610*361e513dSReid Spencer     Function *DF = 0;
611*361e513dSReid Spencer     if (SF->hasName() && !SF->hasInternalLinkage()) {
612*361e513dSReid Spencer       // Check to see if may have to link the function.
613*361e513dSReid Spencer       if (!(DF = Dest->getFunction(SF->getName(), SF->getFunctionType()))) {
614*361e513dSReid Spencer         std::map<std::string, GlobalValue*>::iterator EF =
615*361e513dSReid Spencer           GlobalsByName.find(SF->getName());
616*361e513dSReid Spencer         if (EF != GlobalsByName.end())
617*361e513dSReid Spencer           DF = dyn_cast<Function>(EF->second);
618*361e513dSReid Spencer         if (DF && RecursiveResolveTypes(SF->getType(), DF->getType(), ST, ""))
619*361e513dSReid Spencer           DF = 0;  // FIXME: gross.
620*361e513dSReid Spencer       }
621*361e513dSReid Spencer     }
622*361e513dSReid Spencer 
623*361e513dSReid Spencer     if (!DF || SF->hasInternalLinkage() || DF->hasInternalLinkage()) {
624*361e513dSReid Spencer       // Function does not already exist, simply insert an function signature
625*361e513dSReid Spencer       // identical to SF into the dest module...
626*361e513dSReid Spencer       Function *NewDF = new Function(SF->getFunctionType(), SF->getLinkage(),
627*361e513dSReid Spencer                                      SF->getName(), Dest);
628*361e513dSReid Spencer 
629*361e513dSReid Spencer       // If the LLVM runtime renamed the function, but it is an externally
630*361e513dSReid Spencer       // visible symbol, DF must be an existing function with internal linkage.
631*361e513dSReid Spencer       // Rename it.
632*361e513dSReid Spencer       if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
633*361e513dSReid Spencer         ForceRenaming(NewDF, SF->getName());
634*361e513dSReid Spencer 
635*361e513dSReid Spencer       // ... and remember this mapping...
636*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, NewDF));
637*361e513dSReid Spencer     } else if (SF->isExternal()) {
638*361e513dSReid Spencer       // If SF is external or if both SF & DF are external..  Just link the
639*361e513dSReid Spencer       // external functions, we aren't adding anything.
640*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
641*361e513dSReid Spencer     } else if (DF->isExternal()) {   // If DF is external but SF is not...
642*361e513dSReid Spencer       // Link the external functions, update linkage qualifiers
643*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
644*361e513dSReid Spencer       DF->setLinkage(SF->getLinkage());
645*361e513dSReid Spencer 
646*361e513dSReid Spencer     } else if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage()) {
647*361e513dSReid Spencer       // At this point we know that DF has LinkOnce, Weak, or External linkage.
648*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
649*361e513dSReid Spencer 
650*361e513dSReid Spencer       // Linkonce+Weak = Weak
651*361e513dSReid Spencer       if (DF->hasLinkOnceLinkage() && SF->hasWeakLinkage())
652*361e513dSReid Spencer         DF->setLinkage(SF->getLinkage());
653*361e513dSReid Spencer 
654*361e513dSReid Spencer     } else if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage()) {
655*361e513dSReid Spencer       // At this point we know that SF has LinkOnce or External linkage.
656*361e513dSReid Spencer       ValueMap.insert(std::make_pair(SF, DF));
657*361e513dSReid Spencer       if (!SF->hasLinkOnceLinkage())   // Don't inherit linkonce linkage
658*361e513dSReid Spencer         DF->setLinkage(SF->getLinkage());
659*361e513dSReid Spencer 
660*361e513dSReid Spencer     } else if (SF->getLinkage() != DF->getLinkage()) {
661*361e513dSReid Spencer       return Error(Err, "Functions named '" + SF->getName() +
662*361e513dSReid Spencer                    "' have different linkage specifiers!");
663*361e513dSReid Spencer     } else if (SF->hasExternalLinkage()) {
664*361e513dSReid Spencer       // The function is defined in both modules!!
665*361e513dSReid Spencer       return Error(Err, "Function '" +
666*361e513dSReid Spencer                    ToStr(SF->getFunctionType(), Src) + "':\"" +
667*361e513dSReid Spencer                    SF->getName() + "\" - Function is already defined!");
668*361e513dSReid Spencer     } else {
669*361e513dSReid Spencer       assert(0 && "Unknown linkage configuration found!");
670*361e513dSReid Spencer     }
671*361e513dSReid Spencer   }
672*361e513dSReid Spencer   return false;
673*361e513dSReid Spencer }
674*361e513dSReid Spencer 
675*361e513dSReid Spencer // LinkFunctionBody - Copy the source function over into the dest function and
676*361e513dSReid Spencer // fix up references to values.  At this point we know that Dest is an external
677*361e513dSReid Spencer // function, and that Src is not.
678*361e513dSReid Spencer //
679*361e513dSReid Spencer static bool LinkFunctionBody(Function *Dest, const Function *Src,
680*361e513dSReid Spencer                              std::map<const Value*, Value*> &GlobalMap,
681*361e513dSReid Spencer                              std::string *Err) {
682*361e513dSReid Spencer   assert(Src && Dest && Dest->isExternal() && !Src->isExternal());
683*361e513dSReid Spencer   std::map<const Value*, Value*> LocalMap;   // Map for function local values
684*361e513dSReid Spencer 
685*361e513dSReid Spencer   // Go through and convert function arguments over...
686*361e513dSReid Spencer   Function::aiterator DI = Dest->abegin();
687*361e513dSReid Spencer   for (Function::const_aiterator I = Src->abegin(), E = Src->aend();
688*361e513dSReid Spencer        I != E; ++I, ++DI) {
689*361e513dSReid Spencer     DI->setName(I->getName());  // Copy the name information over...
690*361e513dSReid Spencer 
691*361e513dSReid Spencer     // Add a mapping to our local map
692*361e513dSReid Spencer     LocalMap.insert(std::make_pair(I, DI));
693*361e513dSReid Spencer   }
694*361e513dSReid Spencer 
695*361e513dSReid Spencer   // Loop over all of the basic blocks, copying the instructions over...
696*361e513dSReid Spencer   //
697*361e513dSReid Spencer   for (Function::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
698*361e513dSReid Spencer     // Create new basic block and add to mapping and the Dest function...
699*361e513dSReid Spencer     BasicBlock *DBB = new BasicBlock(I->getName(), Dest);
700*361e513dSReid Spencer     LocalMap.insert(std::make_pair(I, DBB));
701*361e513dSReid Spencer 
702*361e513dSReid Spencer     // Loop over all of the instructions in the src basic block, copying them
703*361e513dSReid Spencer     // over.  Note that this is broken in a strict sense because the cloned
704*361e513dSReid Spencer     // instructions will still be referencing values in the Src module, not
705*361e513dSReid Spencer     // the remapped values.  In our case, however, we will not get caught and
706*361e513dSReid Spencer     // so we can delay patching the values up until later...
707*361e513dSReid Spencer     //
708*361e513dSReid Spencer     for (BasicBlock::const_iterator II = I->begin(), IE = I->end();
709*361e513dSReid Spencer          II != IE; ++II) {
710*361e513dSReid Spencer       Instruction *DI = II->clone();
711*361e513dSReid Spencer       DI->setName(II->getName());
712*361e513dSReid Spencer       DBB->getInstList().push_back(DI);
713*361e513dSReid Spencer       LocalMap.insert(std::make_pair(II, DI));
714*361e513dSReid Spencer     }
715*361e513dSReid Spencer   }
716*361e513dSReid Spencer 
717*361e513dSReid Spencer   // At this point, all of the instructions and values of the function are now
718*361e513dSReid Spencer   // copied over.  The only problem is that they are still referencing values in
719*361e513dSReid Spencer   // the Source function as operands.  Loop through all of the operands of the
720*361e513dSReid Spencer   // functions and patch them up to point to the local versions...
721*361e513dSReid Spencer   //
722*361e513dSReid Spencer   for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
723*361e513dSReid Spencer     for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
724*361e513dSReid Spencer       for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
725*361e513dSReid Spencer            OI != OE; ++OI)
726*361e513dSReid Spencer         *OI = RemapOperand(*OI, LocalMap, &GlobalMap);
727*361e513dSReid Spencer 
728*361e513dSReid Spencer   return false;
729*361e513dSReid Spencer }
730*361e513dSReid Spencer 
731*361e513dSReid Spencer 
732*361e513dSReid Spencer // LinkFunctionBodies - Link in the function bodies that are defined in the
733*361e513dSReid Spencer // source module into the DestModule.  This consists basically of copying the
734*361e513dSReid Spencer // function over and fixing up references to values.
735*361e513dSReid Spencer //
736*361e513dSReid Spencer static bool LinkFunctionBodies(Module *Dest, const Module *Src,
737*361e513dSReid Spencer                                std::map<const Value*, Value*> &ValueMap,
738*361e513dSReid Spencer                                std::string *Err) {
739*361e513dSReid Spencer 
740*361e513dSReid Spencer   // Loop over all of the functions in the src module, mapping them over as we
741*361e513dSReid Spencer   // go
742*361e513dSReid Spencer   //
743*361e513dSReid Spencer   for (Module::const_iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF){
744*361e513dSReid Spencer     if (!SF->isExternal()) {                  // No body if function is external
745*361e513dSReid Spencer       Function *DF = cast<Function>(ValueMap[SF]); // Destination function
746*361e513dSReid Spencer 
747*361e513dSReid Spencer       // DF not external SF external?
748*361e513dSReid Spencer       if (DF->isExternal()) {
749*361e513dSReid Spencer         // Only provide the function body if there isn't one already.
750*361e513dSReid Spencer         if (LinkFunctionBody(DF, SF, ValueMap, Err))
751*361e513dSReid Spencer           return true;
752*361e513dSReid Spencer       }
753*361e513dSReid Spencer     }
754*361e513dSReid Spencer   }
755*361e513dSReid Spencer   return false;
756*361e513dSReid Spencer }
757*361e513dSReid Spencer 
758*361e513dSReid Spencer // LinkAppendingVars - If there were any appending global variables, link them
759*361e513dSReid Spencer // together now.  Return true on error.
760*361e513dSReid Spencer //
761*361e513dSReid Spencer static bool LinkAppendingVars(Module *M,
762*361e513dSReid Spencer                   std::multimap<std::string, GlobalVariable *> &AppendingVars,
763*361e513dSReid Spencer                               std::string *ErrorMsg) {
764*361e513dSReid Spencer   if (AppendingVars.empty()) return false; // Nothing to do.
765*361e513dSReid Spencer 
766*361e513dSReid Spencer   // Loop over the multimap of appending vars, processing any variables with the
767*361e513dSReid Spencer   // same name, forming a new appending global variable with both of the
768*361e513dSReid Spencer   // initializers merged together, then rewrite references to the old variables
769*361e513dSReid Spencer   // and delete them.
770*361e513dSReid Spencer   //
771*361e513dSReid Spencer   std::vector<Constant*> Inits;
772*361e513dSReid Spencer   while (AppendingVars.size() > 1) {
773*361e513dSReid Spencer     // Get the first two elements in the map...
774*361e513dSReid Spencer     std::multimap<std::string,
775*361e513dSReid Spencer       GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
776*361e513dSReid Spencer 
777*361e513dSReid Spencer     // If the first two elements are for different names, there is no pair...
778*361e513dSReid Spencer     // Otherwise there is a pair, so link them together...
779*361e513dSReid Spencer     if (First->first == Second->first) {
780*361e513dSReid Spencer       GlobalVariable *G1 = First->second, *G2 = Second->second;
781*361e513dSReid Spencer       const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
782*361e513dSReid Spencer       const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
783*361e513dSReid Spencer 
784*361e513dSReid Spencer       // Check to see that they two arrays agree on type...
785*361e513dSReid Spencer       if (T1->getElementType() != T2->getElementType())
786*361e513dSReid Spencer         return Error(ErrorMsg,
787*361e513dSReid Spencer          "Appending variables with different element types need to be linked!");
788*361e513dSReid Spencer       if (G1->isConstant() != G2->isConstant())
789*361e513dSReid Spencer         return Error(ErrorMsg,
790*361e513dSReid Spencer                      "Appending variables linked with different const'ness!");
791*361e513dSReid Spencer 
792*361e513dSReid Spencer       unsigned NewSize = T1->getNumElements() + T2->getNumElements();
793*361e513dSReid Spencer       ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
794*361e513dSReid Spencer 
795*361e513dSReid Spencer       // Create the new global variable...
796*361e513dSReid Spencer       GlobalVariable *NG =
797*361e513dSReid Spencer         new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
798*361e513dSReid Spencer                            /*init*/0, First->first, M);
799*361e513dSReid Spencer 
800*361e513dSReid Spencer       // Merge the initializer...
801*361e513dSReid Spencer       Inits.reserve(NewSize);
802*361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
803*361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
804*361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
805*361e513dSReid Spencer       } else {
806*361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G1->getInitializer()));
807*361e513dSReid Spencer         Constant *CV = Constant::getNullValue(T1->getElementType());
808*361e513dSReid Spencer         for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
809*361e513dSReid Spencer           Inits.push_back(CV);
810*361e513dSReid Spencer       }
811*361e513dSReid Spencer       if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
812*361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
813*361e513dSReid Spencer           Inits.push_back(I->getOperand(i));
814*361e513dSReid Spencer       } else {
815*361e513dSReid Spencer         assert(isa<ConstantAggregateZero>(G2->getInitializer()));
816*361e513dSReid Spencer         Constant *CV = Constant::getNullValue(T2->getElementType());
817*361e513dSReid Spencer         for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
818*361e513dSReid Spencer           Inits.push_back(CV);
819*361e513dSReid Spencer       }
820*361e513dSReid Spencer       NG->setInitializer(ConstantArray::get(NewType, Inits));
821*361e513dSReid Spencer       Inits.clear();
822*361e513dSReid Spencer 
823*361e513dSReid Spencer       // Replace any uses of the two global variables with uses of the new
824*361e513dSReid Spencer       // global...
825*361e513dSReid Spencer 
826*361e513dSReid Spencer       // FIXME: This should rewrite simple/straight-forward uses such as
827*361e513dSReid Spencer       // getelementptr instructions to not use the Cast!
828*361e513dSReid Spencer       G1->replaceAllUsesWith(ConstantExpr::getCast(NG, G1->getType()));
829*361e513dSReid Spencer       G2->replaceAllUsesWith(ConstantExpr::getCast(NG, G2->getType()));
830*361e513dSReid Spencer 
831*361e513dSReid Spencer       // Remove the two globals from the module now...
832*361e513dSReid Spencer       M->getGlobalList().erase(G1);
833*361e513dSReid Spencer       M->getGlobalList().erase(G2);
834*361e513dSReid Spencer 
835*361e513dSReid Spencer       // Put the new global into the AppendingVars map so that we can handle
836*361e513dSReid Spencer       // linking of more than two vars...
837*361e513dSReid Spencer       Second->second = NG;
838*361e513dSReid Spencer     }
839*361e513dSReid Spencer     AppendingVars.erase(First);
840*361e513dSReid Spencer   }
841*361e513dSReid Spencer 
842*361e513dSReid Spencer   return false;
843*361e513dSReid Spencer }
844*361e513dSReid Spencer 
845*361e513dSReid Spencer 
846*361e513dSReid Spencer // LinkModules - This function links two modules together, with the resulting
847*361e513dSReid Spencer // left module modified to be the composite of the two input modules.  If an
848*361e513dSReid Spencer // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
849*361e513dSReid Spencer // the problem.  Upon failure, the Dest module could be in a modified state, and
850*361e513dSReid Spencer // shouldn't be relied on to be consistent.
851*361e513dSReid Spencer //
852*361e513dSReid Spencer bool llvm::LinkModules(Module *Dest, const Module *Src, std::string *ErrorMsg) {
853*361e513dSReid Spencer   assert(Dest != 0 && "Invalid Destination module");
854*361e513dSReid Spencer   assert(Src  != 0 && "Invalid Source Module");
855*361e513dSReid Spencer 
856*361e513dSReid Spencer   if (Dest->getEndianness() == Module::AnyEndianness)
857*361e513dSReid Spencer     Dest->setEndianness(Src->getEndianness());
858*361e513dSReid Spencer   if (Dest->getPointerSize() == Module::AnyPointerSize)
859*361e513dSReid Spencer     Dest->setPointerSize(Src->getPointerSize());
860*361e513dSReid Spencer 
861*361e513dSReid Spencer   if (Src->getEndianness() != Module::AnyEndianness &&
862*361e513dSReid Spencer       Dest->getEndianness() != Src->getEndianness())
863*361e513dSReid Spencer     std::cerr << "WARNING: Linking two modules of different endianness!\n";
864*361e513dSReid Spencer   if (Src->getPointerSize() != Module::AnyPointerSize &&
865*361e513dSReid Spencer       Dest->getPointerSize() != Src->getPointerSize())
866*361e513dSReid Spencer     std::cerr << "WARNING: Linking two modules of different pointer size!\n";
867*361e513dSReid Spencer 
868*361e513dSReid Spencer   // Update the destination module's dependent libraries list with the libraries
869*361e513dSReid Spencer   // from the source module. There's no opportunity for duplicates here as the
870*361e513dSReid Spencer   // Module ensures that duplicate insertions are discarded.
871*361e513dSReid Spencer   Module::lib_iterator SI = Src->lib_begin();
872*361e513dSReid Spencer   Module::lib_iterator SE = Src->lib_end();
873*361e513dSReid Spencer   while ( SI != SE ) {
874*361e513dSReid Spencer     Dest->addLibrary(*SI);
875*361e513dSReid Spencer     ++SI;
876*361e513dSReid Spencer   }
877*361e513dSReid Spencer 
878*361e513dSReid Spencer   // LinkTypes - Go through the symbol table of the Src module and see if any
879*361e513dSReid Spencer   // types are named in the src module that are not named in the Dst module.
880*361e513dSReid Spencer   // Make sure there are no type name conflicts.
881*361e513dSReid Spencer   //
882*361e513dSReid Spencer   if (LinkTypes(Dest, Src, ErrorMsg)) return true;
883*361e513dSReid Spencer 
884*361e513dSReid Spencer   // ValueMap - Mapping of values from what they used to be in Src, to what they
885*361e513dSReid Spencer   // are now in Dest.
886*361e513dSReid Spencer   //
887*361e513dSReid Spencer   std::map<const Value*, Value*> ValueMap;
888*361e513dSReid Spencer 
889*361e513dSReid Spencer   // AppendingVars - Keep track of global variables in the destination module
890*361e513dSReid Spencer   // with appending linkage.  After the module is linked together, they are
891*361e513dSReid Spencer   // appended and the module is rewritten.
892*361e513dSReid Spencer   //
893*361e513dSReid Spencer   std::multimap<std::string, GlobalVariable *> AppendingVars;
894*361e513dSReid Spencer 
895*361e513dSReid Spencer   // GlobalsByName - The LLVM SymbolTable class fights our best efforts at
896*361e513dSReid Spencer   // linking by separating globals by type.  Until PR411 is fixed, we replicate
897*361e513dSReid Spencer   // it's functionality here.
898*361e513dSReid Spencer   std::map<std::string, GlobalValue*> GlobalsByName;
899*361e513dSReid Spencer 
900*361e513dSReid Spencer   for (Module::giterator I = Dest->gbegin(), E = Dest->gend(); I != E; ++I) {
901*361e513dSReid Spencer     // Add all of the appending globals already in the Dest module to
902*361e513dSReid Spencer     // AppendingVars.
903*361e513dSReid Spencer     if (I->hasAppendingLinkage())
904*361e513dSReid Spencer       AppendingVars.insert(std::make_pair(I->getName(), I));
905*361e513dSReid Spencer 
906*361e513dSReid Spencer     // Keep track of all globals by name.
907*361e513dSReid Spencer     if (!I->hasInternalLinkage() && I->hasName())
908*361e513dSReid Spencer       GlobalsByName[I->getName()] = I;
909*361e513dSReid Spencer   }
910*361e513dSReid Spencer 
911*361e513dSReid Spencer   // Keep track of all globals by name.
912*361e513dSReid Spencer   for (Module::iterator I = Dest->begin(), E = Dest->end(); I != E; ++I)
913*361e513dSReid Spencer     if (!I->hasInternalLinkage() && I->hasName())
914*361e513dSReid Spencer       GlobalsByName[I->getName()] = I;
915*361e513dSReid Spencer 
916*361e513dSReid Spencer   // Insert all of the globals in src into the Dest module... without linking
917*361e513dSReid Spencer   // initializers (which could refer to functions not yet mapped over).
918*361e513dSReid Spencer   //
919*361e513dSReid Spencer   if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, GlobalsByName, ErrorMsg))
920*361e513dSReid Spencer     return true;
921*361e513dSReid Spencer 
922*361e513dSReid Spencer   // Link the functions together between the two modules, without doing function
923*361e513dSReid Spencer   // bodies... this just adds external function prototypes to the Dest
924*361e513dSReid Spencer   // function...  We do this so that when we begin processing function bodies,
925*361e513dSReid Spencer   // all of the global values that may be referenced are available in our
926*361e513dSReid Spencer   // ValueMap.
927*361e513dSReid Spencer   //
928*361e513dSReid Spencer   if (LinkFunctionProtos(Dest, Src, ValueMap, GlobalsByName, ErrorMsg))
929*361e513dSReid Spencer     return true;
930*361e513dSReid Spencer 
931*361e513dSReid Spencer   // Update the initializers in the Dest module now that all globals that may
932*361e513dSReid Spencer   // be referenced are in Dest.
933*361e513dSReid Spencer   //
934*361e513dSReid Spencer   if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
935*361e513dSReid Spencer 
936*361e513dSReid Spencer   // Link in the function bodies that are defined in the source module into the
937*361e513dSReid Spencer   // DestModule.  This consists basically of copying the function over and
938*361e513dSReid Spencer   // fixing up references to values.
939*361e513dSReid Spencer   //
940*361e513dSReid Spencer   if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
941*361e513dSReid Spencer 
942*361e513dSReid Spencer   // If there were any appending global variables, link them together now.
943*361e513dSReid Spencer   //
944*361e513dSReid Spencer   if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
945*361e513dSReid Spencer 
946*361e513dSReid Spencer   // If the source library's module id is in the dependent library list of the
947*361e513dSReid Spencer   // destination library, remove it since that module is now linked in.
948*361e513dSReid Spencer   sys::Path modId;
949*361e513dSReid Spencer   modId.setFile(Src->getModuleIdentifier());
950*361e513dSReid Spencer   if (!modId.isEmpty())
951*361e513dSReid Spencer     Dest->removeLibrary(modId.getBasename());
952*361e513dSReid Spencer 
953*361e513dSReid Spencer   return false;
954*361e513dSReid Spencer }
955*361e513dSReid Spencer 
956*361e513dSReid Spencer // vim: sw=2
957