Link symbols with different visibilities according to the rules in the
[oota-llvm.git] / lib / Linker / LinkModules.cpp
1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the LLVM module linker.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Linker.h"
15 #include "llvm/Constants.h"
16 #include "llvm/DerivedTypes.h"
17 #include "llvm/Instructions.h"
18 #include "llvm/Module.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/Support/raw_ostream.h"
22 #include "llvm/Support/Path.h"
23 #include "llvm/Transforms/Utils/Cloning.h"
24 #include "llvm/Transforms/Utils/ValueMapper.h"
25 using namespace llvm;
26
27 //===----------------------------------------------------------------------===//
28 // TypeMap implementation.
29 //===----------------------------------------------------------------------===//
30
31 namespace {
32 class TypeMapTy : public ValueMapTypeRemapper {
33   /// MappedTypes - This is a mapping from a source type to a destination type
34   /// to use.
35   DenseMap<Type*, Type*> MappedTypes;
36
37   /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
38   /// we speculatively add types to MappedTypes, but keep track of them here in
39   /// case we need to roll back.
40   SmallVector<Type*, 16> SpeculativeTypes;
41   
42   /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
43   /// source module that are mapped to an opaque struct in the destination
44   /// module.
45   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
46   
47   /// DstResolvedOpaqueTypes - This is the set of opaque types in the
48   /// destination modules who are getting a body from the source module.
49   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
50 public:
51   
52   /// addTypeMapping - Indicate that the specified type in the destination
53   /// module is conceptually equivalent to the specified type in the source
54   /// module.
55   void addTypeMapping(Type *DstTy, Type *SrcTy);
56
57   /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
58   /// module from a type definition in the source module.
59   void linkDefinedTypeBodies();
60   
61   /// get - Return the mapped type to use for the specified input type from the
62   /// source module.
63   Type *get(Type *SrcTy);
64
65   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
66
67 private:
68   Type *getImpl(Type *T);
69   /// remapType - Implement the ValueMapTypeRemapper interface.
70   Type *remapType(Type *SrcTy) {
71     return get(SrcTy);
72   }
73   
74   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
75 };
76 }
77
78 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
79   Type *&Entry = MappedTypes[SrcTy];
80   if (Entry) return;
81   
82   if (DstTy == SrcTy) {
83     Entry = DstTy;
84     return;
85   }
86   
87   // Check to see if these types are recursively isomorphic and establish a
88   // mapping between them if so.
89   if (!areTypesIsomorphic(DstTy, SrcTy)) {
90     // Oops, they aren't isomorphic.  Just discard this request by rolling out
91     // any speculative mappings we've established.
92     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
93       MappedTypes.erase(SpeculativeTypes[i]);
94   }
95   SpeculativeTypes.clear();
96 }
97
98 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
99 /// if they are isomorphic, false if they are not.
100 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
101   // Two types with differing kinds are clearly not isomorphic.
102   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
103
104   // If we have an entry in the MappedTypes table, then we have our answer.
105   Type *&Entry = MappedTypes[SrcTy];
106   if (Entry)
107     return Entry == DstTy;
108
109   // Two identical types are clearly isomorphic.  Remember this
110   // non-speculatively.
111   if (DstTy == SrcTy) {
112     Entry = DstTy;
113     return true;
114   }
115   
116   // Okay, we have two types with identical kinds that we haven't seen before.
117
118   // If this is an opaque struct type, special case it.
119   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
120     // Mapping an opaque type to any struct, just keep the dest struct.
121     if (SSTy->isOpaque()) {
122       Entry = DstTy;
123       SpeculativeTypes.push_back(SrcTy);
124       return true;
125     }
126
127     // Mapping a non-opaque source type to an opaque dest.  If this is the first
128     // type that we're mapping onto this destination type then we succeed.  Keep
129     // the dest, but fill it in later.  This doesn't need to be speculative.  If
130     // this is the second (different) type that we're trying to map onto the
131     // same opaque type then we fail.
132     if (cast<StructType>(DstTy)->isOpaque()) {
133       // We can only map one source type onto the opaque destination type.
134       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
135         return false;
136       SrcDefinitionsToResolve.push_back(SSTy);
137       Entry = DstTy;
138       return true;
139     }
140   }
141   
142   // If the number of subtypes disagree between the two types, then we fail.
143   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
144     return false;
145   
146   // Fail if any of the extra properties (e.g. array size) of the type disagree.
147   if (isa<IntegerType>(DstTy))
148     return false;  // bitwidth disagrees.
149   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
150     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
151       return false;
152     
153   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
154     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
155       return false;
156   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
157     StructType *SSTy = cast<StructType>(SrcTy);
158     if (DSTy->isLiteral() != SSTy->isLiteral() ||
159         DSTy->isPacked() != SSTy->isPacked())
160       return false;
161   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
162     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
163       return false;
164   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
165     if (DVTy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
166       return false;
167   }
168
169   // Otherwise, we speculate that these two types will line up and recursively
170   // check the subelements.
171   Entry = DstTy;
172   SpeculativeTypes.push_back(SrcTy);
173
174   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
175     if (!areTypesIsomorphic(DstTy->getContainedType(i),
176                             SrcTy->getContainedType(i)))
177       return false;
178   
179   // If everything seems to have lined up, then everything is great.
180   return true;
181 }
182
183 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
184 /// module from a type definition in the source module.
185 void TypeMapTy::linkDefinedTypeBodies() {
186   SmallVector<Type*, 16> Elements;
187   SmallString<16> TmpName;
188   
189   // Note that processing entries in this loop (calling 'get') can add new
190   // entries to the SrcDefinitionsToResolve vector.
191   while (!SrcDefinitionsToResolve.empty()) {
192     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
193     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
194     
195     // TypeMap is a many-to-one mapping, if there were multiple types that
196     // provide a body for DstSTy then previous iterations of this loop may have
197     // already handled it.  Just ignore this case.
198     if (!DstSTy->isOpaque()) continue;
199     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
200     
201     // Map the body of the source type over to a new body for the dest type.
202     Elements.resize(SrcSTy->getNumElements());
203     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
204       Elements[i] = getImpl(SrcSTy->getElementType(i));
205     
206     DstSTy->setBody(Elements, SrcSTy->isPacked());
207     
208     // If DstSTy has no name or has a longer name than STy, then viciously steal
209     // STy's name.
210     if (!SrcSTy->hasName()) continue;
211     StringRef SrcName = SrcSTy->getName();
212     
213     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
214       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
215       SrcSTy->setName("");
216       DstSTy->setName(TmpName.str());
217       TmpName.clear();
218     }
219   }
220   
221   DstResolvedOpaqueTypes.clear();
222 }
223
224
225 /// get - Return the mapped type to use for the specified input type from the
226 /// source module.
227 Type *TypeMapTy::get(Type *Ty) {
228   Type *Result = getImpl(Ty);
229   
230   // If this caused a reference to any struct type, resolve it before returning.
231   if (!SrcDefinitionsToResolve.empty())
232     linkDefinedTypeBodies();
233   return Result;
234 }
235
236 /// getImpl - This is the recursive version of get().
237 Type *TypeMapTy::getImpl(Type *Ty) {
238   // If we already have an entry for this type, return it.
239   Type **Entry = &MappedTypes[Ty];
240   if (*Entry) return *Entry;
241   
242   // If this is not a named struct type, then just map all of the elements and
243   // then rebuild the type from inside out.
244   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
245     // If there are no element types to map, then the type is itself.  This is
246     // true for the anonymous {} struct, things like 'float', integers, etc.
247     if (Ty->getNumContainedTypes() == 0)
248       return *Entry = Ty;
249     
250     // Remap all of the elements, keeping track of whether any of them change.
251     bool AnyChange = false;
252     SmallVector<Type*, 4> ElementTypes;
253     ElementTypes.resize(Ty->getNumContainedTypes());
254     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
255       ElementTypes[i] = getImpl(Ty->getContainedType(i));
256       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
257     }
258     
259     // If we found our type while recursively processing stuff, just use it.
260     Entry = &MappedTypes[Ty];
261     if (*Entry) return *Entry;
262     
263     // If all of the element types mapped directly over, then the type is usable
264     // as-is.
265     if (!AnyChange)
266       return *Entry = Ty;
267     
268     // Otherwise, rebuild a modified type.
269     switch (Ty->getTypeID()) {
270     default: assert(0 && "unknown derived type to remap");
271     case Type::ArrayTyID:
272       return *Entry = ArrayType::get(ElementTypes[0],
273                                      cast<ArrayType>(Ty)->getNumElements());
274     case Type::VectorTyID: 
275       return *Entry = VectorType::get(ElementTypes[0],
276                                       cast<VectorType>(Ty)->getNumElements());
277     case Type::PointerTyID:
278       return *Entry = PointerType::get(ElementTypes[0],
279                                       cast<PointerType>(Ty)->getAddressSpace());
280     case Type::FunctionTyID:
281       return *Entry = FunctionType::get(ElementTypes[0],
282                                         makeArrayRef(ElementTypes).slice(1),
283                                         cast<FunctionType>(Ty)->isVarArg());
284     case Type::StructTyID:
285       // Note that this is only reached for anonymous structs.
286       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
287                                       cast<StructType>(Ty)->isPacked());
288     }
289   }
290
291   // Otherwise, this is an unmapped named struct.  If the struct can be directly
292   // mapped over, just use it as-is.  This happens in a case when the linked-in
293   // module has something like:
294   //   %T = type {%T*, i32}
295   //   @GV = global %T* null
296   // where T does not exist at all in the destination module.
297   //
298   // The other case we watch for is when the type is not in the destination
299   // module, but that it has to be rebuilt because it refers to something that
300   // is already mapped.  For example, if the destination module has:
301   //  %A = type { i32 }
302   // and the source module has something like
303   //  %A' = type { i32 }
304   //  %B = type { %A'* }
305   //  @GV = global %B* null
306   // then we want to create a new type: "%B = type { %A*}" and have it take the
307   // pristine "%B" name from the source module.
308   //
309   // To determine which case this is, we have to recursively walk the type graph
310   // speculating that we'll be able to reuse it unmodified.  Only if this is
311   // safe would we map the entire thing over.  Because this is an optimization,
312   // and is not required for the prettiness of the linked module, we just skip
313   // it and always rebuild a type here.
314   StructType *STy = cast<StructType>(Ty);
315   
316   // If the type is opaque, we can just use it directly.
317   if (STy->isOpaque())
318     return *Entry = STy;
319   
320   // Otherwise we create a new type and resolve its body later.  This will be
321   // resolved by the top level of get().
322   SrcDefinitionsToResolve.push_back(STy);
323   StructType *DTy = StructType::create(STy->getContext());
324   DstResolvedOpaqueTypes.insert(DTy);
325   return *Entry = DTy;
326 }
327
328
329
330 //===----------------------------------------------------------------------===//
331 // ModuleLinker implementation.
332 //===----------------------------------------------------------------------===//
333
334 namespace {
335   /// ModuleLinker - This is an implementation class for the LinkModules
336   /// function, which is the entrypoint for this file.
337   class ModuleLinker {
338     Module *DstM, *SrcM;
339     
340     TypeMapTy TypeMap; 
341
342     /// ValueMap - Mapping of values from what they used to be in Src, to what
343     /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
344     /// some overhead due to the use of Value handles which the Linker doesn't
345     /// actually need, but this allows us to reuse the ValueMapper code.
346     ValueToValueMapTy ValueMap;
347     
348     struct AppendingVarInfo {
349       GlobalVariable *NewGV;  // New aggregate global in dest module.
350       Constant *DstInit;      // Old initializer from dest module.
351       Constant *SrcInit;      // Old initializer from src module.
352     };
353     
354     std::vector<AppendingVarInfo> AppendingVars;
355     
356     unsigned Mode; // Mode to treat source module.
357     
358     // Set of items not to link in from source.
359     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
360     
361     // Vector of functions to lazily link in.
362     std::vector<Function*> LazilyLinkFunctions;
363     
364   public:
365     std::string ErrorMsg;
366     
367     ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
368       : DstM(dstM), SrcM(srcM), Mode(mode) { }
369     
370     bool run();
371     
372   private:
373     /// emitError - Helper method for setting a message and returning an error
374     /// code.
375     bool emitError(const Twine &Message) {
376       ErrorMsg = Message.str();
377       return true;
378     }
379     
380     /// getLinkageResult - This analyzes the two global values and determines
381     /// what the result will look like in the destination module.
382     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
383                           GlobalValue::LinkageTypes &LT,
384                           GlobalValue::VisibilityTypes &Vis,
385                           bool &LinkFromSrc);
386
387     /// getLinkedToGlobal - Given a global in the source module, return the
388     /// global in the destination module that is being linked to, if any.
389     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
390       // If the source has no name it can't link.  If it has local linkage,
391       // there is no name match-up going on.
392       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
393         return 0;
394       
395       // Otherwise see if we have a match in the destination module's symtab.
396       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
397       if (DGV == 0) return 0;
398         
399       // If we found a global with the same name in the dest module, but it has
400       // internal linkage, we are really not doing any linkage here.
401       if (DGV->hasLocalLinkage())
402         return 0;
403
404       // Otherwise, we do in fact link to the destination global.
405       return DGV;
406     }
407     
408     void computeTypeMapping();
409     
410     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
411     bool linkGlobalProto(GlobalVariable *SrcGV);
412     bool linkFunctionProto(Function *SrcF);
413     bool linkAliasProto(GlobalAlias *SrcA);
414     
415     void linkAppendingVarInit(const AppendingVarInfo &AVI);
416     void linkGlobalInits();
417     void linkFunctionBody(Function *Dst, Function *Src);
418     void linkAliasBodies();
419     void linkNamedMDNodes();
420   };
421 }
422
423
424
425 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
426 /// in the symbol table.  This is good for all clients except for us.  Go
427 /// through the trouble to force this back.
428 static void forceRenaming(GlobalValue *GV, StringRef Name) {
429   // If the global doesn't force its name or if it already has the right name,
430   // there is nothing for us to do.
431   if (GV->hasLocalLinkage() || GV->getName() == Name)
432     return;
433
434   Module *M = GV->getParent();
435
436   // If there is a conflict, rename the conflict.
437   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
438     GV->takeName(ConflictGV);
439     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
440     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
441   } else {
442     GV->setName(Name);              // Force the name back
443   }
444 }
445
446 /// CopyGVAttributes - copy additional attributes (those not needed to construct
447 /// a GlobalValue) from the SrcGV to the DestGV.
448 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
449   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
450   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
451   DestGV->copyAttributesFrom(SrcGV);
452   DestGV->setAlignment(Alignment);
453   
454   forceRenaming(DestGV, SrcGV->getName());
455 }
456
457 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
458                                GlobalValue::VisibilityTypes b) {
459   if (a == GlobalValue::HiddenVisibility)
460     return false;
461   if (b == GlobalValue::HiddenVisibility)
462     return true;
463   if (a == GlobalValue::ProtectedVisibility)
464     return false;
465   if (b == GlobalValue::ProtectedVisibility)
466     return true;
467   return false;
468 }
469
470 /// getLinkageResult - This analyzes the two global values and determines what
471 /// the result will look like in the destination module.  In particular, it
472 /// computes the resultant linkage type and visibility, computes whether the
473 /// global in the source should be copied over to the destination (replacing
474 /// the existing one), and computes whether this linkage is an error or not.
475 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
476                                     GlobalValue::LinkageTypes &LT,
477                                     GlobalValue::VisibilityTypes &Vis,
478                                     bool &LinkFromSrc) {
479   assert(Dest && "Must have two globals being queried");
480   assert(!Src->hasLocalLinkage() &&
481          "If Src has internal linkage, Dest shouldn't be set!");
482   
483   bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
484   bool DestIsDeclaration = Dest->isDeclaration();
485   
486   if (SrcIsDeclaration) {
487     // If Src is external or if both Src & Dest are external..  Just link the
488     // external globals, we aren't adding anything.
489     if (Src->hasDLLImportLinkage()) {
490       // If one of GVs has DLLImport linkage, result should be dllimport'ed.
491       if (DestIsDeclaration) {
492         LinkFromSrc = true;
493         LT = Src->getLinkage();
494       }
495     } else if (Dest->hasExternalWeakLinkage()) {
496       // If the Dest is weak, use the source linkage.
497       LinkFromSrc = true;
498       LT = Src->getLinkage();
499     } else {
500       LinkFromSrc = false;
501       LT = Dest->getLinkage();
502     }
503   } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
504     // If Dest is external but Src is not:
505     LinkFromSrc = true;
506     LT = Src->getLinkage();
507   } else if (Src->isWeakForLinker()) {
508     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
509     // or DLL* linkage.
510     if (Dest->hasExternalWeakLinkage() ||
511         Dest->hasAvailableExternallyLinkage() ||
512         (Dest->hasLinkOnceLinkage() &&
513          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
514       LinkFromSrc = true;
515       LT = Src->getLinkage();
516     } else {
517       LinkFromSrc = false;
518       LT = Dest->getLinkage();
519     }
520   } else if (Dest->isWeakForLinker()) {
521     // At this point we know that Src has External* or DLL* linkage.
522     if (Src->hasExternalWeakLinkage()) {
523       LinkFromSrc = false;
524       LT = Dest->getLinkage();
525     } else {
526       LinkFromSrc = true;
527       LT = GlobalValue::ExternalLinkage;
528     }
529   } else {
530     assert((Dest->hasExternalLinkage()  || Dest->hasDLLImportLinkage() ||
531             Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
532            (Src->hasExternalLinkage()   || Src->hasDLLImportLinkage() ||
533             Src->hasDLLExportLinkage()  || Src->hasExternalWeakLinkage()) &&
534            "Unexpected linkage type!");
535     return emitError("Linking globals named '" + Src->getName() +
536                  "': symbol multiply defined!");
537   }
538
539   // Compute the visibility. We follow the rules in the System V Application
540   // Binary Interface.
541   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
542     Dest->getVisibility() : Src->getVisibility();
543   return false;
544 }
545
546 /// computeTypeMapping - Loop over all of the linked values to compute type
547 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
548 /// we have two struct types 'Foo' but one got renamed when the module was
549 /// loaded into the same LLVMContext.
550 void ModuleLinker::computeTypeMapping() {
551   // Incorporate globals.
552   for (Module::global_iterator I = SrcM->global_begin(),
553        E = SrcM->global_end(); I != E; ++I) {
554     GlobalValue *DGV = getLinkedToGlobal(I);
555     if (DGV == 0) continue;
556     
557     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
558       TypeMap.addTypeMapping(DGV->getType(), I->getType());
559       continue;      
560     }
561     
562     // Unify the element type of appending arrays.
563     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
564     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
565     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
566   }
567   
568   // Incorporate functions.
569   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
570     if (GlobalValue *DGV = getLinkedToGlobal(I))
571       TypeMap.addTypeMapping(DGV->getType(), I->getType());
572   }
573   
574   // Incorporate types by name, scanning all the types in the source module.
575   // At this point, the destination module may have a type "%foo = { i32 }" for
576   // example.  When the source module got loaded into the same LLVMContext, if
577   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
578   // Though it isn't required for correctness, attempt to link these up to clean
579   // up the IR.
580   std::vector<StructType*> SrcStructTypes;
581   SrcM->findUsedStructTypes(SrcStructTypes);
582   
583   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
584                                                  SrcStructTypes.end());
585   
586   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
587     StructType *ST = SrcStructTypes[i];
588     if (!ST->hasName()) continue;
589     
590     // Check to see if there is a dot in the name followed by a digit.
591     size_t DotPos = ST->getName().rfind('.');
592     if (DotPos == 0 || DotPos == StringRef::npos ||
593         ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
594       continue;
595     
596     // Check to see if the destination module has a struct with the prefix name.
597     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
598       // Don't use it if this actually came from the source module.  They're in
599       // the same LLVMContext after all.
600       if (!SrcStructTypesSet.count(DST))
601         TypeMap.addTypeMapping(DST, ST);
602   }
603   
604   
605   // Don't bother incorporating aliases, they aren't generally typed well.
606   
607   // Now that we have discovered all of the type equivalences, get a body for
608   // any 'opaque' types in the dest module that are now resolved. 
609   TypeMap.linkDefinedTypeBodies();
610 }
611
612 /// linkAppendingVarProto - If there were any appending global variables, link
613 /// them together now.  Return true on error.
614 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
615                                          GlobalVariable *SrcGV) {
616  
617   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
618     return emitError("Linking globals named '" + SrcGV->getName() +
619            "': can only link appending global with another appending global!");
620   
621   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
622   ArrayType *SrcTy =
623     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
624   Type *EltTy = DstTy->getElementType();
625   
626   // Check to see that they two arrays agree on type.
627   if (EltTy != SrcTy->getElementType())
628     return emitError("Appending variables with different element types!");
629   if (DstGV->isConstant() != SrcGV->isConstant())
630     return emitError("Appending variables linked with different const'ness!");
631   
632   if (DstGV->getAlignment() != SrcGV->getAlignment())
633     return emitError(
634              "Appending variables with different alignment need to be linked!");
635   
636   if (DstGV->getVisibility() != SrcGV->getVisibility())
637     return emitError(
638             "Appending variables with different visibility need to be linked!");
639   
640   if (DstGV->getSection() != SrcGV->getSection())
641     return emitError(
642           "Appending variables with different section name need to be linked!");
643   
644   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
645   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
646   
647   // Create the new global variable.
648   GlobalVariable *NG =
649     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
650                        DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
651                        DstGV->isThreadLocal(),
652                        DstGV->getType()->getAddressSpace());
653   
654   // Propagate alignment, visibility and section info.
655   CopyGVAttributes(NG, DstGV);
656   
657   AppendingVarInfo AVI;
658   AVI.NewGV = NG;
659   AVI.DstInit = DstGV->getInitializer();
660   AVI.SrcInit = SrcGV->getInitializer();
661   AppendingVars.push_back(AVI);
662
663   // Replace any uses of the two global variables with uses of the new
664   // global.
665   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
666
667   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
668   DstGV->eraseFromParent();
669   
670   // Track the source variable so we don't try to link it.
671   DoNotLinkFromSource.insert(SrcGV);
672   
673   return false;
674 }
675
676 /// linkGlobalProto - Loop through the global variables in the src module and
677 /// merge them into the dest module.
678 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
679   GlobalValue *DGV = getLinkedToGlobal(SGV);
680   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
681
682   if (DGV) {
683     // Concatenation of appending linkage variables is magic and handled later.
684     if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
685       return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
686     
687     // Determine whether linkage of these two globals follows the source
688     // module's definition or the destination module's definition.
689     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
690     GlobalValue::VisibilityTypes NV;
691     bool LinkFromSrc = false;
692     if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
693       return true;
694     NewVisibility = NV;
695
696     // If we're not linking from the source, then keep the definition that we
697     // have.
698     if (!LinkFromSrc) {
699       // Special case for const propagation.
700       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
701         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
702           DGVar->setConstant(true);
703       
704       // Set calculated linkage and visibility.
705       DGV->setLinkage(NewLinkage);
706       DGV->setVisibility(*NewVisibility);
707
708       // Make sure to remember this mapping.
709       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
710       
711       // Track the source global so that we don't attempt to copy it over when 
712       // processing global initializers.
713       DoNotLinkFromSource.insert(SGV);
714       
715       return false;
716     }
717   }
718   
719   // No linking to be performed or linking from the source: simply create an
720   // identical version of the symbol over in the dest module... the
721   // initializer will be filled in later by LinkGlobalInits.
722   GlobalVariable *NewDGV =
723     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
724                        SGV->isConstant(), SGV->getLinkage(), /*init*/0,
725                        SGV->getName(), /*insertbefore*/0,
726                        SGV->isThreadLocal(),
727                        SGV->getType()->getAddressSpace());
728   // Propagate alignment, visibility and section info.
729   CopyGVAttributes(NewDGV, SGV);
730   if (NewVisibility)
731     NewDGV->setVisibility(*NewVisibility);
732
733   if (DGV) {
734     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
735     DGV->eraseFromParent();
736   }
737   
738   // Make sure to remember this mapping.
739   ValueMap[SGV] = NewDGV;
740   return false;
741 }
742
743 /// linkFunctionProto - Link the function in the source module into the
744 /// destination module if needed, setting up mapping information.
745 bool ModuleLinker::linkFunctionProto(Function *SF) {
746   GlobalValue *DGV = getLinkedToGlobal(SF);
747   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
748
749   if (DGV) {
750     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
751     bool LinkFromSrc = false;
752     GlobalValue::VisibilityTypes NV;
753     if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
754       return true;
755     NewVisibility = NV;
756
757     if (!LinkFromSrc) {
758       // Set calculated linkage
759       DGV->setLinkage(NewLinkage);
760       DGV->setVisibility(*NewVisibility);
761
762       // Make sure to remember this mapping.
763       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
764       
765       // Track the function from the source module so we don't attempt to remap 
766       // it.
767       DoNotLinkFromSource.insert(SF);
768       
769       return false;
770     }
771   }
772   
773   // If there is no linkage to be performed or we are linking from the source,
774   // bring SF over.
775   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
776                                      SF->getLinkage(), SF->getName(), DstM);
777   CopyGVAttributes(NewDF, SF);
778   if (NewVisibility)
779     NewDF->setVisibility(*NewVisibility);
780
781   if (DGV) {
782     // Any uses of DF need to change to NewDF, with cast.
783     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
784     DGV->eraseFromParent();
785   } else {
786     // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
787     if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
788         SF->hasAvailableExternallyLinkage()) {
789       DoNotLinkFromSource.insert(SF);
790       LazilyLinkFunctions.push_back(SF);
791     }
792   }
793   
794   ValueMap[SF] = NewDF;
795   return false;
796 }
797
798 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
799 /// source module.
800 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
801   GlobalValue *DGV = getLinkedToGlobal(SGA);
802   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
803
804   if (DGV) {
805     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
806     GlobalValue::VisibilityTypes NV;
807     bool LinkFromSrc = false;
808     if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
809       return true;
810     NewVisibility = NV;
811
812     if (!LinkFromSrc) {
813       // Set calculated linkage.
814       DGV->setLinkage(NewLinkage);
815       DGV->setVisibility(*NewVisibility);
816
817       // Make sure to remember this mapping.
818       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
819       
820       // Track the alias from the source module so we don't attempt to remap it.
821       DoNotLinkFromSource.insert(SGA);
822       
823       return false;
824     }
825   }
826   
827   // If there is no linkage to be performed or we're linking from the source,
828   // bring over SGA.
829   GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
830                                        SGA->getLinkage(), SGA->getName(),
831                                        /*aliasee*/0, DstM);
832   CopyGVAttributes(NewDA, SGA);
833   if (NewVisibility)
834     NewDA->setVisibility(*NewVisibility);
835
836   if (DGV) {
837     // Any uses of DGV need to change to NewDA, with cast.
838     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
839     DGV->eraseFromParent();
840   }
841   
842   ValueMap[SGA] = NewDA;
843   return false;
844 }
845
846 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
847   // Merge the initializer.
848   SmallVector<Constant*, 16> Elements;
849   if (ConstantArray *I = dyn_cast<ConstantArray>(AVI.DstInit)) {
850     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
851       Elements.push_back(I->getOperand(i));
852   } else {
853     assert(isa<ConstantAggregateZero>(AVI.DstInit));
854     ArrayType *DstAT = cast<ArrayType>(AVI.DstInit->getType());
855     Type *EltTy = DstAT->getElementType();
856     Elements.append(DstAT->getNumElements(), Constant::getNullValue(EltTy));
857   }
858   
859   Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
860   if (const ConstantArray *I = dyn_cast<ConstantArray>(SrcInit)) {
861     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
862       Elements.push_back(I->getOperand(i));
863   } else {
864     assert(isa<ConstantAggregateZero>(SrcInit));
865     ArrayType *SrcAT = cast<ArrayType>(SrcInit->getType());
866     Type *EltTy = SrcAT->getElementType();
867     Elements.append(SrcAT->getNumElements(), Constant::getNullValue(EltTy));
868   }
869   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
870   AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
871 }
872
873
874 // linkGlobalInits - Update the initializers in the Dest module now that all
875 // globals that may be referenced are in Dest.
876 void ModuleLinker::linkGlobalInits() {
877   // Loop over all of the globals in the src module, mapping them over as we go
878   for (Module::const_global_iterator I = SrcM->global_begin(),
879        E = SrcM->global_end(); I != E; ++I) {
880     
881     // Only process initialized GV's or ones not already in dest.
882     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;          
883     
884     // Grab destination global variable.
885     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
886     // Figure out what the initializer looks like in the dest module.
887     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
888                                  RF_None, &TypeMap));
889   }
890 }
891
892 // linkFunctionBody - Copy the source function over into the dest function and
893 // fix up references to values.  At this point we know that Dest is an external
894 // function, and that Src is not.
895 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
896   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
897
898   // Go through and convert function arguments over, remembering the mapping.
899   Function::arg_iterator DI = Dst->arg_begin();
900   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
901        I != E; ++I, ++DI) {
902     DI->setName(I->getName());  // Copy the name over.
903
904     // Add a mapping to our mapping.
905     ValueMap[I] = DI;
906   }
907
908   if (Mode == Linker::DestroySource) {
909     // Splice the body of the source function into the dest function.
910     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
911     
912     // At this point, all of the instructions and values of the function are now
913     // copied over.  The only problem is that they are still referencing values in
914     // the Source function as operands.  Loop through all of the operands of the
915     // functions and patch them up to point to the local versions.
916     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
917       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
918         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
919     
920   } else {
921     // Clone the body of the function into the dest function.
922     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
923     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
924   }
925   
926   // There is no need to map the arguments anymore.
927   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
928        I != E; ++I)
929     ValueMap.erase(I);
930   
931 }
932
933
934 void ModuleLinker::linkAliasBodies() {
935   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
936        I != E; ++I) {
937     if (DoNotLinkFromSource.count(I))
938       continue;
939     if (Constant *Aliasee = I->getAliasee()) {
940       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
941       DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
942     }
943   }
944 }
945
946 /// linkNamedMDNodes - Insert all of the named mdnodes in Src into the Dest
947 /// module.
948 void ModuleLinker::linkNamedMDNodes() {
949   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
950        E = SrcM->named_metadata_end(); I != E; ++I) {
951     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
952     // Add Src elements into Dest node.
953     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
954       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
955                                    RF_None, &TypeMap));
956   }
957 }
958   
959 bool ModuleLinker::run() {
960   assert(DstM && "Null Destination module");
961   assert(SrcM && "Null Source Module");
962
963   // Inherit the target data from the source module if the destination module
964   // doesn't have one already.
965   if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
966     DstM->setDataLayout(SrcM->getDataLayout());
967
968   // Copy the target triple from the source to dest if the dest's is empty.
969   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
970     DstM->setTargetTriple(SrcM->getTargetTriple());
971
972   if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
973       SrcM->getDataLayout() != DstM->getDataLayout())
974     errs() << "WARNING: Linking two modules of different data layouts!\n";
975   if (!SrcM->getTargetTriple().empty() &&
976       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
977     errs() << "WARNING: Linking two modules of different target triples: ";
978     if (!SrcM->getModuleIdentifier().empty())
979       errs() << SrcM->getModuleIdentifier() << ": ";
980     errs() << "'" << SrcM->getTargetTriple() << "' and '" 
981            << DstM->getTargetTriple() << "'\n";
982   }
983
984   // Append the module inline asm string.
985   if (!SrcM->getModuleInlineAsm().empty()) {
986     if (DstM->getModuleInlineAsm().empty())
987       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
988     else
989       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
990                                SrcM->getModuleInlineAsm());
991   }
992
993   // Update the destination module's dependent libraries list with the libraries
994   // from the source module. There's no opportunity for duplicates here as the
995   // Module ensures that duplicate insertions are discarded.
996   for (Module::lib_iterator SI = SrcM->lib_begin(), SE = SrcM->lib_end();
997        SI != SE; ++SI)
998     DstM->addLibrary(*SI);
999   
1000   // If the source library's module id is in the dependent library list of the
1001   // destination library, remove it since that module is now linked in.
1002   StringRef ModuleId = SrcM->getModuleIdentifier();
1003   if (!ModuleId.empty())
1004     DstM->removeLibrary(sys::path::stem(ModuleId));
1005   
1006   // Loop over all of the linked values to compute type mappings.
1007   computeTypeMapping();
1008
1009   // Insert all of the globals in src into the DstM module... without linking
1010   // initializers (which could refer to functions not yet mapped over).
1011   for (Module::global_iterator I = SrcM->global_begin(),
1012        E = SrcM->global_end(); I != E; ++I)
1013     if (linkGlobalProto(I))
1014       return true;
1015
1016   // Link the functions together between the two modules, without doing function
1017   // bodies... this just adds external function prototypes to the DstM
1018   // function...  We do this so that when we begin processing function bodies,
1019   // all of the global values that may be referenced are available in our
1020   // ValueMap.
1021   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1022     if (linkFunctionProto(I))
1023       return true;
1024
1025   // If there were any aliases, link them now.
1026   for (Module::alias_iterator I = SrcM->alias_begin(),
1027        E = SrcM->alias_end(); I != E; ++I)
1028     if (linkAliasProto(I))
1029       return true;
1030
1031   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1032     linkAppendingVarInit(AppendingVars[i]);
1033   
1034   // Update the initializers in the DstM module now that all globals that may
1035   // be referenced are in DstM.
1036   linkGlobalInits();
1037
1038   // Link in the function bodies that are defined in the source module into
1039   // DstM.
1040   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1041     
1042     // Skip if not linking from source.
1043     if (DoNotLinkFromSource.count(SF)) continue;
1044     
1045     // Skip if no body (function is external) or materialize.
1046     if (SF->isDeclaration()) {
1047       if (!SF->isMaterializable())
1048         continue;
1049       if (SF->Materialize(&ErrorMsg))
1050         return true;
1051     }
1052     
1053     linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1054   }
1055
1056   // Resolve all uses of aliases with aliasees.
1057   linkAliasBodies();
1058
1059   // Remap all of the named mdnoes in Src into the DstM module. We do this
1060   // after linking GlobalValues so that MDNodes that reference GlobalValues
1061   // are properly remapped.
1062   linkNamedMDNodes();
1063
1064   // Process vector of lazily linked in functions.
1065   bool LinkedInAnyFunctions;
1066   do {
1067     LinkedInAnyFunctions = false;
1068     
1069     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1070         E = LazilyLinkFunctions.end(); I != E; ++I) {
1071       if (!*I)
1072         continue;
1073       
1074       Function *SF = *I;
1075       Function *DF = cast<Function>(ValueMap[SF]);
1076       
1077       if (!DF->use_empty()) {
1078         
1079         // Materialize if necessary.
1080         if (SF->isDeclaration()) {
1081           if (!SF->isMaterializable())
1082             continue;
1083           if (SF->Materialize(&ErrorMsg))
1084             return true;
1085         }
1086         
1087         // Link in function body.
1088         linkFunctionBody(DF, SF);
1089         
1090         // "Remove" from vector by setting the element to 0.
1091         *I = 0;
1092         
1093         // Set flag to indicate we may have more functions to lazily link in
1094         // since we linked in a function.
1095         LinkedInAnyFunctions = true;
1096       }
1097     }
1098   } while (LinkedInAnyFunctions);
1099   
1100   // Remove any prototypes of functions that were not actually linked in.
1101   for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1102       E = LazilyLinkFunctions.end(); I != E; ++I) {
1103     if (!*I)
1104       continue;
1105     
1106     Function *SF = *I;
1107     Function *DF = cast<Function>(ValueMap[SF]);
1108     if (DF->use_empty())
1109       DF->eraseFromParent();
1110   }
1111   
1112   // Now that all of the types from the source are used, resolve any structs
1113   // copied over to the dest that didn't exist there.
1114   TypeMap.linkDefinedTypeBodies();
1115   
1116   return false;
1117 }
1118
1119 //===----------------------------------------------------------------------===//
1120 // LinkModules entrypoint.
1121 //===----------------------------------------------------------------------===//
1122
1123 // LinkModules - This function links two modules together, with the resulting
1124 // left module modified to be the composite of the two input modules.  If an
1125 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1126 // the problem.  Upon failure, the Dest module could be in a modified state, and
1127 // shouldn't be relied on to be consistent.
1128 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode, 
1129                          std::string *ErrorMsg) {
1130   ModuleLinker TheLinker(Dest, Src, Mode);
1131   if (TheLinker.run()) {
1132     if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
1133     return true;
1134   }
1135   
1136   return false;
1137 }