1193323Sed//===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
2193323Sed//
3193323Sed//                     The LLVM Compiler Infrastructure
4193323Sed//
5193323Sed// This file is distributed under the University of Illinois Open Source
6193323Sed// License. See LICENSE.TXT for details.
7193323Sed//
8193323Sed//===----------------------------------------------------------------------===//
9193323Sed//
10193323Sed// This file implements the LLVM module linker.
11193323Sed//
12193323Sed//===----------------------------------------------------------------------===//
13193323Sed
14193323Sed#include "llvm/Linker.h"
15252723Sdim#include "llvm-c/Linker.h"
16235633Sdim#include "llvm/ADT/Optional.h"
17235633Sdim#include "llvm/ADT/SetVector.h"
18252723Sdim#include "llvm/ADT/SmallString.h"
19252723Sdim#include "llvm/IR/Constants.h"
20252723Sdim#include "llvm/IR/Module.h"
21252723Sdim#include "llvm/IR/TypeFinder.h"
22235633Sdim#include "llvm/Support/Debug.h"
23198090Srdivacky#include "llvm/Support/raw_ostream.h"
24226890Sdim#include "llvm/Transforms/Utils/Cloning.h"
25263509Sdim#include <cctype>
26193323Sedusing namespace llvm;
27193323Sed
28224145Sdim//===----------------------------------------------------------------------===//
29224145Sdim// TypeMap implementation.
30224145Sdim//===----------------------------------------------------------------------===//
31193323Sed
32193323Sednamespace {
33252723Sdim  typedef SmallPtrSet<StructType*, 32> TypeSet;
34252723Sdim
35224145Sdimclass TypeMapTy : public ValueMapTypeRemapper {
36224145Sdim  /// MappedTypes - This is a mapping from a source type to a destination type
37224145Sdim  /// to use.
38224145Sdim  DenseMap<Type*, Type*> MappedTypes;
39193323Sed
40224145Sdim  /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
41224145Sdim  /// we speculatively add types to MappedTypes, but keep track of them here in
42224145Sdim  /// case we need to roll back.
43224145Sdim  SmallVector<Type*, 16> SpeculativeTypes;
44224145Sdim
45235633Sdim  /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
46235633Sdim  /// source module that are mapped to an opaque struct in the destination
47235633Sdim  /// module.
48235633Sdim  SmallVector<StructType*, 16> SrcDefinitionsToResolve;
49235633Sdim
50235633Sdim  /// DstResolvedOpaqueTypes - This is the set of opaque types in the
51235633Sdim  /// destination modules who are getting a body from the source module.
52235633Sdim  SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
53235633Sdim
54193323Sedpublic:
55252723Sdim  TypeMapTy(TypeSet &Set) : DstStructTypesSet(Set) {}
56252723Sdim
57252723Sdim  TypeSet &DstStructTypesSet;
58224145Sdim  /// addTypeMapping - Indicate that the specified type in the destination
59224145Sdim  /// module is conceptually equivalent to the specified type in the source
60224145Sdim  /// module.
61224145Sdim  void addTypeMapping(Type *DstTy, Type *SrcTy);
62193323Sed
63224145Sdim  /// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
64224145Sdim  /// module from a type definition in the source module.
65224145Sdim  void linkDefinedTypeBodies();
66224145Sdim
67224145Sdim  /// get - Return the mapped type to use for the specified input type from the
68224145Sdim  /// source module.
69224145Sdim  Type *get(Type *SrcTy);
70193323Sed
71224145Sdim  FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
72193323Sed
73235633Sdim  /// dump - Dump out the type map for debugging purposes.
74235633Sdim  void dump() const {
75235633Sdim    for (DenseMap<Type*, Type*>::const_iterator
76235633Sdim           I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
77235633Sdim      dbgs() << "TypeMap: ";
78235633Sdim      I->first->dump();
79235633Sdim      dbgs() << " => ";
80235633Sdim      I->second->dump();
81235633Sdim      dbgs() << '\n';
82235633Sdim    }
83235633Sdim  }
84235633Sdim
85224145Sdimprivate:
86224145Sdim  Type *getImpl(Type *T);
87224145Sdim  /// remapType - Implement the ValueMapTypeRemapper interface.
88224145Sdim  Type *remapType(Type *SrcTy) {
89224145Sdim    return get(SrcTy);
90193323Sed  }
91224145Sdim
92224145Sdim  bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
93224145Sdim};
94224145Sdim}
95193323Sed
96224145Sdimvoid TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97224145Sdim  Type *&Entry = MappedTypes[SrcTy];
98224145Sdim  if (Entry) return;
99224145Sdim
100224145Sdim  if (DstTy == SrcTy) {
101224145Sdim    Entry = DstTy;
102224145Sdim    return;
103193323Sed  }
104224145Sdim
105224145Sdim  // Check to see if these types are recursively isomorphic and establish a
106224145Sdim  // mapping between them if so.
107224145Sdim  if (!areTypesIsomorphic(DstTy, SrcTy)) {
108224145Sdim    // Oops, they aren't isomorphic.  Just discard this request by rolling out
109224145Sdim    // any speculative mappings we've established.
110224145Sdim    for (unsigned i = 0, e = SpeculativeTypes.size(); i != e; ++i)
111224145Sdim      MappedTypes.erase(SpeculativeTypes[i]);
112193323Sed  }
113224145Sdim  SpeculativeTypes.clear();
114193323Sed}
115193323Sed
116224145Sdim/// areTypesIsomorphic - Recursively walk this pair of types, returning true
117224145Sdim/// if they are isomorphic, false if they are not.
118224145Sdimbool TypeMapTy::areTypesIsomorphic(Type *DstTy, Type *SrcTy) {
119224145Sdim  // Two types with differing kinds are clearly not isomorphic.
120224145Sdim  if (DstTy->getTypeID() != SrcTy->getTypeID()) return false;
121193323Sed
122224145Sdim  // If we have an entry in the MappedTypes table, then we have our answer.
123224145Sdim  Type *&Entry = MappedTypes[SrcTy];
124224145Sdim  if (Entry)
125224145Sdim    return Entry == DstTy;
126193323Sed
127224145Sdim  // Two identical types are clearly isomorphic.  Remember this
128224145Sdim  // non-speculatively.
129224145Sdim  if (DstTy == SrcTy) {
130224145Sdim    Entry = DstTy;
131193323Sed    return true;
132224145Sdim  }
133224145Sdim
134224145Sdim  // Okay, we have two types with identical kinds that we haven't seen before.
135193323Sed
136224145Sdim  // If this is an opaque struct type, special case it.
137224145Sdim  if (StructType *SSTy = dyn_cast<StructType>(SrcTy)) {
138224145Sdim    // Mapping an opaque type to any struct, just keep the dest struct.
139224145Sdim    if (SSTy->isOpaque()) {
140224145Sdim      Entry = DstTy;
141224145Sdim      SpeculativeTypes.push_back(SrcTy);
142193323Sed      return true;
143224145Sdim    }
144193323Sed
145235633Sdim    // Mapping a non-opaque source type to an opaque dest.  If this is the first
146235633Sdim    // type that we're mapping onto this destination type then we succeed.  Keep
147235633Sdim    // the dest, but fill it in later.  This doesn't need to be speculative.  If
148235633Sdim    // this is the second (different) type that we're trying to map onto the
149235633Sdim    // same opaque type then we fail.
150224145Sdim    if (cast<StructType>(DstTy)->isOpaque()) {
151235633Sdim      // We can only map one source type onto the opaque destination type.
152235633Sdim      if (!DstResolvedOpaqueTypes.insert(cast<StructType>(DstTy)))
153235633Sdim        return false;
154235633Sdim      SrcDefinitionsToResolve.push_back(SSTy);
155224145Sdim      Entry = DstTy;
156224145Sdim      return true;
157193323Sed    }
158193323Sed  }
159224145Sdim
160224145Sdim  // If the number of subtypes disagree between the two types, then we fail.
161224145Sdim  if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
162193323Sed    return false;
163224145Sdim
164224145Sdim  // Fail if any of the extra properties (e.g. array size) of the type disagree.
165224145Sdim  if (isa<IntegerType>(DstTy))
166224145Sdim    return false;  // bitwidth disagrees.
167224145Sdim  if (PointerType *PT = dyn_cast<PointerType>(DstTy)) {
168224145Sdim    if (PT->getAddressSpace() != cast<PointerType>(SrcTy)->getAddressSpace())
169224145Sdim      return false;
170235633Sdim
171224145Sdim  } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
172224145Sdim    if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
173224145Sdim      return false;
174224145Sdim  } else if (StructType *DSTy = dyn_cast<StructType>(DstTy)) {
175224145Sdim    StructType *SSTy = cast<StructType>(SrcTy);
176226890Sdim    if (DSTy->isLiteral() != SSTy->isLiteral() ||
177224145Sdim        DSTy->isPacked() != SSTy->isPacked())
178224145Sdim      return false;
179224145Sdim  } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
180224145Sdim    if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
181224145Sdim      return false;
182224145Sdim  } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
183252723Sdim    if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
184224145Sdim      return false;
185193323Sed  }
186193323Sed
187224145Sdim  // Otherwise, we speculate that these two types will line up and recursively
188224145Sdim  // check the subelements.
189224145Sdim  Entry = DstTy;
190224145Sdim  SpeculativeTypes.push_back(SrcTy);
191193323Sed
192224145Sdim  for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
193224145Sdim    if (!areTypesIsomorphic(DstTy->getContainedType(i),
194224145Sdim                            SrcTy->getContainedType(i)))
195224145Sdim      return false;
196224145Sdim
197224145Sdim  // If everything seems to have lined up, then everything is great.
198224145Sdim  return true;
199224145Sdim}
200193323Sed
201224145Sdim/// linkDefinedTypeBodies - Produce a body for an opaque type in the dest
202224145Sdim/// module from a type definition in the source module.
203224145Sdimvoid TypeMapTy::linkDefinedTypeBodies() {
204224145Sdim  SmallVector<Type*, 16> Elements;
205224145Sdim  SmallString<16> TmpName;
206224145Sdim
207224145Sdim  // Note that processing entries in this loop (calling 'get') can add new
208235633Sdim  // entries to the SrcDefinitionsToResolve vector.
209235633Sdim  while (!SrcDefinitionsToResolve.empty()) {
210235633Sdim    StructType *SrcSTy = SrcDefinitionsToResolve.pop_back_val();
211224145Sdim    StructType *DstSTy = cast<StructType>(MappedTypes[SrcSTy]);
212224145Sdim
213224145Sdim    // TypeMap is a many-to-one mapping, if there were multiple types that
214224145Sdim    // provide a body for DstSTy then previous iterations of this loop may have
215224145Sdim    // already handled it.  Just ignore this case.
216224145Sdim    if (!DstSTy->isOpaque()) continue;
217224145Sdim    assert(!SrcSTy->isOpaque() && "Not resolving a definition?");
218224145Sdim
219224145Sdim    // Map the body of the source type over to a new body for the dest type.
220224145Sdim    Elements.resize(SrcSTy->getNumElements());
221224145Sdim    for (unsigned i = 0, e = Elements.size(); i != e; ++i)
222224145Sdim      Elements[i] = getImpl(SrcSTy->getElementType(i));
223224145Sdim
224224145Sdim    DstSTy->setBody(Elements, SrcSTy->isPacked());
225224145Sdim
226224145Sdim    // If DstSTy has no name or has a longer name than STy, then viciously steal
227224145Sdim    // STy's name.
228224145Sdim    if (!SrcSTy->hasName()) continue;
229224145Sdim    StringRef SrcName = SrcSTy->getName();
230224145Sdim
231224145Sdim    if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
232224145Sdim      TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
233224145Sdim      SrcSTy->setName("");
234224145Sdim      DstSTy->setName(TmpName.str());
235224145Sdim      TmpName.clear();
236224145Sdim    }
237193323Sed  }
238235633Sdim
239235633Sdim  DstResolvedOpaqueTypes.clear();
240193323Sed}
241193323Sed
242224145Sdim/// get - Return the mapped type to use for the specified input type from the
243224145Sdim/// source module.
244224145SdimType *TypeMapTy::get(Type *Ty) {
245224145Sdim  Type *Result = getImpl(Ty);
246224145Sdim
247224145Sdim  // If this caused a reference to any struct type, resolve it before returning.
248235633Sdim  if (!SrcDefinitionsToResolve.empty())
249224145Sdim    linkDefinedTypeBodies();
250224145Sdim  return Result;
251193323Sed}
252193323Sed
253224145Sdim/// getImpl - This is the recursive version of get().
254224145SdimType *TypeMapTy::getImpl(Type *Ty) {
255224145Sdim  // If we already have an entry for this type, return it.
256224145Sdim  Type **Entry = &MappedTypes[Ty];
257224145Sdim  if (*Entry) return *Entry;
258224145Sdim
259224145Sdim  // If this is not a named struct type, then just map all of the elements and
260224145Sdim  // then rebuild the type from inside out.
261226890Sdim  if (!isa<StructType>(Ty) || cast<StructType>(Ty)->isLiteral()) {
262224145Sdim    // If there are no element types to map, then the type is itself.  This is
263224145Sdim    // true for the anonymous {} struct, things like 'float', integers, etc.
264224145Sdim    if (Ty->getNumContainedTypes() == 0)
265224145Sdim      return *Entry = Ty;
266224145Sdim
267224145Sdim    // Remap all of the elements, keeping track of whether any of them change.
268224145Sdim    bool AnyChange = false;
269224145Sdim    SmallVector<Type*, 4> ElementTypes;
270224145Sdim    ElementTypes.resize(Ty->getNumContainedTypes());
271224145Sdim    for (unsigned i = 0, e = Ty->getNumContainedTypes(); i != e; ++i) {
272224145Sdim      ElementTypes[i] = getImpl(Ty->getContainedType(i));
273224145Sdim      AnyChange |= ElementTypes[i] != Ty->getContainedType(i);
274224145Sdim    }
275224145Sdim
276224145Sdim    // If we found our type while recursively processing stuff, just use it.
277224145Sdim    Entry = &MappedTypes[Ty];
278224145Sdim    if (*Entry) return *Entry;
279224145Sdim
280224145Sdim    // If all of the element types mapped directly over, then the type is usable
281224145Sdim    // as-is.
282224145Sdim    if (!AnyChange)
283224145Sdim      return *Entry = Ty;
284224145Sdim
285224145Sdim    // Otherwise, rebuild a modified type.
286224145Sdim    switch (Ty->getTypeID()) {
287235633Sdim    default: llvm_unreachable("unknown derived type to remap");
288224145Sdim    case Type::ArrayTyID:
289224145Sdim      return *Entry = ArrayType::get(ElementTypes[0],
290224145Sdim                                     cast<ArrayType>(Ty)->getNumElements());
291224145Sdim    case Type::VectorTyID:
292224145Sdim      return *Entry = VectorType::get(ElementTypes[0],
293224145Sdim                                      cast<VectorType>(Ty)->getNumElements());
294224145Sdim    case Type::PointerTyID:
295224145Sdim      return *Entry = PointerType::get(ElementTypes[0],
296224145Sdim                                      cast<PointerType>(Ty)->getAddressSpace());
297224145Sdim    case Type::FunctionTyID:
298224145Sdim      return *Entry = FunctionType::get(ElementTypes[0],
299226890Sdim                                        makeArrayRef(ElementTypes).slice(1),
300224145Sdim                                        cast<FunctionType>(Ty)->isVarArg());
301224145Sdim    case Type::StructTyID:
302224145Sdim      // Note that this is only reached for anonymous structs.
303224145Sdim      return *Entry = StructType::get(Ty->getContext(), ElementTypes,
304224145Sdim                                      cast<StructType>(Ty)->isPacked());
305224145Sdim    }
306224145Sdim  }
307193323Sed
308224145Sdim  // Otherwise, this is an unmapped named struct.  If the struct can be directly
309224145Sdim  // mapped over, just use it as-is.  This happens in a case when the linked-in
310224145Sdim  // module has something like:
311224145Sdim  //   %T = type {%T*, i32}
312224145Sdim  //   @GV = global %T* null
313224145Sdim  // where T does not exist at all in the destination module.
314224145Sdim  //
315224145Sdim  // The other case we watch for is when the type is not in the destination
316224145Sdim  // module, but that it has to be rebuilt because it refers to something that
317224145Sdim  // is already mapped.  For example, if the destination module has:
318224145Sdim  //  %A = type { i32 }
319224145Sdim  // and the source module has something like
320224145Sdim  //  %A' = type { i32 }
321224145Sdim  //  %B = type { %A'* }
322224145Sdim  //  @GV = global %B* null
323224145Sdim  // then we want to create a new type: "%B = type { %A*}" and have it take the
324224145Sdim  // pristine "%B" name from the source module.
325224145Sdim  //
326224145Sdim  // To determine which case this is, we have to recursively walk the type graph
327224145Sdim  // speculating that we'll be able to reuse it unmodified.  Only if this is
328224145Sdim  // safe would we map the entire thing over.  Because this is an optimization,
329224145Sdim  // and is not required for the prettiness of the linked module, we just skip
330224145Sdim  // it and always rebuild a type here.
331224145Sdim  StructType *STy = cast<StructType>(Ty);
332224145Sdim
333224145Sdim  // If the type is opaque, we can just use it directly.
334252723Sdim  if (STy->isOpaque()) {
335252723Sdim    // A named structure type from src module is used. Add it to the Set of
336252723Sdim    // identified structs in the destination module.
337252723Sdim    DstStructTypesSet.insert(STy);
338224145Sdim    return *Entry = STy;
339252723Sdim  }
340224145Sdim
341224145Sdim  // Otherwise we create a new type and resolve its body later.  This will be
342224145Sdim  // resolved by the top level of get().
343235633Sdim  SrcDefinitionsToResolve.push_back(STy);
344235633Sdim  StructType *DTy = StructType::create(STy->getContext());
345252723Sdim  // A new identified structure type was created. Add it to the set of
346252723Sdim  // identified structs in the destination module.
347252723Sdim  DstStructTypesSet.insert(DTy);
348235633Sdim  DstResolvedOpaqueTypes.insert(DTy);
349235633Sdim  return *Entry = DTy;
350224145Sdim}
351193323Sed
352224145Sdim//===----------------------------------------------------------------------===//
353224145Sdim// ModuleLinker implementation.
354224145Sdim//===----------------------------------------------------------------------===//
355193323Sed
356224145Sdimnamespace {
357263509Sdim  class ModuleLinker;
358263509Sdim
359263509Sdim  /// ValueMaterializerTy - Creates prototypes for functions that are lazily
360263509Sdim  /// linked on the fly. This speeds up linking for modules with many
361263509Sdim  /// lazily linked functions of which few get used.
362263509Sdim  class ValueMaterializerTy : public ValueMaterializer {
363263509Sdim    TypeMapTy &TypeMap;
364263509Sdim    Module *DstM;
365263509Sdim    std::vector<Function*> &LazilyLinkFunctions;
366263509Sdim  public:
367263509Sdim    ValueMaterializerTy(TypeMapTy &TypeMap, Module *DstM,
368263509Sdim                        std::vector<Function*> &LazilyLinkFunctions) :
369263509Sdim      ValueMaterializer(), TypeMap(TypeMap), DstM(DstM),
370263509Sdim      LazilyLinkFunctions(LazilyLinkFunctions) {
371263509Sdim    }
372263509Sdim
373263509Sdim    virtual Value *materializeValueFor(Value *V);
374263509Sdim  };
375263509Sdim
376224145Sdim  /// ModuleLinker - This is an implementation class for the LinkModules
377224145Sdim  /// function, which is the entrypoint for this file.
378224145Sdim  class ModuleLinker {
379224145Sdim    Module *DstM, *SrcM;
380224145Sdim
381224145Sdim    TypeMapTy TypeMap;
382263509Sdim    ValueMaterializerTy ValMaterializer;
383193323Sed
384224145Sdim    /// ValueMap - Mapping of values from what they used to be in Src, to what
385224145Sdim    /// they are now in DstM.  ValueToValueMapTy is a ValueMap, which involves
386224145Sdim    /// some overhead due to the use of Value handles which the Linker doesn't
387224145Sdim    /// actually need, but this allows us to reuse the ValueMapper code.
388224145Sdim    ValueToValueMapTy ValueMap;
389224145Sdim
390224145Sdim    struct AppendingVarInfo {
391224145Sdim      GlobalVariable *NewGV;  // New aggregate global in dest module.
392224145Sdim      Constant *DstInit;      // Old initializer from dest module.
393224145Sdim      Constant *SrcInit;      // Old initializer from src module.
394224145Sdim    };
395224145Sdim
396224145Sdim    std::vector<AppendingVarInfo> AppendingVars;
397224145Sdim
398226890Sdim    unsigned Mode; // Mode to treat source module.
399226890Sdim
400226890Sdim    // Set of items not to link in from source.
401226890Sdim    SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
402226890Sdim
403235633Sdim    // Vector of functions to lazily link in.
404235633Sdim    std::vector<Function*> LazilyLinkFunctions;
405235633Sdim
406224145Sdim  public:
407224145Sdim    std::string ErrorMsg;
408224145Sdim
409252723Sdim    ModuleLinker(Module *dstM, TypeSet &Set, Module *srcM, unsigned mode)
410263509Sdim      : DstM(dstM), SrcM(srcM), TypeMap(Set),
411263509Sdim        ValMaterializer(TypeMap, DstM, LazilyLinkFunctions),
412263509Sdim        Mode(mode) { }
413224145Sdim
414224145Sdim    bool run();
415224145Sdim
416224145Sdim  private:
417224145Sdim    /// emitError - Helper method for setting a message and returning an error
418224145Sdim    /// code.
419224145Sdim    bool emitError(const Twine &Message) {
420224145Sdim      ErrorMsg = Message.str();
421224145Sdim      return true;
422193323Sed    }
423224145Sdim
424224145Sdim    /// getLinkageResult - This analyzes the two global values and determines
425224145Sdim    /// what the result will look like in the destination module.
426224145Sdim    bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
427235633Sdim                          GlobalValue::LinkageTypes &LT,
428235633Sdim                          GlobalValue::VisibilityTypes &Vis,
429235633Sdim                          bool &LinkFromSrc);
430193323Sed
431224145Sdim    /// getLinkedToGlobal - Given a global in the source module, return the
432224145Sdim    /// global in the destination module that is being linked to, if any.
433224145Sdim    GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
434224145Sdim      // If the source has no name it can't link.  If it has local linkage,
435224145Sdim      // there is no name match-up going on.
436224145Sdim      if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
437224145Sdim        return 0;
438224145Sdim
439224145Sdim      // Otherwise see if we have a match in the destination module's symtab.
440224145Sdim      GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
441224145Sdim      if (DGV == 0) return 0;
442224145Sdim
443224145Sdim      // If we found a global with the same name in the dest module, but it has
444224145Sdim      // internal linkage, we are really not doing any linkage here.
445224145Sdim      if (DGV->hasLocalLinkage())
446224145Sdim        return 0;
447193323Sed
448224145Sdim      // Otherwise, we do in fact link to the destination global.
449224145Sdim      return DGV;
450193323Sed    }
451224145Sdim
452224145Sdim    void computeTypeMapping();
453224145Sdim
454224145Sdim    bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
455224145Sdim    bool linkGlobalProto(GlobalVariable *SrcGV);
456224145Sdim    bool linkFunctionProto(Function *SrcF);
457224145Sdim    bool linkAliasProto(GlobalAlias *SrcA);
458235633Sdim    bool linkModuleFlagsMetadata();
459224145Sdim
460224145Sdim    void linkAppendingVarInit(const AppendingVarInfo &AVI);
461224145Sdim    void linkGlobalInits();
462224145Sdim    void linkFunctionBody(Function *Dst, Function *Src);
463224145Sdim    void linkAliasBodies();
464224145Sdim    void linkNamedMDNodes();
465224145Sdim  };
466224145Sdim}
467193323Sed
468224145Sdim/// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
469193323Sed/// in the symbol table.  This is good for all clients except for us.  Go
470193323Sed/// through the trouble to force this back.
471224145Sdimstatic void forceRenaming(GlobalValue *GV, StringRef Name) {
472224145Sdim  // If the global doesn't force its name or if it already has the right name,
473224145Sdim  // there is nothing for us to do.
474224145Sdim  if (GV->hasLocalLinkage() || GV->getName() == Name)
475224145Sdim    return;
476193323Sed
477224145Sdim  Module *M = GV->getParent();
478224145Sdim
479193323Sed  // If there is a conflict, rename the conflict.
480224145Sdim  if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
481193323Sed    GV->takeName(ConflictGV);
482193323Sed    ConflictGV->setName(Name);    // This will cause ConflictGV to get renamed
483224145Sdim    assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
484193323Sed  } else {
485193323Sed    GV->setName(Name);              // Force the name back
486193323Sed  }
487193323Sed}
488193323Sed
489235633Sdim/// copyGVAttributes - copy additional attributes (those not needed to construct
490193323Sed/// a GlobalValue) from the SrcGV to the DestGV.
491235633Sdimstatic void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
492193323Sed  // Use the maximum alignment, rather than just copying the alignment of SrcGV.
493193323Sed  unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
494193323Sed  DestGV->copyAttributesFrom(SrcGV);
495193323Sed  DestGV->setAlignment(Alignment);
496224145Sdim
497224145Sdim  forceRenaming(DestGV, SrcGV->getName());
498193323Sed}
499193323Sed
500235633Sdimstatic bool isLessConstraining(GlobalValue::VisibilityTypes a,
501235633Sdim                               GlobalValue::VisibilityTypes b) {
502235633Sdim  if (a == GlobalValue::HiddenVisibility)
503235633Sdim    return false;
504235633Sdim  if (b == GlobalValue::HiddenVisibility)
505235633Sdim    return true;
506235633Sdim  if (a == GlobalValue::ProtectedVisibility)
507235633Sdim    return false;
508235633Sdim  if (b == GlobalValue::ProtectedVisibility)
509235633Sdim    return true;
510235633Sdim  return false;
511235633Sdim}
512235633Sdim
513263509SdimValue *ValueMaterializerTy::materializeValueFor(Value *V) {
514263509Sdim  Function *SF = dyn_cast<Function>(V);
515263509Sdim  if (!SF)
516263509Sdim    return NULL;
517263509Sdim
518263509Sdim  Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
519263509Sdim                                  SF->getLinkage(), SF->getName(), DstM);
520263509Sdim  copyGVAttributes(DF, SF);
521263509Sdim
522263509Sdim  LazilyLinkFunctions.push_back(SF);
523263509Sdim  return DF;
524263509Sdim}
525263509Sdim
526263509Sdim
527224145Sdim/// getLinkageResult - This analyzes the two global values and determines what
528193323Sed/// the result will look like in the destination module.  In particular, it
529235633Sdim/// computes the resultant linkage type and visibility, computes whether the
530235633Sdim/// global in the source should be copied over to the destination (replacing
531235633Sdim/// the existing one), and computes whether this linkage is an error or not.
532224145Sdimbool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
533235633Sdim                                    GlobalValue::LinkageTypes &LT,
534235633Sdim                                    GlobalValue::VisibilityTypes &Vis,
535224145Sdim                                    bool &LinkFromSrc) {
536224145Sdim  assert(Dest && "Must have two globals being queried");
537224145Sdim  assert(!Src->hasLocalLinkage() &&
538193323Sed         "If Src has internal linkage, Dest shouldn't be set!");
539224145Sdim
540235633Sdim  bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
541224145Sdim  bool DestIsDeclaration = Dest->isDeclaration();
542224145Sdim
543224145Sdim  if (SrcIsDeclaration) {
544193323Sed    // If Src is external or if both Src & Dest are external..  Just link the
545193323Sed    // external globals, we aren't adding anything.
546193323Sed    if (Src->hasDLLImportLinkage()) {
547193323Sed      // If one of GVs has DLLImport linkage, result should be dllimport'ed.
548224145Sdim      if (DestIsDeclaration) {
549193323Sed        LinkFromSrc = true;
550193323Sed        LT = Src->getLinkage();
551193323Sed      }
552193323Sed    } else if (Dest->hasExternalWeakLinkage()) {
553193323Sed      // If the Dest is weak, use the source linkage.
554193323Sed      LinkFromSrc = true;
555193323Sed      LT = Src->getLinkage();
556193323Sed    } else {
557193323Sed      LinkFromSrc = false;
558193323Sed      LT = Dest->getLinkage();
559193323Sed    }
560224145Sdim  } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
561193323Sed    // If Dest is external but Src is not:
562193323Sed    LinkFromSrc = true;
563193323Sed    LT = Src->getLinkage();
564193323Sed  } else if (Src->isWeakForLinker()) {
565193323Sed    // At this point we know that Dest has LinkOnce, External*, Weak, Common,
566193323Sed    // or DLL* linkage.
567193323Sed    if (Dest->hasExternalWeakLinkage() ||
568193323Sed        Dest->hasAvailableExternallyLinkage() ||
569193323Sed        (Dest->hasLinkOnceLinkage() &&
570193323Sed         (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
571193323Sed      LinkFromSrc = true;
572193323Sed      LT = Src->getLinkage();
573193323Sed    } else {
574193323Sed      LinkFromSrc = false;
575193323Sed      LT = Dest->getLinkage();
576193323Sed    }
577193323Sed  } else if (Dest->isWeakForLinker()) {
578193323Sed    // At this point we know that Src has External* or DLL* linkage.
579193323Sed    if (Src->hasExternalWeakLinkage()) {
580193323Sed      LinkFromSrc = false;
581193323Sed      LT = Dest->getLinkage();
582193323Sed    } else {
583193323Sed      LinkFromSrc = true;
584193323Sed      LT = GlobalValue::ExternalLinkage;
585193323Sed    }
586193323Sed  } else {
587224145Sdim    assert((Dest->hasExternalLinkage()  || Dest->hasDLLImportLinkage() ||
588224145Sdim            Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
589224145Sdim           (Src->hasExternalLinkage()   || Src->hasDLLImportLinkage() ||
590224145Sdim            Src->hasDLLExportLinkage()  || Src->hasExternalWeakLinkage()) &&
591193323Sed           "Unexpected linkage type!");
592224145Sdim    return emitError("Linking globals named '" + Src->getName() +
593193323Sed                 "': symbol multiply defined!");
594193323Sed  }
595193323Sed
596235633Sdim  // Compute the visibility. We follow the rules in the System V Application
597235633Sdim  // Binary Interface.
598235633Sdim  Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
599235633Sdim    Dest->getVisibility() : Src->getVisibility();
600193323Sed  return false;
601193323Sed}
602193323Sed
603224145Sdim/// computeTypeMapping - Loop over all of the linked values to compute type
604224145Sdim/// mappings.  For example, if we link "extern Foo *x" and "Foo *x = NULL", then
605224145Sdim/// we have two struct types 'Foo' but one got renamed when the module was
606224145Sdim/// loaded into the same LLVMContext.
607224145Sdimvoid ModuleLinker::computeTypeMapping() {
608224145Sdim  // Incorporate globals.
609224145Sdim  for (Module::global_iterator I = SrcM->global_begin(),
610224145Sdim       E = SrcM->global_end(); I != E; ++I) {
611224145Sdim    GlobalValue *DGV = getLinkedToGlobal(I);
612224145Sdim    if (DGV == 0) continue;
613224145Sdim
614224145Sdim    if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
615224145Sdim      TypeMap.addTypeMapping(DGV->getType(), I->getType());
616224145Sdim      continue;
617224145Sdim    }
618224145Sdim
619224145Sdim    // Unify the element type of appending arrays.
620224145Sdim    ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
621224145Sdim    ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
622224145Sdim    TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
623198090Srdivacky  }
624224145Sdim
625224145Sdim  // Incorporate functions.
626224145Sdim  for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
627224145Sdim    if (GlobalValue *DGV = getLinkedToGlobal(I))
628224145Sdim      TypeMap.addTypeMapping(DGV->getType(), I->getType());
629224145Sdim  }
630235633Sdim
631235633Sdim  // Incorporate types by name, scanning all the types in the source module.
632235633Sdim  // At this point, the destination module may have a type "%foo = { i32 }" for
633235633Sdim  // example.  When the source module got loaded into the same LLVMContext, if
634235633Sdim  // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
635245431Sdim  TypeFinder SrcStructTypes;
636245431Sdim  SrcStructTypes.run(*SrcM, true);
637235633Sdim  SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
638235633Sdim                                                 SrcStructTypes.end());
639235633Sdim
640235633Sdim  for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
641235633Sdim    StructType *ST = SrcStructTypes[i];
642235633Sdim    if (!ST->hasName()) continue;
643235633Sdim
644235633Sdim    // Check to see if there is a dot in the name followed by a digit.
645235633Sdim    size_t DotPos = ST->getName().rfind('.');
646235633Sdim    if (DotPos == 0 || DotPos == StringRef::npos ||
647252723Sdim        ST->getName().back() == '.' ||
648252723Sdim        !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
649235633Sdim      continue;
650235633Sdim
651235633Sdim    // Check to see if the destination module has a struct with the prefix name.
652235633Sdim    if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
653235633Sdim      // Don't use it if this actually came from the source module. They're in
654235633Sdim      // the same LLVMContext after all. Also don't use it unless the type is
655235633Sdim      // actually used in the destination module. This can happen in situations
656235633Sdim      // like this:
657235633Sdim      //
658235633Sdim      //      Module A                         Module B
659235633Sdim      //      --------                         --------
660235633Sdim      //   %Z = type { %A }                %B = type { %C.1 }
661235633Sdim      //   %A = type { %B.1, [7 x i8] }    %C.1 = type { i8* }
662235633Sdim      //   %B.1 = type { %C }              %A.2 = type { %B.3, [5 x i8] }
663235633Sdim      //   %C = type { i8* }               %B.3 = type { %C.1 }
664235633Sdim      //
665235633Sdim      // When we link Module B with Module A, the '%B' in Module B is
666235633Sdim      // used. However, that would then use '%C.1'. But when we process '%C.1',
667235633Sdim      // we prefer to take the '%C' version. So we are then left with both
668235633Sdim      // '%C.1' and '%C' being used for the same types. This leads to some
669235633Sdim      // variables using one type and some using the other.
670252723Sdim      if (!SrcStructTypesSet.count(DST) && TypeMap.DstStructTypesSet.count(DST))
671235633Sdim        TypeMap.addTypeMapping(DST, ST);
672235633Sdim  }
673235633Sdim
674224145Sdim  // Don't bother incorporating aliases, they aren't generally typed well.
675224145Sdim
676224145Sdim  // Now that we have discovered all of the type equivalences, get a body for
677224145Sdim  // any 'opaque' types in the dest module that are now resolved.
678224145Sdim  TypeMap.linkDefinedTypeBodies();
679198090Srdivacky}
680198090Srdivacky
681224145Sdim/// linkAppendingVarProto - If there were any appending global variables, link
682224145Sdim/// them together now.  Return true on error.
683224145Sdimbool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
684224145Sdim                                         GlobalVariable *SrcGV) {
685224145Sdim
686224145Sdim  if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
687224145Sdim    return emitError("Linking globals named '" + SrcGV->getName() +
688224145Sdim           "': can only link appending global with another appending global!");
689224145Sdim
690224145Sdim  ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
691224145Sdim  ArrayType *SrcTy =
692224145Sdim    cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
693224145Sdim  Type *EltTy = DstTy->getElementType();
694224145Sdim
695224145Sdim  // Check to see that they two arrays agree on type.
696224145Sdim  if (EltTy != SrcTy->getElementType())
697224145Sdim    return emitError("Appending variables with different element types!");
698224145Sdim  if (DstGV->isConstant() != SrcGV->isConstant())
699224145Sdim    return emitError("Appending variables linked with different const'ness!");
700224145Sdim
701224145Sdim  if (DstGV->getAlignment() != SrcGV->getAlignment())
702224145Sdim    return emitError(
703224145Sdim             "Appending variables with different alignment need to be linked!");
704224145Sdim
705224145Sdim  if (DstGV->getVisibility() != SrcGV->getVisibility())
706224145Sdim    return emitError(
707224145Sdim            "Appending variables with different visibility need to be linked!");
708263509Sdim
709263509Sdim  if (DstGV->hasUnnamedAddr() != SrcGV->hasUnnamedAddr())
710263509Sdim    return emitError(
711263509Sdim        "Appending variables with different unnamed_addr need to be linked!");
712263509Sdim
713224145Sdim  if (DstGV->getSection() != SrcGV->getSection())
714224145Sdim    return emitError(
715224145Sdim          "Appending variables with different section name need to be linked!");
716224145Sdim
717224145Sdim  uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
718224145Sdim  ArrayType *NewType = ArrayType::get(EltTy, NewSize);
719224145Sdim
720224145Sdim  // Create the new global variable.
721224145Sdim  GlobalVariable *NG =
722224145Sdim    new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
723224145Sdim                       DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
724245431Sdim                       DstGV->getThreadLocalMode(),
725224145Sdim                       DstGV->getType()->getAddressSpace());
726224145Sdim
727224145Sdim  // Propagate alignment, visibility and section info.
728235633Sdim  copyGVAttributes(NG, DstGV);
729224145Sdim
730224145Sdim  AppendingVarInfo AVI;
731224145Sdim  AVI.NewGV = NG;
732224145Sdim  AVI.DstInit = DstGV->getInitializer();
733224145Sdim  AVI.SrcInit = SrcGV->getInitializer();
734224145Sdim  AppendingVars.push_back(AVI);
735193323Sed
736224145Sdim  // Replace any uses of the two global variables with uses of the new
737224145Sdim  // global.
738224145Sdim  ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
739193323Sed
740224145Sdim  DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
741224145Sdim  DstGV->eraseFromParent();
742224145Sdim
743226890Sdim  // Track the source variable so we don't try to link it.
744226890Sdim  DoNotLinkFromSource.insert(SrcGV);
745226890Sdim
746224145Sdim  return false;
747224145Sdim}
748193323Sed
749224145Sdim/// linkGlobalProto - Loop through the global variables in the src module and
750224145Sdim/// merge them into the dest module.
751224145Sdimbool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
752224145Sdim  GlobalValue *DGV = getLinkedToGlobal(SGV);
753235633Sdim  llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
754263509Sdim  bool HasUnnamedAddr = SGV->hasUnnamedAddr();
755193323Sed
756224145Sdim  if (DGV) {
757224145Sdim    // Concatenation of appending linkage variables is magic and handled later.
758224145Sdim    if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
759224145Sdim      return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
760224145Sdim
761224145Sdim    // Determine whether linkage of these two globals follows the source
762224145Sdim    // module's definition or the destination module's definition.
763193323Sed    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
764235633Sdim    GlobalValue::VisibilityTypes NV;
765193323Sed    bool LinkFromSrc = false;
766235633Sdim    if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
767193323Sed      return true;
768235633Sdim    NewVisibility = NV;
769263509Sdim    HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
770193323Sed
771224145Sdim    // If we're not linking from the source, then keep the definition that we
772224145Sdim    // have.
773224145Sdim    if (!LinkFromSrc) {
774224145Sdim      // Special case for const propagation.
775224145Sdim      if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
776224145Sdim        if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
777224145Sdim          DGVar->setConstant(true);
778263509Sdim
779263509Sdim      // Set calculated linkage, visibility and unnamed_addr.
780224145Sdim      DGV->setLinkage(NewLinkage);
781235633Sdim      DGV->setVisibility(*NewVisibility);
782263509Sdim      DGV->setUnnamedAddr(HasUnnamedAddr);
783235633Sdim
784193323Sed      // Make sure to remember this mapping.
785224145Sdim      ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
786224145Sdim
787226890Sdim      // Track the source global so that we don't attempt to copy it over when
788226890Sdim      // processing global initializers.
789226890Sdim      DoNotLinkFromSource.insert(SGV);
790226890Sdim
791224145Sdim      return false;
792193323Sed    }
793224145Sdim  }
794224145Sdim
795224145Sdim  // No linking to be performed or linking from the source: simply create an
796224145Sdim  // identical version of the symbol over in the dest module... the
797224145Sdim  // initializer will be filled in later by LinkGlobalInits.
798224145Sdim  GlobalVariable *NewDGV =
799224145Sdim    new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
800224145Sdim                       SGV->isConstant(), SGV->getLinkage(), /*init*/0,
801224145Sdim                       SGV->getName(), /*insertbefore*/0,
802245431Sdim                       SGV->getThreadLocalMode(),
803224145Sdim                       SGV->getType()->getAddressSpace());
804224145Sdim  // Propagate alignment, visibility and section info.
805235633Sdim  copyGVAttributes(NewDGV, SGV);
806235633Sdim  if (NewVisibility)
807235633Sdim    NewDGV->setVisibility(*NewVisibility);
808263509Sdim  NewDGV->setUnnamedAddr(HasUnnamedAddr);
809193323Sed
810224145Sdim  if (DGV) {
811224145Sdim    DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
812224145Sdim    DGV->eraseFromParent();
813193323Sed  }
814224145Sdim
815224145Sdim  // Make sure to remember this mapping.
816224145Sdim  ValueMap[SGV] = NewDGV;
817193323Sed  return false;
818193323Sed}
819193323Sed
820224145Sdim/// linkFunctionProto - Link the function in the source module into the
821224145Sdim/// destination module if needed, setting up mapping information.
822224145Sdimbool ModuleLinker::linkFunctionProto(Function *SF) {
823224145Sdim  GlobalValue *DGV = getLinkedToGlobal(SF);
824235633Sdim  llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
825263509Sdim  bool HasUnnamedAddr = SF->hasUnnamedAddr();
826193323Sed
827224145Sdim  if (DGV) {
828224145Sdim    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
829224145Sdim    bool LinkFromSrc = false;
830235633Sdim    GlobalValue::VisibilityTypes NV;
831235633Sdim    if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
832224145Sdim      return true;
833235633Sdim    NewVisibility = NV;
834263509Sdim    HasUnnamedAddr = HasUnnamedAddr && DGV->hasUnnamedAddr();
835235633Sdim
836224145Sdim    if (!LinkFromSrc) {
837224145Sdim      // Set calculated linkage
838224145Sdim      DGV->setLinkage(NewLinkage);
839235633Sdim      DGV->setVisibility(*NewVisibility);
840263509Sdim      DGV->setUnnamedAddr(HasUnnamedAddr);
841235633Sdim
842224145Sdim      // Make sure to remember this mapping.
843224145Sdim      ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
844224145Sdim
845226890Sdim      // Track the function from the source module so we don't attempt to remap
846226890Sdim      // it.
847226890Sdim      DoNotLinkFromSource.insert(SF);
848226890Sdim
849224145Sdim      return false;
850193323Sed    }
851193323Sed  }
852224145Sdim
853263509Sdim  // If the function is to be lazily linked, don't create it just yet.
854263509Sdim  // The ValueMaterializerTy will deal with creating it if it's used.
855263509Sdim  if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
856263509Sdim               SF->hasAvailableExternallyLinkage())) {
857263509Sdim    DoNotLinkFromSource.insert(SF);
858263509Sdim    return false;
859263509Sdim  }
860263509Sdim
861224145Sdim  // If there is no linkage to be performed or we are linking from the source,
862224145Sdim  // bring SF over.
863224145Sdim  Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
864224145Sdim                                     SF->getLinkage(), SF->getName(), DstM);
865235633Sdim  copyGVAttributes(NewDF, SF);
866235633Sdim  if (NewVisibility)
867235633Sdim    NewDF->setVisibility(*NewVisibility);
868263509Sdim  NewDF->setUnnamedAddr(HasUnnamedAddr);
869193323Sed
870224145Sdim  if (DGV) {
871224145Sdim    // Any uses of DF need to change to NewDF, with cast.
872224145Sdim    DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
873224145Sdim    DGV->eraseFromParent();
874193323Sed  }
875224145Sdim
876224145Sdim  ValueMap[SF] = NewDF;
877193323Sed  return false;
878193323Sed}
879193323Sed
880224145Sdim/// LinkAliasProto - Set up prototypes for any aliases that come over from the
881224145Sdim/// source module.
882224145Sdimbool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
883224145Sdim  GlobalValue *DGV = getLinkedToGlobal(SGA);
884235633Sdim  llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
885235633Sdim
886224145Sdim  if (DGV) {
887193323Sed    GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
888235633Sdim    GlobalValue::VisibilityTypes NV;
889193323Sed    bool LinkFromSrc = false;
890235633Sdim    if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
891193323Sed      return true;
892235633Sdim    NewVisibility = NV;
893235633Sdim
894224145Sdim    if (!LinkFromSrc) {
895224145Sdim      // Set calculated linkage.
896224145Sdim      DGV->setLinkage(NewLinkage);
897235633Sdim      DGV->setVisibility(*NewVisibility);
898235633Sdim
899224145Sdim      // Make sure to remember this mapping.
900224145Sdim      ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
901224145Sdim
902226890Sdim      // Track the alias from the source module so we don't attempt to remap it.
903226890Sdim      DoNotLinkFromSource.insert(SGA);
904226890Sdim
905224145Sdim      return false;
906193323Sed    }
907224145Sdim  }
908224145Sdim
909224145Sdim  // If there is no linkage to be performed or we're linking from the source,
910224145Sdim  // bring over SGA.
911224145Sdim  GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
912224145Sdim                                       SGA->getLinkage(), SGA->getName(),
913224145Sdim                                       /*aliasee*/0, DstM);
914235633Sdim  copyGVAttributes(NewDA, SGA);
915235633Sdim  if (NewVisibility)
916235633Sdim    NewDA->setVisibility(*NewVisibility);
917193323Sed
918224145Sdim  if (DGV) {
919224145Sdim    // Any uses of DGV need to change to NewDA, with cast.
920224145Sdim    DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
921224145Sdim    DGV->eraseFromParent();
922224145Sdim  }
923224145Sdim
924224145Sdim  ValueMap[SGA] = NewDA;
925224145Sdim  return false;
926224145Sdim}
927193323Sed
928235633Sdimstatic void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
929235633Sdim  unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
930235633Sdim
931235633Sdim  for (unsigned i = 0; i != NumElements; ++i)
932235633Sdim    Dest.push_back(C->getAggregateElement(i));
933235633Sdim}
934235633Sdim
935224145Sdimvoid ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
936224145Sdim  // Merge the initializer.
937224145Sdim  SmallVector<Constant*, 16> Elements;
938235633Sdim  getArrayElements(AVI.DstInit, Elements);
939224145Sdim
940263509Sdim  Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap, &ValMaterializer);
941235633Sdim  getArrayElements(SrcInit, Elements);
942235633Sdim
943224145Sdim  ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
944224145Sdim  AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
945224145Sdim}
946193323Sed
947235633Sdim/// linkGlobalInits - Update the initializers in the Dest module now that all
948235633Sdim/// globals that may be referenced are in Dest.
949224145Sdimvoid ModuleLinker::linkGlobalInits() {
950224145Sdim  // Loop over all of the globals in the src module, mapping them over as we go
951224145Sdim  for (Module::const_global_iterator I = SrcM->global_begin(),
952224145Sdim       E = SrcM->global_end(); I != E; ++I) {
953224145Sdim
954226890Sdim    // Only process initialized GV's or ones not already in dest.
955226890Sdim    if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
956226890Sdim
957224145Sdim    // Grab destination global variable.
958224145Sdim    GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
959224145Sdim    // Figure out what the initializer looks like in the dest module.
960224145Sdim    DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
961263509Sdim                                 RF_None, &TypeMap, &ValMaterializer));
962193323Sed  }
963193323Sed}
964193323Sed
965235633Sdim/// linkFunctionBody - Copy the source function over into the dest function and
966235633Sdim/// fix up references to values.  At this point we know that Dest is an external
967235633Sdim/// function, and that Src is not.
968224145Sdimvoid ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
969224145Sdim  assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
970193323Sed
971193323Sed  // Go through and convert function arguments over, remembering the mapping.
972224145Sdim  Function::arg_iterator DI = Dst->arg_begin();
973193323Sed  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
974193323Sed       I != E; ++I, ++DI) {
975224145Sdim    DI->setName(I->getName());  // Copy the name over.
976193323Sed
977224145Sdim    // Add a mapping to our mapping.
978193323Sed    ValueMap[I] = DI;
979193323Sed  }
980193323Sed
981226890Sdim  if (Mode == Linker::DestroySource) {
982226890Sdim    // Splice the body of the source function into the dest function.
983226890Sdim    Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
984226890Sdim
985226890Sdim    // At this point, all of the instructions and values of the function are now
986226890Sdim    // copied over.  The only problem is that they are still referencing values in
987226890Sdim    // the Source function as operands.  Loop through all of the operands of the
988226890Sdim    // functions and patch them up to point to the local versions.
989226890Sdim    for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
990226890Sdim      for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
991263509Sdim        RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries,
992263509Sdim                         &TypeMap, &ValMaterializer);
993226890Sdim
994226890Sdim  } else {
995226890Sdim    // Clone the body of the function into the dest function.
996226890Sdim    SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
997263509Sdim    CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL,
998263509Sdim                      &TypeMap, &ValMaterializer);
999226890Sdim  }
1000226890Sdim
1001193323Sed  // There is no need to map the arguments anymore.
1002193323Sed  for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1003193323Sed       I != E; ++I)
1004193323Sed    ValueMap.erase(I);
1005226890Sdim
1006193323Sed}
1007193323Sed
1008235633Sdim/// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
1009224145Sdimvoid ModuleLinker::linkAliasBodies() {
1010224145Sdim  for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
1011226890Sdim       I != E; ++I) {
1012226890Sdim    if (DoNotLinkFromSource.count(I))
1013226890Sdim      continue;
1014224145Sdim    if (Constant *Aliasee = I->getAliasee()) {
1015224145Sdim      GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
1016263509Sdim      DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None,
1017263509Sdim                              &TypeMap, &ValMaterializer));
1018193323Sed    }
1019226890Sdim  }
1020193323Sed}
1021193323Sed
1022235633Sdim/// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
1023224145Sdim/// module.
1024224145Sdimvoid ModuleLinker::linkNamedMDNodes() {
1025235633Sdim  const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1026224145Sdim  for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
1027224145Sdim       E = SrcM->named_metadata_end(); I != E; ++I) {
1028235633Sdim    // Don't link module flags here. Do them separately.
1029235633Sdim    if (&*I == SrcModFlags) continue;
1030224145Sdim    NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
1031224145Sdim    // Add Src elements into Dest node.
1032224145Sdim    for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
1033224145Sdim      DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
1034263509Sdim                                   RF_None, &TypeMap, &ValMaterializer));
1035193323Sed  }
1036193323Sed}
1037235633Sdim
1038235633Sdim/// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1039235633Sdim/// module.
1040235633Sdimbool ModuleLinker::linkModuleFlagsMetadata() {
1041252723Sdim  // If the source module has no module flags, we are done.
1042235633Sdim  const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1043235633Sdim  if (!SrcModFlags) return false;
1044235633Sdim
1045235633Sdim  // If the destination module doesn't have module flags yet, then just copy
1046235633Sdim  // over the source module's flags.
1047252723Sdim  NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1048235633Sdim  if (DstModFlags->getNumOperands() == 0) {
1049235633Sdim    for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1050235633Sdim      DstModFlags->addOperand(SrcModFlags->getOperand(I));
1051235633Sdim
1052235633Sdim    return false;
1053235633Sdim  }
1054235633Sdim
1055252723Sdim  // First build a map of the existing module flags and requirements.
1056252723Sdim  DenseMap<MDString*, MDNode*> Flags;
1057252723Sdim  SmallSetVector<MDNode*, 16> Requirements;
1058252723Sdim  for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1059252723Sdim    MDNode *Op = DstModFlags->getOperand(I);
1060252723Sdim    ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1061252723Sdim    MDString *ID = cast<MDString>(Op->getOperand(1));
1062235633Sdim
1063252723Sdim    if (Behavior->getZExtValue() == Module::Require) {
1064252723Sdim      Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1065252723Sdim    } else {
1066252723Sdim      Flags[ID] = Op;
1067252723Sdim    }
1068235633Sdim  }
1069235633Sdim
1070252723Sdim  // Merge in the flags from the source module, and also collect its set of
1071252723Sdim  // requirements.
1072252723Sdim  bool HasErr = false;
1073252723Sdim  for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1074252723Sdim    MDNode *SrcOp = SrcModFlags->getOperand(I);
1075252723Sdim    ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1076252723Sdim    MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1077252723Sdim    MDNode *DstOp = Flags.lookup(ID);
1078252723Sdim    unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1079235633Sdim
1080252723Sdim    // If this is a requirement, add it and continue.
1081252723Sdim    if (SrcBehaviorValue == Module::Require) {
1082252723Sdim      // If the destination module does not already have this requirement, add
1083252723Sdim      // it.
1084252723Sdim      if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1085252723Sdim        DstModFlags->addOperand(SrcOp);
1086252723Sdim      }
1087252723Sdim      continue;
1088252723Sdim    }
1089235633Sdim
1090252723Sdim    // If there is no existing flag with this ID, just add it.
1091252723Sdim    if (!DstOp) {
1092252723Sdim      Flags[ID] = SrcOp;
1093252723Sdim      DstModFlags->addOperand(SrcOp);
1094252723Sdim      continue;
1095235633Sdim    }
1096235633Sdim
1097252723Sdim    // Otherwise, perform a merge.
1098252723Sdim    ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1099252723Sdim    unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1100235633Sdim
1101252723Sdim    // If either flag has override behavior, handle it first.
1102252723Sdim    if (DstBehaviorValue == Module::Override) {
1103252723Sdim      // Diagnose inconsistent flags which both have override behavior.
1104252723Sdim      if (SrcBehaviorValue == Module::Override &&
1105252723Sdim          SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1106252723Sdim        HasErr |= emitError("linking module flags '" + ID->getString() +
1107252723Sdim                            "': IDs have conflicting override values");
1108252723Sdim      }
1109252723Sdim      continue;
1110252723Sdim    } else if (SrcBehaviorValue == Module::Override) {
1111252723Sdim      // Update the destination flag to that of the source.
1112252723Sdim      DstOp->replaceOperandWith(0, SrcBehavior);
1113252723Sdim      DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1114252723Sdim      continue;
1115252723Sdim    }
1116235633Sdim
1117252723Sdim    // Diagnose inconsistent merge behavior types.
1118252723Sdim    if (SrcBehaviorValue != DstBehaviorValue) {
1119252723Sdim      HasErr |= emitError("linking module flags '" + ID->getString() +
1120252723Sdim                          "': IDs have conflicting behaviors");
1121252723Sdim      continue;
1122252723Sdim    }
1123235633Sdim
1124252723Sdim    // Perform the merge for standard behavior types.
1125252723Sdim    switch (SrcBehaviorValue) {
1126252723Sdim    case Module::Require:
1127252723Sdim    case Module::Override: assert(0 && "not possible"); break;
1128252723Sdim    case Module::Error: {
1129252723Sdim      // Emit an error if the values differ.
1130252723Sdim      if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1131252723Sdim        HasErr |= emitError("linking module flags '" + ID->getString() +
1132252723Sdim                            "': IDs have conflicting values");
1133235633Sdim      }
1134252723Sdim      continue;
1135252723Sdim    }
1136252723Sdim    case Module::Warning: {
1137252723Sdim      // Emit a warning if the values differ.
1138252723Sdim      if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1139252723Sdim        errs() << "WARNING: linking module flags '" << ID->getString()
1140252723Sdim               << "': IDs have conflicting values";
1141252723Sdim      }
1142252723Sdim      continue;
1143252723Sdim    }
1144252723Sdim    case Module::Append: {
1145252723Sdim      MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1146252723Sdim      MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1147252723Sdim      unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1148252723Sdim      Value **VP, **Values = VP = new Value*[NumOps];
1149252723Sdim      for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1150252723Sdim        *VP = DstValue->getOperand(i);
1151252723Sdim      for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1152252723Sdim        *VP = SrcValue->getOperand(i);
1153252723Sdim      DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1154252723Sdim                                               ArrayRef<Value*>(Values,
1155252723Sdim                                                                NumOps)));
1156252723Sdim      delete[] Values;
1157252723Sdim      break;
1158252723Sdim    }
1159252723Sdim    case Module::AppendUnique: {
1160252723Sdim      SmallSetVector<Value*, 16> Elts;
1161252723Sdim      MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1162252723Sdim      MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1163252723Sdim      for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1164252723Sdim        Elts.insert(DstValue->getOperand(i));
1165252723Sdim      for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1166252723Sdim        Elts.insert(SrcValue->getOperand(i));
1167252723Sdim      DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1168252723Sdim                                               ArrayRef<Value*>(Elts.begin(),
1169252723Sdim                                                                Elts.end())));
1170252723Sdim      break;
1171252723Sdim    }
1172252723Sdim    }
1173252723Sdim  }
1174235633Sdim
1175252723Sdim  // Check all of the requirements.
1176252723Sdim  for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1177252723Sdim    MDNode *Requirement = Requirements[I];
1178252723Sdim    MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1179252723Sdim    Value *ReqValue = Requirement->getOperand(1);
1180252723Sdim
1181252723Sdim    MDNode *Op = Flags[Flag];
1182252723Sdim    if (!Op || Op->getOperand(2) != ReqValue) {
1183252723Sdim      HasErr |= emitError("linking module flags '" + Flag->getString() +
1184252723Sdim                          "': does not have the required value");
1185252723Sdim      continue;
1186235633Sdim    }
1187235633Sdim  }
1188235633Sdim
1189235633Sdim  return HasErr;
1190235633Sdim}
1191224145Sdim
1192224145Sdimbool ModuleLinker::run() {
1193235633Sdim  assert(DstM && "Null destination module");
1194235633Sdim  assert(SrcM && "Null source module");
1195193323Sed
1196224145Sdim  // Inherit the target data from the source module if the destination module
1197224145Sdim  // doesn't have one already.
1198224145Sdim  if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1199224145Sdim    DstM->setDataLayout(SrcM->getDataLayout());
1200193323Sed
1201193323Sed  // Copy the target triple from the source to dest if the dest's is empty.
1202224145Sdim  if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1203224145Sdim    DstM->setTargetTriple(SrcM->getTargetTriple());
1204193323Sed
1205224145Sdim  if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1206224145Sdim      SrcM->getDataLayout() != DstM->getDataLayout())
1207198090Srdivacky    errs() << "WARNING: Linking two modules of different data layouts!\n";
1208224145Sdim  if (!SrcM->getTargetTriple().empty() &&
1209224145Sdim      DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1210218893Sdim    errs() << "WARNING: Linking two modules of different target triples: ";
1211224145Sdim    if (!SrcM->getModuleIdentifier().empty())
1212224145Sdim      errs() << SrcM->getModuleIdentifier() << ": ";
1213224145Sdim    errs() << "'" << SrcM->getTargetTriple() << "' and '"
1214224145Sdim           << DstM->getTargetTriple() << "'\n";
1215218893Sdim  }
1216193323Sed
1217193323Sed  // Append the module inline asm string.
1218224145Sdim  if (!SrcM->getModuleInlineAsm().empty()) {
1219224145Sdim    if (DstM->getModuleInlineAsm().empty())
1220224145Sdim      DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1221193323Sed    else
1222224145Sdim      DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1223224145Sdim                               SrcM->getModuleInlineAsm());
1224193323Sed  }
1225193323Sed
1226224145Sdim  // Loop over all of the linked values to compute type mappings.
1227224145Sdim  computeTypeMapping();
1228193323Sed
1229224145Sdim  // Insert all of the globals in src into the DstM module... without linking
1230193323Sed  // initializers (which could refer to functions not yet mapped over).
1231224145Sdim  for (Module::global_iterator I = SrcM->global_begin(),
1232224145Sdim       E = SrcM->global_end(); I != E; ++I)
1233224145Sdim    if (linkGlobalProto(I))
1234224145Sdim      return true;
1235193323Sed
1236193323Sed  // Link the functions together between the two modules, without doing function
1237224145Sdim  // bodies... this just adds external function prototypes to the DstM
1238193323Sed  // function...  We do this so that when we begin processing function bodies,
1239193323Sed  // all of the global values that may be referenced are available in our
1240193323Sed  // ValueMap.
1241224145Sdim  for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1242224145Sdim    if (linkFunctionProto(I))
1243224145Sdim      return true;
1244193323Sed
1245224145Sdim  // If there were any aliases, link them now.
1246224145Sdim  for (Module::alias_iterator I = SrcM->alias_begin(),
1247224145Sdim       E = SrcM->alias_end(); I != E; ++I)
1248224145Sdim    if (linkAliasProto(I))
1249224145Sdim      return true;
1250193323Sed
1251224145Sdim  for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1252224145Sdim    linkAppendingVarInit(AppendingVars[i]);
1253224145Sdim
1254224145Sdim  // Update the initializers in the DstM module now that all globals that may
1255224145Sdim  // be referenced are in DstM.
1256224145Sdim  linkGlobalInits();
1257193323Sed
1258224145Sdim  // Link in the function bodies that are defined in the source module into
1259224145Sdim  // DstM.
1260224145Sdim  for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1261226890Sdim    // Skip if not linking from source.
1262226890Sdim    if (DoNotLinkFromSource.count(SF)) continue;
1263226890Sdim
1264263509Sdim    Function *DF = cast<Function>(ValueMap[SF]);
1265263509Sdim    if (SF->hasPrefixData()) {
1266263509Sdim      // Link in the prefix data.
1267263509Sdim      DF->setPrefixData(MapValue(
1268263509Sdim          SF->getPrefixData(), ValueMap, RF_None, &TypeMap, &ValMaterializer));
1269263509Sdim    }
1270263509Sdim
1271226890Sdim    // Skip if no body (function is external) or materialize.
1272226890Sdim    if (SF->isDeclaration()) {
1273226890Sdim      if (!SF->isMaterializable())
1274226890Sdim        continue;
1275226890Sdim      if (SF->Materialize(&ErrorMsg))
1276226890Sdim        return true;
1277226890Sdim    }
1278226890Sdim
1279263509Sdim    linkFunctionBody(DF, SF);
1280235633Sdim    SF->Dematerialize();
1281224145Sdim  }
1282193323Sed
1283224145Sdim  // Resolve all uses of aliases with aliasees.
1284224145Sdim  linkAliasBodies();
1285193323Sed
1286235633Sdim  // Remap all of the named MDNodes in Src into the DstM module. We do this
1287226890Sdim  // after linking GlobalValues so that MDNodes that reference GlobalValues
1288226890Sdim  // are properly remapped.
1289226890Sdim  linkNamedMDNodes();
1290226890Sdim
1291235633Sdim  // Merge the module flags into the DstM module.
1292235633Sdim  if (linkModuleFlagsMetadata())
1293235633Sdim    return true;
1294235633Sdim
1295235633Sdim  // Process vector of lazily linked in functions.
1296235633Sdim  bool LinkedInAnyFunctions;
1297235633Sdim  do {
1298235633Sdim    LinkedInAnyFunctions = false;
1299235633Sdim
1300235633Sdim    for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1301263509Sdim        E = LazilyLinkFunctions.end(); I != E; ++I) {
1302263509Sdim      Function *SF = *I;
1303263509Sdim      if (!SF)
1304235633Sdim        continue;
1305263509Sdim
1306235633Sdim      Function *DF = cast<Function>(ValueMap[SF]);
1307263509Sdim      if (SF->hasPrefixData()) {
1308263509Sdim        // Link in the prefix data.
1309263509Sdim        DF->setPrefixData(MapValue(SF->getPrefixData(),
1310263509Sdim                                   ValueMap,
1311263509Sdim                                   RF_None,
1312263509Sdim                                   &TypeMap,
1313263509Sdim                                   &ValMaterializer));
1314263509Sdim      }
1315263509Sdim
1316263509Sdim      // Materialize if necessary.
1317263509Sdim      if (SF->isDeclaration()) {
1318263509Sdim        if (!SF->isMaterializable())
1319263509Sdim          continue;
1320263509Sdim        if (SF->Materialize(&ErrorMsg))
1321263509Sdim          return true;
1322263509Sdim      }
1323235633Sdim
1324263509Sdim      // Erase from vector *before* the function body is linked - linkFunctionBody could
1325263509Sdim      // invalidate I.
1326263509Sdim      LazilyLinkFunctions.erase(I);
1327235633Sdim
1328263509Sdim      // Link in function body.
1329263509Sdim      linkFunctionBody(DF, SF);
1330263509Sdim      SF->Dematerialize();
1331263509Sdim
1332263509Sdim      // Set flag to indicate we may have more functions to lazily link in
1333263509Sdim      // since we linked in a function.
1334263509Sdim      LinkedInAnyFunctions = true;
1335263509Sdim      break;
1336235633Sdim    }
1337235633Sdim  } while (LinkedInAnyFunctions);
1338235633Sdim
1339224145Sdim  // Now that all of the types from the source are used, resolve any structs
1340224145Sdim  // copied over to the dest that didn't exist there.
1341224145Sdim  TypeMap.linkDefinedTypeBodies();
1342224145Sdim
1343224145Sdim  return false;
1344224145Sdim}
1345193323Sed
1346252723SdimLinker::Linker(Module *M) : Composite(M) {
1347252723Sdim  TypeFinder StructTypes;
1348252723Sdim  StructTypes.run(*M, true);
1349252723Sdim  IdentifiedStructTypes.insert(StructTypes.begin(), StructTypes.end());
1350252723Sdim}
1351252723Sdim
1352252723SdimLinker::~Linker() {
1353252723Sdim}
1354252723Sdim
1355263509Sdimvoid Linker::deleteModule() {
1356263509Sdim  delete Composite;
1357263509Sdim  Composite = NULL;
1358263509Sdim}
1359263509Sdim
1360252723Sdimbool Linker::linkInModule(Module *Src, unsigned Mode, std::string *ErrorMsg) {
1361252723Sdim  ModuleLinker TheLinker(Composite, IdentifiedStructTypes, Src, Mode);
1362252723Sdim  if (TheLinker.run()) {
1363252723Sdim    if (ErrorMsg)
1364252723Sdim      *ErrorMsg = TheLinker.ErrorMsg;
1365252723Sdim    return true;
1366252723Sdim  }
1367252723Sdim  return false;
1368252723Sdim}
1369252723Sdim
1370224145Sdim//===----------------------------------------------------------------------===//
1371224145Sdim// LinkModules entrypoint.
1372224145Sdim//===----------------------------------------------------------------------===//
1373212904Sdim
1374235633Sdim/// LinkModules - This function links two modules together, with the resulting
1375252723Sdim/// Dest module modified to be the composite of the two input modules.  If an
1376235633Sdim/// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1377235633Sdim/// the problem.  Upon failure, the Dest module could be in a modified state,
1378235633Sdim/// and shouldn't be relied on to be consistent.
1379226890Sdimbool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1380226890Sdim                         std::string *ErrorMsg) {
1381252723Sdim  Linker L(Dest);
1382252723Sdim  return L.linkInModule(Src, Mode, ErrorMsg);
1383193323Sed}
1384245431Sdim
1385245431Sdim//===----------------------------------------------------------------------===//
1386245431Sdim// C API.
1387245431Sdim//===----------------------------------------------------------------------===//
1388245431Sdim
1389245431SdimLLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1390245431Sdim                         LLVMLinkerMode Mode, char **OutMessages) {
1391245431Sdim  std::string Messages;
1392245431Sdim  LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1393245431Sdim                                        Mode, OutMessages? &Messages : 0);
1394245431Sdim  if (OutMessages)
1395245431Sdim    *OutMessages = strdup(Messages.c_str());
1396245431Sdim  return Result;
1397245431Sdim}
1398