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