Add a -suppress-warnings option to bitcode linking.
[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-c/Linker.h"
16 #include "llvm/ADT/Optional.h"
17 #include "llvm/ADT/SetVector.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/IR/Constants.h"
20 #include "llvm/IR/Module.h"
21 #include "llvm/IR/TypeFinder.h"
22 #include "llvm/Support/CommandLine.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include "llvm/Transforms/Utils/Cloning.h"
26 #include <cctype>
27 using namespace llvm;
28
29
30 static cl::opt<bool>
31 SuppressWarnings("suppress-warnings", cl::desc("Suppress all linking warnings"),
32                  cl::init(false));
33
34 //===----------------------------------------------------------------------===//
35 // TypeMap implementation.
36 //===----------------------------------------------------------------------===//
37
38 namespace {
39   typedef SmallPtrSet<StructType*, 32> TypeSet;
40
41 class TypeMapTy : public ValueMapTypeRemapper {
42   /// MappedTypes - This is a mapping from a source type to a destination type
43   /// to use.
44   DenseMap<Type*, Type*> MappedTypes;
45
46   /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
47   /// we speculatively add types to MappedTypes, but keep track of them here in
48   /// case we need to roll back.
49   SmallVector<Type*, 16> SpeculativeTypes;
50   
51   /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
52   /// source module that are mapped to an opaque struct in the destination
53   /// module.
54   SmallVector<StructType*, 16> SrcDefinitionsToResolve;
55   
56   /// DstResolvedOpaqueTypes - This is the set of opaque types in the
57   /// destination modules who are getting a body from the source module.
58   SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
59
60 public:
61   TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
62
63   TypeSet &DstStructTypesSet;
64   /// addTypeMapping - Indicate that the specified type in the destination
65   /// module is conceptually equivalent to the specified type in the source
66   /// module.
67   void addTypeMapping(Type *DstTy, Type *SrcTy);
68
69   /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
70   /// module from a type definition in the source module.
71   void linkDefinedTypeBodies();
72   
73   /// get - Return the mapped type to use for the specified input type from the
74   /// source module.
75   Type *get(Type *SrcTy);
76
77   FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
78
79   /// dump - Dump out the type map for debugging purposes.
80   void dump() const {
81     for (DenseMap<Type*, Type*>::const_iterator
82            I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
83       dbgs() << "TypeMap: ";
84       I->first->dump();
85       dbgs() << " => ";
86       I->second->dump();
87       dbgs() << '\n';
88     }
89   }
90
91 private:
92   Type *getImpl(Type *T);
93   /// remapType - Implement the ValueMapTypeRemapper interface.
94   Type *remapType(Type *SrcTy) {
95     return get(SrcTy);
96   }
97   
98   bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
99 };
100 }
101
102 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
103   Type *&Entry = MappedTypes[SrcTy];
104   if (Entry) return;
105   
106   if (DstTy == SrcTy) {
107     Entry = DstTy;
108     return;
109   }
110   
111   // Check to see if these types are recursively isomorphic and establish a
112   // mapping between them if so.
113   if (!areTypesIsomorphic(DstTy, SrcTy)) {
114     // Oops, they aren't isomorphic.  Just discard this request by rolling out
115     // any speculative mappings we've established.
116     for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
117       MappedTypes.erase(SpeculativeTypes[i]);
118   }
119   SpeculativeTypes.clear();
120 }
121
122 /// areTypesIsomorphic - Recursively walk this pair of types, returning true
123 /// if they are isomorphic, false if they are not.
124 bool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
125   // Two types with differing kinds are clearly not isomorphic.
126   if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
127
128   // If we have an entry in the MappedTypes table, then we have our answer.
129   Type *&Entry = MappedTypes[SrcTy];
130   if (Entry)
131     return Entry == DstTy;
132
133   // Two identical types are clearly isomorphic.  Remember this
134   // non-speculatively.
135   if (DstTy == SrcTy) {
136     Entry = DstTy;
137     return true;
138   }
139   
140   // Okay, we have two types with identical kinds that we haven't seen before.
141
142   // If this is an opaque struct type, special case it.
143   if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
144     // Mapping an opaque type to any struct, just keep the dest struct.
145     if (SSTy->isOpaque()) {
146       Entry = DstTy;
147       SpeculativeTypes.push_back(SrcTy);
148       return true;
149     }
150
151     // Mapping a non-opaque source type to an opaque dest.  If this is the first
152     // type that we're mapping onto this destination type then we succeed.  Keep
153     // the dest, but fill it in later.  This doesn't need to be speculative.  If
154     // this is the second (different) type that we're trying to map onto the
155     // same opaque type then we fail.
156     if (cast<StructType>(DstTy)->isOpaque()) {
157       // We can only map one source type onto the opaque destination type.
158       if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
159         return false;
160       SrcDefinitionsToResolve.push_back(SSTy);
161       Entry = DstTy;
162       return true;
163     }
164   }
165   
166   // If the number of subtypes disagree between the two types, then we fail.
167   if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
168     return false;
169   
170   // Fail if any of the extra properties (e.g. array size) of the type disagree.
171   if (isa<IntegerType>(DstTy))
172     return false;  // bitwidth disagrees.
173   if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
174     if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
175       return false;
176     
177   } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
178     if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
179       return false;
180   } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
181     StructType *SSTy = cast<StructType>(SrcTy);
182     if (DSTy->isLiteral() != SSTy->isLiteral() ||
183         DSTy->isPacked() != SSTy->isPacked())
184       return false;
185   } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
186     if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
187       return false;
188   } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
189     if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
190       return false;
191   }
192
193   // Otherwise, we speculate that these two types will line up and recursively
194   // check the subelements.
195   Entry = DstTy;
196   SpeculativeTypes.push_back(SrcTy);
197
198   for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
199     if (!areTypesIsomorphic(DstTy->getContainedType(i),
200                             SrcTy->getContainedType(i)))
201       return false;
202   
203   // If everything seems to have lined up, then everything is great.
204   return true;
205 }
206
207 /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
208 /// module from a type definition in the source module.
209 void TypeMapTy::linkDefinedTypeBodies() {
210   SmallVector<Type*, 16> Elements;
211   SmallString<16> TmpName;
212   
213   // Note that processing entries in this loop (calling 'get') can add new
214   // entries to the SrcDefinitionsToResolve vector.
215   while (!SrcDefinitionsToResolve.empty()) {
216     StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
217     StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
218     
219     // TypeMap is a many-to-one mapping, if there were multiple types that
220     // provide a body for DstSTy then previous iterations of this loop may have
221     // already handled it.  Just ignore this case.
222     if (!DstSTy->isOpaque()) continue;
223     assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
224     
225     // Map the body of the source type over to a new body for the dest type.
226     Elements.resize(SrcSTy->getNumElements());
227     for (unsigned i = 0, e = Elements.size(); i != e; ++i)
228       Elements[i] = getImpl(SrcSTy->getElementType(i));
229     
230     DstSTy->setBody(Elements, SrcSTy->isPacked());
231     
232     // If DstSTy has no name or has a longer name than STy, then viciously steal
233     // STy's name.
234     if (!SrcSTy->hasName()) continue;
235     StringRef SrcName = SrcSTy->getName();
236     
237     if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
238       TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
239       SrcSTy->setName("");
240       DstSTy->setName(TmpName.str());
241       TmpName.clear();
242     }
243   }
244   
245   DstResolvedOpaqueTypes.clear();
246 }
247
248 /// get - Return the mapped type to use for the specified input type from the
249 /// source module.
250 Type *TypeMapTy::get(Type *Ty) {
251   Type *Result = getImpl(Ty);
252   
253   // If this caused a reference to any struct type, resolve it before returning.
254   if (!SrcDefinitionsToResolve.empty())
255     linkDefinedTypeBodies();
256   return Result;
257 }
258
259 /// getImpl - This is the recursive version of get().
260 Type *TypeMapTy::getImpl(Type *Ty) {
261   // If we already have an entry for this type, return it.
262   Type **Entry = &MappedTypes[Ty];
263   if (*Entry) return *Entry;
264   
265   // If this is not a named struct type, then just map all of the elements and
266   // then rebuild the type from inside out.
267   if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
268     // If there are no element types to map, then the type is itself.  This is
269     // true for the anonymous {} struct, things like 'float', integers, etc.
270     if (Ty->getNumContainedTypes() == 0)
271       return *Entry = Ty;
272     
273     // Remap all of the elements, keeping track of whether any of them change.
274     bool AnyChange = false;
275     SmallVector<Type*, 4> ElementTypes;
276     ElementTypes.resize(Ty->getNumContainedTypes());
277     for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
278       ElementTypes[i] = getImpl(Ty->getContainedType(i));
279       AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
280     }
281     
282     // If we found our type while recursively processing stuff, just use it.
283     Entry = &MappedTypes[Ty];
284     if (*Entry) return *Entry;
285     
286     // If all of the element types mapped directly over, then the type is usable
287     // as-is.
288     if (!AnyChange)
289       return *Entry = Ty;
290     
291     // Otherwise, rebuild a modified type.
292     switch (Ty->getTypeID()) {
293     default: llvm_unreachable("unknown derived type to remap");
294     case Type::ArrayTyID:
295       return *Entry = ArrayType::get(ElementTypes[0],
296                                      cast<ArrayType>(Ty)->getNumElements());
297     case Type::VectorTyID: 
298       return *Entry = VectorType::get(ElementTypes[0],
299                                       cast<VectorType>(Ty)->getNumElements());
300     case Type::PointerTyID:
301       return *Entry = PointerType::get(ElementTypes[0],
302                                       cast<PointerType>(Ty)->getAddressSpace());
303     case Type::FunctionTyID:
304       return *Entry = FunctionType::get(ElementTypes[0],
305                                         makeArrayRef(ElementTypes).slice(1),
306                                         cast<FunctionType>(Ty)->isVarArg());
307     case Type::StructTyID:
308       // Note that this is only reached for anonymous structs.
309       return *Entry = StructType::get(Ty->getContext(), ElementTypes,
310                                       cast<StructType>(Ty)->isPacked());
311     }
312   }
313
314   // Otherwise, this is an unmapped named struct.  If the struct can be directly
315   // mapped over, just use it as-is.  This happens in a case when the linked-in
316   // module has something like:
317   //   %T = type {%T*, i32}
318   //   @GV = global %T* null
319   // where T does not exist at all in the destination module.
320   //
321   // The other case we watch for is when the type is not in the destination
322   // module, but that it has to be rebuilt because it refers to something that
323   // is already mapped.  For example, if the destination module has:
324   //  %A = type { i32 }
325   // and the source module has something like
326   //  %A' = type { i32 }
327   //  %B = type { %A'* }
328   //  @GV = global %B* null
329   // then we want to create a new type: "%B = type { %A*}" and have it take the
330   // pristine "%B" name from the source module.
331   //
332   // To determine which case this is, we have to recursively walk the type graph
333   // speculating that we'll be able to reuse it unmodified.  Only if this is
334   // safe would we map the entire thing over.  Because this is an optimization,
335   // and is not required for the prettiness of the linked module, we just skip
336   // it and always rebuild a type here.
337   StructType *STy = cast<StructType>(Ty);
338   
339   // If the type is opaque, we can just use it directly.
340   if (STy->isOpaque()) {
341     // A named structure type from src module is used. Add it to the Set of
342     // identified structs in the destination module.
343     DstStructTypesSet.insert(STy);
344     return *Entry = STy;
345   }
346   
347   // Otherwise we create a new type and resolve its body later.  This will be
348   // resolved by the top level of get().
349   SrcDefinitionsToResolve.push_back(STy);
350   StructType *DTy = StructType::create(STy->getContext());
351   // A new identified structure type was created. Add it to the set of
352   // identified structs in the destination module.
353   DstStructTypesSet.insert(DTy);
354   DstResolvedOpaqueTypes.insert(DTy);
355   return *Entry = DTy;
356 }
357
358 //===----------------------------------------------------------------------===//
359 // ModuleLinker implementation.
360 //===----------------------------------------------------------------------===//
361
362 namespace {
363   class ModuleLinker;
364
365   /// ValueMaterializerTy - Creates prototypes for functions that are lazily
366   /// linked on the fly. This speeds up linking for modules with many
367   /// lazily linked functions of which few get used.
368   class ValueMaterializerTy : public ValueMaterializer {
369     TypeMapTy &TypeMap;
370     Module *DstM;
371     std::vector<Function*> &LazilyLinkFunctions;
372   public:
373     ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
374                         std::vector<Function*> &LazilyLinkFunctions) :
375       ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
376       LazilyLinkFunctions(LazilyLinkFunctions) {
377     }
378
379     virtual Value *materializeValueFor(Value *V);
380   };
381
382   /// ModuleLinker - This is an implementation class for the LinkModules
383   /// function, which is the entrypoint for this file.
384   class ModuleLinker {
385     Module *DstM, *SrcM;
386     
387     TypeMapTy TypeMap; 
388     ValueMaterializerTy ValMaterializer;
389
390     /// ValueMap - Mapping of values from what they used to be in Src, to what
391     /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
392     /// some overhead due to the use of Value handles which the Linker doesn't
393     /// actually need, but this allows us to reuse the ValueMapper code.
394     ValueToValueMapTy ValueMap;
395     
396     struct AppendingVarInfo {
397       GlobalVariable *NewGV;  // New aggregate global in dest module.
398       Constant *DstInit;      // Old initializer from dest module.
399       Constant *SrcInit;      // Old initializer from src module.
400     };
401     
402     std::vector<AppendingVarInfo> AppendingVars;
403     
404     unsigned Mode; // Mode to treat source module.
405     
406     // Set of items not to link in from source.
407     SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
408     
409     // Vector of functions to lazily link in.
410     std::vector<Function*> LazilyLinkFunctions;
411     
412   public:
413     std::string ErrorMsg;
414     
415     ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
416       : DstM(dstM), SrcM(srcM), TypeMap(Set),
417         ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
418         Mode(mode) { }
419     
420     bool run();
421     
422   private:
423     /// emitError - Helper method for setting a message and returning an error
424     /// code.
425     bool emitError(const Twine &Message) {
426       ErrorMsg = Message.str();
427       return true;
428     }
429     
430     /// getLinkageResult - This analyzes the two global values and determines
431     /// what the result will look like in the destination module.
432     bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
433                           GlobalValue::LinkageTypes &LT,
434                           GlobalValue::VisibilityTypes &Vis,
435                           bool &LinkFromSrc);
436
437     /// getLinkedToGlobal - Given a global in the source module, return the
438     /// global in the destination module that is being linked to, if any.
439     GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
440       // If the source has no name it can't link.  If it has local linkage,
441       // there is no name match-up going on.
442       if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
443         return 0;
444       
445       // Otherwise see if we have a match in the destination module's symtab.
446       GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
447       if (DGV == 0) return 0;
448         
449       // If we found a global with the same name in the dest module, but it has
450       // internal linkage, we are really not doing any linkage here.
451       if (DGV->hasLocalLinkage())
452         return 0;
453
454       // Otherwise, we do in fact link to the destination global.
455       return DGV;
456     }
457     
458     void computeTypeMapping();
459     
460     bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
461     bool linkGlobalProto(GlobalVariable *SrcGV);
462     bool linkFunctionProto(Function *SrcF);
463     bool linkAliasProto(GlobalAlias *SrcA);
464     bool linkModuleFlagsMetadata();
465     
466     void linkAppendingVarInit(const AppendingVarInfo &AVI);
467     void linkGlobalInits();
468     void linkFunctionBody(Function *Dst, Function *Src);
469     void linkAliasBodies();
470     void linkNamedMDNodes();
471   };
472 }
473
474 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
475 /// in the symbol table.  This is good for all clients except for us.  Go
476 /// through the trouble to force this back.
477 static void forceRenaming(GlobalValue *GV, StringRef Name) {
478   // If the global doesn't force its name or if it already has the right name,
479   // there is nothing for us to do.
480   if (GV->hasLocalLinkage() || GV->getName() == Name)
481     return;
482
483   Module *M = GV->getParent();
484
485   // If there is a conflict, rename the conflict.
486   if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
487     GV->takeName(ConflictGV);
488     ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
489     assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
490   } else {
491     GV->setName(Name);              // Force the name back
492   }
493 }
494
495 /// copyGVAttributes - copy additional attributes (those not needed to construct
496 /// a GlobalValue) from the SrcGV to the DestGV.
497 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
498   // Use the maximum alignment, rather than just copying the alignment of SrcGV.
499   unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
500   DestGV->copyAttributesFrom(SrcGV);
501   DestGV->setAlignment(Alignment);
502   
503   forceRenaming(DestGV, SrcGV->getName());
504 }
505
506 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
507                                GlobalValue::VisibilityTypes b) {
508   if (a == GlobalValue::HiddenVisibility)
509     return false;
510   if (b == GlobalValue::HiddenVisibility)
511     return true;
512   if (a == GlobalValue::ProtectedVisibility)
513     return false;
514   if (b == GlobalValue::ProtectedVisibility)
515     return true;
516   return false;
517 }
518
519 Value *ValueMaterializerTy::materializeValueFor(Value *V) {
520   Function *SF = dyn_cast<Function>(V);
521   if (!SF)
522     return NULL;
523
524   Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
525                                   SF->getLinkage(), SF->getName(), DstM);
526   copyGVAttributes(DF, SF);
527
528   LazilyLinkFunctions.push_back(SF);
529   return DF;
530 }
531
532
533 /// getLinkageResult - This analyzes the two global values and determines what
534 /// the result will look like in the destination module.  In particular, it
535 /// computes the resultant linkage type and visibility, computes whether the
536 /// global in the source should be copied over to the destination (replacing
537 /// the existing one), and computes whether this linkage is an error or not.
538 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
539                                     GlobalValue::LinkageTypes &LT,
540                                     GlobalValue::VisibilityTypes &Vis,
541                                     bool &LinkFromSrc) {
542   assert(Dest && "Must have two globals being queried");
543   assert(!Src->hasLocalLinkage() &&
544          "If Src has internal linkage, Dest shouldn't be set!");
545   
546   bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
547   bool DestIsDeclaration = Dest->isDeclaration();
548   
549   if (SrcIsDeclaration) {
550     // If Src is external or if both Src & Dest are external..  Just link the
551     // external globals, we aren't adding anything.
552     if (Src->hasDLLImportStorageClass()) {
553       // If one of GVs is marked as DLLImport, result should be dllimport'ed.
554       if (DestIsDeclaration) {
555         LinkFromSrc = true;
556         LT = Src->getLinkage();
557       }
558     } else if (Dest->hasExternalWeakLinkage()) {
559       // If the Dest is weak, use the source linkage.
560       LinkFromSrc = true;
561       LT = Src->getLinkage();
562     } else {
563       LinkFromSrc = false;
564       LT = Dest->getLinkage();
565     }
566   } else if (DestIsDeclaration && !Dest->hasDLLImportStorageClass()) {
567     // If Dest is external but Src is not:
568     LinkFromSrc = true;
569     LT = Src->getLinkage();
570   } else if (Src->isWeakForLinker()) {
571     // At this point we know that Dest has LinkOnce, External*, Weak, Common,
572     // or DLL* linkage.
573     if (Dest->hasExternalWeakLinkage() ||
574         Dest->hasAvailableExternallyLinkage() ||
575         (Dest->hasLinkOnceLinkage() &&
576          (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
577       LinkFromSrc = true;
578       LT = Src->getLinkage();
579     } else {
580       LinkFromSrc = false;
581       LT = Dest->getLinkage();
582     }
583   } else if (Dest->isWeakForLinker()) {
584     // At this point we know that Src has External* or DLL* linkage.
585     if (Src->hasExternalWeakLinkage()) {
586       LinkFromSrc = false;
587       LT = Dest->getLinkage();
588     } else {
589       LinkFromSrc = true;
590       LT = GlobalValue::ExternalLinkage;
591     }
592   } else {
593     assert((Dest->hasExternalLinkage()  || Dest->hasExternalWeakLinkage()) &&
594            (Src->hasExternalLinkage()   || Src->hasExternalWeakLinkage()) &&
595            "Unexpected linkage type!");
596     return emitError("Linking globals named '" + Src->getName() +
597                  "': symbol multiply defined!");
598   }
599
600   // Compute the visibility. We follow the rules in the System V Application
601   // Binary Interface.
602   Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
603     Dest->getVisibility() : Src->getVisibility();
604   return false;
605 }
606
607 /// computeTypeMapping - Loop over all of the linked values to compute type
608 /// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
609 /// we have two struct types 'Foo' but one got renamed when the module was
610 /// loaded into the same LLVMContext.
611 void ModuleLinker::computeTypeMapping() {
612   // Incorporate globals.
613   for (Module::global_iterator I = SrcM->global_begin(),
614        E = SrcM->global_end(); I != E; ++I) {
615     GlobalValue *DGV = getLinkedToGlobal(I);
616     if (DGV == 0) continue;
617     
618     if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
619       TypeMap.addTypeMapping(DGV->getType(), I->getType());
620       continue;      
621     }
622     
623     // Unify the element type of appending arrays.
624     ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
625     ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
626     TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
627   }
628   
629   // Incorporate functions.
630   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
631     if (GlobalValue *DGV = getLinkedToGlobal(I))
632       TypeMap.addTypeMapping(DGV->getType(), I->getType());
633   }
634
635   // Incorporate types by name, scanning all the types in the source module.
636   // At this point, the destination module may have a type "%foo = { i32 }" for
637   // example.  When the source module got loaded into the same LLVMContext, if
638   // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
639   TypeFinder SrcStructTypes;
640   SrcStructTypes.run(*SrcM, true);
641   SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
642                                                  SrcStructTypes.end());
643
644   for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
645     StructType *ST = SrcStructTypes[i];
646     if (!ST->hasName()) continue;
647     
648     // Check to see if there is a dot in the name followed by a digit.
649     size_t DotPos = ST->getName().rfind('.');
650     if (DotPos == 0 || DotPos == StringRef::npos ||
651         ST->getName().back() == '.' ||
652         !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
653       continue;
654     
655     // Check to see if the destination module has a struct with the prefix name.
656     if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
657       // Don't use it if this actually came from the source module. They're in
658       // the same LLVMContext after all. Also don't use it unless the type is
659       // actually used in the destination module. This can happen in situations
660       // like this:
661       //
662       //      Module A                         Module B
663       //      --------                         --------
664       //   %Z = type { %A }                %B = type { %C.1 }
665       //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
666       //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
667       //   %C = type { i8* }               %B.3 = type { %C.1 }
668       //
669       // When we link Module B with Module A, the '%B' in Module B is
670       // used. However, that would then use '%C.1'. But when we process '%C.1',
671       // we prefer to take the '%C' version. So we are then left with both
672       // '%C.1' and '%C' being used for the same types. This leads to some
673       // variables using one type and some using the other.
674       if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
675         TypeMap.addTypeMapping(DST, ST);
676   }
677
678   // Don't bother incorporating aliases, they aren't generally typed well.
679   
680   // Now that we have discovered all of the type equivalences, get a body for
681   // any 'opaque' types in the dest module that are now resolved. 
682   TypeMap.linkDefinedTypeBodies();
683 }
684
685 /// linkAppendingVarProto - If there were any appending global variables, link
686 /// them together now.  Return true on error.
687 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
688                                          GlobalVariable *SrcGV) {
689  
690   if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
691     return emitError("Linking globals named '" + SrcGV->getName() +
692            "': can only link appending global with another appending global!");
693   
694   ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
695   ArrayType *SrcTy =
696     cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
697   Type *EltTy = DstTy->getElementType();
698   
699   // Check to see that they two arrays agree on type.
700   if (EltTy != SrcTy->getElementType())
701     return emitError("Appending variables with different element types!");
702   if (DstGV->isConstant() != SrcGV->isConstant())
703     return emitError("Appending variables linked with different const'ness!");
704   
705   if (DstGV->getAlignment() != SrcGV->getAlignment())
706     return emitError(
707              "Appending variables with different alignment need to be linked!");
708   
709   if (DstGV->getVisibility() != SrcGV->getVisibility())
710     return emitError(
711             "Appending variables with different visibility need to be linked!");
712
713   if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
714     return emitError(
715         "Appending variables with different unnamed_addr need to be linked!");
716
717   if (DstGV->getSection() != SrcGV->getSection())
718     return emitError(
719           "Appending variables with different section name need to be linked!");
720   
721   uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
722   ArrayType *NewType = ArrayType::get(EltTy, NewSize);
723   
724   // Create the new global variable.
725   GlobalVariable *NG =
726     new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
727                        DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
728                        DstGV->getThreadLocalMode(),
729                        DstGV->getType()->getAddressSpace());
730   
731   // Propagate alignment, visibility and section info.
732   copyGVAttributes(NG, DstGV);
733   
734   AppendingVarInfo AVI;
735   AVI.NewGV = NG;
736   AVI.DstInit = DstGV->getInitializer();
737   AVI.SrcInit = SrcGV->getInitializer();
738   AppendingVars.push_back(AVI);
739
740   // Replace any uses of the two global variables with uses of the new
741   // global.
742   ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
743
744   DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
745   DstGV->eraseFromParent();
746   
747   // Track the source variable so we don't try to link it.
748   DoNotLinkFromSource.insert(SrcGV);
749   
750   return false;
751 }
752
753 /// linkGlobalProto - Loop through the global variables in the src module and
754 /// merge them into the dest module.
755 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
756   GlobalValue *DGV = getLinkedToGlobal(SGV);
757   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
758   bool HasUnnamedAddr = SGV->hasUnnamedAddr();
759
760   if (DGV) {
761     // Concatenation of appending linkage variables is magic and handled later.
762     if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
763       return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
764     
765     // Determine whether linkage of these two globals follows the source
766     // module's definition or the destination module's definition.
767     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
768     GlobalValue::VisibilityTypes NV;
769     bool LinkFromSrc = false;
770     if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
771       return true;
772     NewVisibility = NV;
773     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
774
775     // If we're not linking from the source, then keep the definition that we
776     // have.
777     if (!LinkFromSrc) {
778       // Special case for const propagation.
779       if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
780         if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
781           DGVar->setConstant(true);
782
783       // Set calculated linkage, visibility and unnamed_addr.
784       DGV->setLinkage(NewLinkage);
785       DGV->setVisibility(*NewVisibility);
786       DGV->setUnnamedAddr(HasUnnamedAddr);
787
788       // Make sure to remember this mapping.
789       ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
790       
791       // Track the source global so that we don't attempt to copy it over when 
792       // processing global initializers.
793       DoNotLinkFromSource.insert(SGV);
794       
795       return false;
796     }
797   }
798   
799   // No linking to be performed or linking from the source: simply create an
800   // identical version of the symbol over in the dest module... the
801   // initializer will be filled in later by LinkGlobalInits.
802   GlobalVariable *NewDGV =
803     new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
804                        SGV->isConstant(), SGV->getLinkage(), /*init*/0,
805                        SGV->getName(), /*insertbefore*/0,
806                        SGV->getThreadLocalMode(),
807                        SGV->getType()->getAddressSpace());
808   // Propagate alignment, visibility and section info.
809   copyGVAttributes(NewDGV, SGV);
810   if (NewVisibility)
811     NewDGV->setVisibility(*NewVisibility);
812   NewDGV->setUnnamedAddr(HasUnnamedAddr);
813
814   if (DGV) {
815     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
816     DGV->eraseFromParent();
817   }
818   
819   // Make sure to remember this mapping.
820   ValueMap[SGV] = NewDGV;
821   return false;
822 }
823
824 /// linkFunctionProto - Link the function in the source module into the
825 /// destination module if needed, setting up mapping information.
826 bool ModuleLinker::linkFunctionProto(Function *SF) {
827   GlobalValue *DGV = getLinkedToGlobal(SF);
828   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
829   bool HasUnnamedAddr = SF->hasUnnamedAddr();
830
831   if (DGV) {
832     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
833     bool LinkFromSrc = false;
834     GlobalValue::VisibilityTypes NV;
835     if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
836       return true;
837     NewVisibility = NV;
838     HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
839
840     if (!LinkFromSrc) {
841       // Set calculated linkage
842       DGV->setLinkage(NewLinkage);
843       DGV->setVisibility(*NewVisibility);
844       DGV->setUnnamedAddr(HasUnnamedAddr);
845
846       // Make sure to remember this mapping.
847       ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
848       
849       // Track the function from the source module so we don't attempt to remap 
850       // it.
851       DoNotLinkFromSource.insert(SF);
852       
853       return false;
854     }
855   }
856   
857   // If the function is to be lazily linked, don't create it just yet.
858   // The ValueMaterializerTy will deal with creating it if it's used.
859   if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
860                SF->hasAvailableExternallyLinkage())) {
861     DoNotLinkFromSource.insert(SF);
862     return false;
863   }
864
865   // If there is no linkage to be performed or we are linking from the source,
866   // bring SF over.
867   Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
868                                      SF->getLinkage(), SF->getName(), DstM);
869   copyGVAttributes(NewDF, SF);
870   if (NewVisibility)
871     NewDF->setVisibility(*NewVisibility);
872   NewDF->setUnnamedAddr(HasUnnamedAddr);
873
874   if (DGV) {
875     // Any uses of DF need to change to NewDF, with cast.
876     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
877     DGV->eraseFromParent();
878   }
879   
880   ValueMap[SF] = NewDF;
881   return false;
882 }
883
884 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
885 /// source module.
886 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
887   GlobalValue *DGV = getLinkedToGlobal(SGA);
888   llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
889
890   if (DGV) {
891     GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
892     GlobalValue::VisibilityTypes NV;
893     bool LinkFromSrc = false;
894     if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
895       return true;
896     NewVisibility = NV;
897
898     if (!LinkFromSrc) {
899       // Set calculated linkage.
900       DGV->setLinkage(NewLinkage);
901       DGV->setVisibility(*NewVisibility);
902
903       // Make sure to remember this mapping.
904       ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
905       
906       // Track the alias from the source module so we don't attempt to remap it.
907       DoNotLinkFromSource.insert(SGA);
908       
909       return false;
910     }
911   }
912   
913   // If there is no linkage to be performed or we're linking from the source,
914   // bring over SGA.
915   GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
916                                        SGA->getLinkage(), SGA->getName(),
917                                        /*aliasee*/0, DstM);
918   copyGVAttributes(NewDA, SGA);
919   if (NewVisibility)
920     NewDA->setVisibility(*NewVisibility);
921
922   if (DGV) {
923     // Any uses of DGV need to change to NewDA, with cast.
924     DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
925     DGV->eraseFromParent();
926   }
927   
928   ValueMap[SGA] = NewDA;
929   return false;
930 }
931
932 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
933   unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
934
935   for (unsigned i = 0; i != NumElements; ++i)
936     Dest.push_back(C->getAggregateElement(i));
937 }
938                              
939 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
940   // Merge the initializer.
941   SmallVector<Constant*, 16> Elements;
942   getArrayElements(AVI.DstInit, Elements);
943   
944   Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
945   getArrayElements(SrcInit, Elements);
946   
947   ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
948   AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
949 }
950
951 /// linkGlobalInits - Update the initializers in the Dest module now that all
952 /// globals that may be referenced are in Dest.
953 void ModuleLinker::linkGlobalInits() {
954   // Loop over all of the globals in the src module, mapping them over as we go
955   for (Module::const_global_iterator I = SrcM->global_begin(),
956        E = SrcM->global_end(); I != E; ++I) {
957     
958     // Only process initialized GV's or ones not already in dest.
959     if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;          
960     
961     // Grab destination global variable.
962     GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
963     // Figure out what the initializer looks like in the dest module.
964     DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
965                                  RF_None, &TypeMap, &ValMaterializer));
966   }
967 }
968
969 /// linkFunctionBody - Copy the source function over into the dest function and
970 /// fix up references to values.  At this point we know that Dest is an external
971 /// function, and that Src is not.
972 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
973   assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
974
975   // Go through and convert function arguments over, remembering the mapping.
976   Function::arg_iterator DI = Dst->arg_begin();
977   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
978        I != E; ++I, ++DI) {
979     DI->setName(I->getName());  // Copy the name over.
980
981     // Add a mapping to our mapping.
982     ValueMap[I] = DI;
983   }
984
985   if (Mode == Linker::DestroySource) {
986     // Splice the body of the source function into the dest function.
987     Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
988     
989     // At this point, all of the instructions and values of the function are now
990     // copied over.  The only problem is that they are still referencing values in
991     // the Source function as operands.  Loop through all of the operands of the
992     // functions and patch them up to point to the local versions.
993     for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
994       for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
995         RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
996                          &TypeMap, &ValMaterializer);
997     
998   } else {
999     // Clone the body of the function into the dest function.
1000     SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
1001     CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL,
1002                       &TypeMap, &ValMaterializer);
1003   }
1004   
1005   // There is no need to map the arguments anymore.
1006   for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1007        I != E; ++I)
1008     ValueMap.erase(I);
1009   
1010 }
1011
1012 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1013 void ModuleLinker::linkAliasBodies() {
1014   for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1015        I != E; ++I) {
1016     if (DoNotLinkFromSource.count(I))
1017       continue;
1018     if (Constant *Aliasee = I->getAliasee()) {
1019       GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1020       DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None,
1021                               &TypeMap, &ValMaterializer));
1022     }
1023   }
1024 }
1025
1026 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1027 /// module.
1028 void ModuleLinker::linkNamedMDNodes() {
1029   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1030   for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1031        E = SrcM->named_metadata_end(); I != E; ++I) {
1032     // Don't link module flags here. Do them separately.
1033     if (&*I == SrcModFlags) continue;
1034     NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1035     // Add Src elements into Dest node.
1036     for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1037       DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1038                                    RF_None, &TypeMap, &ValMaterializer));
1039   }
1040 }
1041
1042 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1043 /// module.
1044 bool ModuleLinker::linkModuleFlagsMetadata() {
1045   // If the source module has no module flags, we are done.
1046   const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1047   if (!SrcModFlags) return false;
1048
1049   // If the destination module doesn't have module flags yet, then just copy
1050   // over the source module's flags.
1051   NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1052   if (DstModFlags->getNumOperands() == 0) {
1053     for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1054       DstModFlags->addOperand(SrcModFlags->getOperand(I));
1055
1056     return false;
1057   }
1058
1059   // First build a map of the existing module flags and requirements.
1060   DenseMap<MDString*, MDNode*> Flags;
1061   SmallSetVector<MDNode*, 16> Requirements;
1062   for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1063     MDNode *Op = DstModFlags->getOperand(I);
1064     ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1065     MDString *ID = cast<MDString>(Op->getOperand(1));
1066
1067     if (Behavior->getZExtValue() == Module::Require) {
1068       Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1069     } else {
1070       Flags[ID] = Op;
1071     }
1072   }
1073
1074   // Merge in the flags from the source module, and also collect its set of
1075   // requirements.
1076   bool HasErr = false;
1077   for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1078     MDNode *SrcOp = SrcModFlags->getOperand(I);
1079     ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1080     MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1081     MDNode *DstOp = Flags.lookup(ID);
1082     unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1083
1084     // If this is a requirement, add it and continue.
1085     if (SrcBehaviorValue == Module::Require) {
1086       // If the destination module does not already have this requirement, add
1087       // it.
1088       if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1089         DstModFlags->addOperand(SrcOp);
1090       }
1091       continue;
1092     }
1093
1094     // If there is no existing flag with this ID, just add it.
1095     if (!DstOp) {
1096       Flags[ID] = SrcOp;
1097       DstModFlags->addOperand(SrcOp);
1098       continue;
1099     }
1100
1101     // Otherwise, perform a merge.
1102     ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1103     unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1104
1105     // If either flag has override behavior, handle it first.
1106     if (DstBehaviorValue == Module::Override) {
1107       // Diagnose inconsistent flags which both have override behavior.
1108       if (SrcBehaviorValue == Module::Override &&
1109           SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1110         HasErr |= emitError("linking module flags '" + ID->getString() +
1111                             "': IDs have conflicting override values");
1112       }
1113       continue;
1114     } else if (SrcBehaviorValue == Module::Override) {
1115       // Update the destination flag to that of the source.
1116       DstOp->replaceOperandWith(0, SrcBehavior);
1117       DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1118       continue;
1119     }
1120
1121     // Diagnose inconsistent merge behavior types.
1122     if (SrcBehaviorValue != DstBehaviorValue) {
1123       HasErr |= emitError("linking module flags '" + ID->getString() +
1124                           "': IDs have conflicting behaviors");
1125       continue;
1126     }
1127
1128     // Perform the merge for standard behavior types.
1129     switch (SrcBehaviorValue) {
1130     case Module::Require:
1131     case Module::Override: assert(0 && "not possible"); break;
1132     case Module::Error: {
1133       // Emit an error if the values differ.
1134       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1135         HasErr |= emitError("linking module flags '" + ID->getString() +
1136                             "': IDs have conflicting values");
1137       }
1138       continue;
1139     }
1140     case Module::Warning: {
1141       // Emit a warning if the values differ.
1142       if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1143         if (!SuppressWarnings) {
1144           errs() << "WARNING: linking module flags '" << ID->getString()
1145                  << "': IDs have conflicting values";
1146         }
1147       }
1148       continue;
1149     }
1150     case Module::Append: {
1151       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1152       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1153       unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1154       Value **VP, **Values = VP = new Value*[NumOps];
1155       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1156         *VP = DstValue->getOperand(i);
1157       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1158         *VP = SrcValue->getOperand(i);
1159       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1160                                                ArrayRef<Value*>(Values,
1161                                                                 NumOps)));
1162       delete[] Values;
1163       break;
1164     }
1165     case Module::AppendUnique: {
1166       SmallSetVector<Value*, 16> Elts;
1167       MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1168       MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1169       for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1170         Elts.insert(DstValue->getOperand(i));
1171       for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1172         Elts.insert(SrcValue->getOperand(i));
1173       DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1174                                                ArrayRef<Value*>(Elts.begin(),
1175                                                                 Elts.end())));
1176       break;
1177     }
1178     }
1179   }
1180
1181   // Check all of the requirements.
1182   for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1183     MDNode *Requirement = Requirements[I];
1184     MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1185     Value *ReqValue = Requirement->getOperand(1);
1186
1187     MDNode *Op = Flags[Flag];
1188     if (!Op || Op->getOperand(2) != ReqValue) {
1189       HasErr |= emitError("linking module flags '" + Flag->getString() +
1190                           "': does not have the required value");
1191       continue;
1192     }
1193   }
1194
1195   return HasErr;
1196 }
1197   
1198 bool ModuleLinker::run() {
1199   assert(DstM && "Null destination module");
1200   assert(SrcM && "Null source module");
1201
1202   // Inherit the target data from the source module if the destination module
1203   // doesn't have one already.
1204   if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1205     DstM->setDataLayout(SrcM->getDataLayout());
1206
1207   // Copy the target triple from the source to dest if the dest's is empty.
1208   if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1209     DstM->setTargetTriple(SrcM->getTargetTriple());
1210
1211   if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1212       SrcM->getDataLayout() != DstM->getDataLayout()) {
1213     if (!SuppressWarnings) {
1214       errs() << "WARNING: Linking two modules of different data layouts!\n";
1215     }
1216   }
1217   if (!SrcM->getTargetTriple().empty() &&
1218       DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1219     if (!SuppressWarnings) {
1220       errs() << "WARNING: Linking two modules of different target triples: ";
1221       if (!SrcM->getModuleIdentifier().empty())
1222         errs() << SrcM->getModuleIdentifier() << ": ";
1223       errs() << "'" << SrcM->getTargetTriple() << "' and '"
1224              << DstM->getTargetTriple() << "'\n";
1225     }
1226   }
1227
1228   // Append the module inline asm string.
1229   if (!SrcM->getModuleInlineAsm().empty()) {
1230     if (DstM->getModuleInlineAsm().empty())
1231       DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1232     else
1233       DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1234                                SrcM->getModuleInlineAsm());
1235   }
1236
1237   // Loop over all of the linked values to compute type mappings.
1238   computeTypeMapping();
1239
1240   // Insert all of the globals in src into the DstM module... without linking
1241   // initializers (which could refer to functions not yet mapped over).
1242   for (Module::global_iterator I = SrcM->global_begin(),
1243        E = SrcM->global_end(); I != E; ++I)
1244     if (linkGlobalProto(I))
1245       return true;
1246
1247   // Link the functions together between the two modules, without doing function
1248   // bodies... this just adds external function prototypes to the DstM
1249   // function...  We do this so that when we begin processing function bodies,
1250   // all of the global values that may be referenced are available in our
1251   // ValueMap.
1252   for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1253     if (linkFunctionProto(I))
1254       return true;
1255
1256   // If there were any aliases, link them now.
1257   for (Module::alias_iterator I = SrcM->alias_begin(),
1258        E = SrcM->alias_end(); I != E; ++I)
1259     if (linkAliasProto(I))
1260       return true;
1261
1262   for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1263     linkAppendingVarInit(AppendingVars[i]);
1264   
1265   // Link in the function bodies that are defined in the source module into
1266   // DstM.
1267   for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1268     // Skip if not linking from source.
1269     if (DoNotLinkFromSource.count(SF)) continue;
1270     
1271     Function *DF = cast<Function>(ValueMap[SF]);
1272     if (SF->hasPrefixData()) {
1273       // Link in the prefix data.
1274       DF->setPrefixData(MapValue(
1275           SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1276     }
1277
1278     // Skip if no body (function is external) or materialize.
1279     if (SF->isDeclaration()) {
1280       if (!SF->isMaterializable())
1281         continue;
1282       if (SF->Materialize(&ErrorMsg))
1283         return true;
1284     }
1285     
1286     linkFunctionBody(DF, SF);
1287     SF->Dematerialize();
1288   }
1289
1290   // Resolve all uses of aliases with aliasees.
1291   linkAliasBodies();
1292
1293   // Remap all of the named MDNodes in Src into the DstM module. We do this
1294   // after linking GlobalValues so that MDNodes that reference GlobalValues
1295   // are properly remapped.
1296   linkNamedMDNodes();
1297
1298   // Merge the module flags into the DstM module.
1299   if (linkModuleFlagsMetadata())
1300     return true;
1301
1302   // Update the initializers in the DstM module now that all globals that may
1303   // be referenced are in DstM.
1304   linkGlobalInits();
1305
1306   // Process vector of lazily linked in functions.
1307   bool LinkedInAnyFunctions;
1308   do {
1309     LinkedInAnyFunctions = false;
1310     
1311     for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1312         E = LazilyLinkFunctions.end(); I != E; ++I) {      
1313       Function *SF = *I;
1314       if (!SF)
1315         continue;
1316
1317       Function *DF = cast<Function>(ValueMap[SF]);
1318       if (SF->hasPrefixData()) {
1319         // Link in the prefix data.
1320         DF->setPrefixData(MapValue(SF->getPrefixData(),
1321                                    ValueMap,
1322                                    RF_None,
1323                                    &TypeMap,
1324                                    &ValMaterializer));
1325       }
1326
1327       // Materialize if necessary.
1328       if (SF->isDeclaration()) {
1329         if (!SF->isMaterializable())
1330           continue;
1331         if (SF->Materialize(&ErrorMsg))
1332           return true;
1333       }
1334       
1335       // Erase from vector *before* the function body is linked - linkFunctionBody could
1336       // invalidate I.
1337       LazilyLinkFunctions.erase(I);
1338
1339       // Link in function body.
1340       linkFunctionBody(DF, SF);
1341       SF->Dematerialize();
1342
1343       // Set flag to indicate we may have more functions to lazily link in
1344       // since we linked in a function.
1345       LinkedInAnyFunctions = true;
1346       break;
1347     }
1348   } while (LinkedInAnyFunctions);
1349   
1350   // Now that all of the types from the source are used, resolve any structs
1351   // copied over to the dest that didn't exist there.
1352   TypeMap.linkDefinedTypeBodies();
1353   
1354   return false;
1355 }
1356
1357 Linker::Linker(Module *M) : Composite(M) {
1358   TypeFinder StructTypes;
1359   StructTypes.run(*M, true);
1360   IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1361 }
1362
1363 Linker::~Linker() {
1364 }
1365
1366 void Linker::deleteModule() {
1367   delete Composite;
1368   Composite = NULL;
1369 }
1370
1371 bool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1372   ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
1373   if (TheLinker.run()) {
1374     if (ErrorMsg)
1375       *ErrorMsg = TheLinker.ErrorMsg;
1376     return true;
1377   }
1378   return false;
1379 }
1380
1381 //===----------------------------------------------------------------------===//
1382 // LinkModules entrypoint.
1383 //===----------------------------------------------------------------------===//
1384
1385 /// LinkModules - This function links two modules together, with the resulting
1386 /// Dest module modified to be the composite of the two input modules.  If an
1387 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1388 /// the problem.  Upon failure, the Dest module could be in a modified state,
1389 /// and shouldn't be relied on to be consistent.
1390 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode, 
1391                          std::string *ErrorMsg) {
1392   Linker L(Dest);
1393   return L.linkInModule(Src, Mode, ErrorMsg);
1394 }
1395
1396 //===----------------------------------------------------------------------===//
1397 // C API.
1398 //===----------------------------------------------------------------------===//
1399
1400 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1401                          LLVMLinkerMode Mode, char **OutMessages) {
1402   std::string Messages;
1403   LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1404                                         Mode, OutMessages? &Messages : 0);
1405   if (OutMessages)
1406     *OutMessages = strdup(Messages.c_str());
1407   return Result;
1408 }