1 //===- lib/Linker/LinkModules.cpp - Module Linker Implementation ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVM module linker.
12 //===----------------------------------------------------------------------===//
14 #include "llvm/Linker.h"
15 #include "llvm-c/Linker.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/Optional.h"
18 #include "llvm/ADT/SetVector.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/IR/Constants.h"
22 #include "llvm/IR/DerivedTypes.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/Module.h"
25 #include "llvm/IR/TypeFinder.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Cloning.h"
29 #include "llvm/Transforms/Utils/ValueMapper.h"
33 //===----------------------------------------------------------------------===//
34 // TypeMap implementation.
35 //===----------------------------------------------------------------------===//
38 class TypeMapTy : public ValueMapTypeRemapper {
39 /// MappedTypes - This is a mapping from a source type to a destination type
41 DenseMap<Type*, Type*> MappedTypes;
43 /// SpeculativeTypes - When checking to see if two subgraphs are isomorphic,
44 /// we speculatively add types to MappedTypes, but keep track of them here in
45 /// case we need to roll back.
46 SmallVector<Type*, 16> SpeculativeTypes;
48 /// SrcDefinitionsToResolve - This is a list of non-opaque structs in the
49 /// source module that are mapped to an opaque struct in the destination
51 SmallVector<StructType*, 16> SrcDefinitionsToResolve;
53 /// DstResolvedOpaqueTypes - This is the set of opaque types in the
54 /// destination modules who are getting a body from the source module.
55 SmallPtrSet<StructType*, 16> DstResolvedOpaqueTypes;
58 /// addTypeMapping - Indicate that the specified type in the destination
59 /// module is conceptually equivalent to the specified type in the source
61 void addTypeMapping(Type *DstTy, Type *SrcTy);
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();
67 /// get - Return the mapped type to use for the specified input type from the
69 Type *get(Type *SrcTy);
71 FunctionType *get(FunctionType *T) {return cast<FunctionType>(get((Type*)T));}
73 /// dump - Dump out the type map for debugging purposes.
75 for (DenseMap<Type*, Type*>::const_iterator
76 I = MappedTypes.begin(), E = MappedTypes.end(); I != E; ++I) {
77 dbgs() << "TypeMap: ";
86 Type *getImpl(Type *T);
87 /// remapType - Implement the ValueMapTypeRemapper interface.
88 Type *remapType(Type *SrcTy) {
92 bool areTypesIsomorphic(Type *DstTy, Type *SrcTy);
96 void TypeMapTy::addTypeMapping(Type *DstTy, Type *SrcTy) {
97 Type *&Entry = MappedTypes[SrcTy];
100 if (DstTy == SrcTy) {
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]);
113 SpeculativeTypes.clear();
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;
122 // If we have an entry in the MappedTypes table, then we have our answer.
123 Type *&Entry = MappedTypes[SrcTy];
125 return Entry == DstTy;
127 // Two identical types are clearly isomorphic. Remember this
128 // non-speculatively.
129 if (DstTy == SrcTy) {
134 // Okay, we have two types with identical kinds that we haven't seen before.
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()) {
141 SpeculativeTypes.push_back(SrcTy);
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)))
154 SrcDefinitionsToResolve.push_back(SSTy);
160 // If the number of subtypes disagree between the two types, then we fail.
161 if (SrcTy->getNumContainedTypes() != DstTy->getNumContainedTypes())
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())
171 } else if (FunctionType *FT = dyn_cast<FunctionType>(DstTy)) {
172 if (FT->isVarArg() != cast<FunctionType>(SrcTy)->isVarArg())
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())
179 } else if (ArrayType *DATy = dyn_cast<ArrayType>(DstTy)) {
180 if (DATy->getNumElements() != cast<ArrayType>(SrcTy)->getNumElements())
182 } else if (VectorType *DVTy = dyn_cast<VectorType>(DstTy)) {
183 if (DVTy->getNumElements() != cast<VectorType>(SrcTy)->getNumElements())
187 // Otherwise, we speculate that these two types will line up and recursively
188 // check the subelements.
190 SpeculativeTypes.push_back(SrcTy);
192 for (unsigned i = 0, e = SrcTy->getNumContainedTypes(); i != e; ++i)
193 if (!areTypesIsomorphic(DstTy->getContainedType(i),
194 SrcTy->getContainedType(i)))
197 // If everything seems to have lined up, then everything is great.
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;
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]);
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?");
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));
224 DstSTy->setBody(Elements, SrcSTy->isPacked());
226 // If DstSTy has no name or has a longer name than STy, then viciously steal
228 if (!SrcSTy->hasName()) continue;
229 StringRef SrcName = SrcSTy->getName();
231 if (!DstSTy->hasName() || DstSTy->getName().size() > SrcName.size()) {
232 TmpName.insert(TmpName.end(), SrcName.begin(), SrcName.end());
234 DstSTy->setName(TmpName.str());
239 DstResolvedOpaqueTypes.clear();
242 /// get - Return the mapped type to use for the specified input type from the
244 Type *TypeMapTy::get(Type *Ty) {
245 Type *Result = getImpl(Ty);
247 // If this caused a reference to any struct type, resolve it before returning.
248 if (!SrcDefinitionsToResolve.empty())
249 linkDefinedTypeBodies();
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;
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)
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);
276 // If we found our type while recursively processing stuff, just use it.
277 Entry = &MappedTypes[Ty];
278 if (*Entry) return *Entry;
280 // If all of the element types mapped directly over, then the type is usable
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());
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.
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:
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.
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);
333 // If the type is opaque, we can just use it directly.
337 // Otherwise we create a new type and resolve its body later. This will be
338 // resolved by the top level of get().
339 SrcDefinitionsToResolve.push_back(STy);
340 StructType *DTy = StructType::create(STy->getContext());
341 DstResolvedOpaqueTypes.insert(DTy);
345 //===----------------------------------------------------------------------===//
346 // ModuleLinker implementation.
347 //===----------------------------------------------------------------------===//
350 /// ModuleLinker - This is an implementation class for the LinkModules
351 /// function, which is the entrypoint for this file.
357 /// ValueMap - Mapping of values from what they used to be in Src, to what
358 /// they are now in DstM. ValueToValueMapTy is a ValueMap, which involves
359 /// some overhead due to the use of Value handles which the Linker doesn't
360 /// actually need, but this allows us to reuse the ValueMapper code.
361 ValueToValueMapTy ValueMap;
363 struct AppendingVarInfo {
364 GlobalVariable *NewGV; // New aggregate global in dest module.
365 Constant *DstInit; // Old initializer from dest module.
366 Constant *SrcInit; // Old initializer from src module.
369 std::vector<AppendingVarInfo> AppendingVars;
371 unsigned Mode; // Mode to treat source module.
373 struct LazyLinkEntry {
375 llvm::SmallPtrSet<User*, 4> Uses;
378 // Set of items not to link in from source.
379 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
381 // Vector of functions to lazily link in.
382 std::vector<LazyLinkEntry> LazilyLinkFunctions;
385 std::string ErrorMsg;
387 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
388 : DstM(dstM), SrcM(srcM), Mode(mode) { }
393 /// emitError - Helper method for setting a message and returning an error
395 bool emitError(const Twine &Message) {
396 ErrorMsg = Message.str();
400 /// getLinkageResult - This analyzes the two global values and determines
401 /// what the result will look like in the destination module.
402 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
403 GlobalValue::LinkageTypes <,
404 GlobalValue::VisibilityTypes &Vis,
407 /// getLinkedToGlobal - Given a global in the source module, return the
408 /// global in the destination module that is being linked to, if any.
409 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
410 // If the source has no name it can't link. If it has local linkage,
411 // there is no name match-up going on.
412 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
415 // Otherwise see if we have a match in the destination module's symtab.
416 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
417 if (DGV == 0) return 0;
419 // If we found a global with the same name in the dest module, but it has
420 // internal linkage, we are really not doing any linkage here.
421 if (DGV->hasLocalLinkage())
424 // Otherwise, we do in fact link to the destination global.
428 void computeTypeMapping();
430 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
431 bool linkGlobalProto(GlobalVariable *SrcGV);
432 bool linkFunctionProto(Function *SrcF);
433 bool linkAliasProto(GlobalAlias *SrcA);
434 bool linkModuleFlagsMetadata();
436 void linkAppendingVarInit(const AppendingVarInfo &AVI);
437 void linkGlobalInits();
438 void linkFunctionBody(Function *Dst, Function *Src);
439 void linkAliasBodies();
440 void linkNamedMDNodes();
444 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
445 /// in the symbol table. This is good for all clients except for us. Go
446 /// through the trouble to force this back.
447 static void forceRenaming(GlobalValue *GV, StringRef Name) {
448 // If the global doesn't force its name or if it already has the right name,
449 // there is nothing for us to do.
450 if (GV->hasLocalLinkage() || GV->getName() == Name)
453 Module *M = GV->getParent();
455 // If there is a conflict, rename the conflict.
456 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
457 GV->takeName(ConflictGV);
458 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
459 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
461 GV->setName(Name); // Force the name back
465 /// copyGVAttributes - copy additional attributes (those not needed to construct
466 /// a GlobalValue) from the SrcGV to the DestGV.
467 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
468 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
469 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
470 DestGV->copyAttributesFrom(SrcGV);
471 DestGV->setAlignment(Alignment);
473 forceRenaming(DestGV, SrcGV->getName());
476 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
477 GlobalValue::VisibilityTypes b) {
478 if (a == GlobalValue::HiddenVisibility)
480 if (b == GlobalValue::HiddenVisibility)
482 if (a == GlobalValue::ProtectedVisibility)
484 if (b == GlobalValue::ProtectedVisibility)
489 /// getLinkageResult - This analyzes the two global values and determines what
490 /// the result will look like in the destination module. In particular, it
491 /// computes the resultant linkage type and visibility, computes whether the
492 /// global in the source should be copied over to the destination (replacing
493 /// the existing one), and computes whether this linkage is an error or not.
494 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
495 GlobalValue::LinkageTypes <,
496 GlobalValue::VisibilityTypes &Vis,
498 assert(Dest && "Must have two globals being queried");
499 assert(!Src->hasLocalLinkage() &&
500 "If Src has internal linkage, Dest shouldn't be set!");
502 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
503 bool DestIsDeclaration = Dest->isDeclaration();
505 if (SrcIsDeclaration) {
506 // If Src is external or if both Src & Dest are external.. Just link the
507 // external globals, we aren't adding anything.
508 if (Src->hasDLLImportLinkage()) {
509 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
510 if (DestIsDeclaration) {
512 LT = Src->getLinkage();
514 } else if (Dest->hasExternalWeakLinkage()) {
515 // If the Dest is weak, use the source linkage.
517 LT = Src->getLinkage();
520 LT = Dest->getLinkage();
522 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
523 // If Dest is external but Src is not:
525 LT = Src->getLinkage();
526 } else if (Src->isWeakForLinker()) {
527 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
529 if (Dest->hasExternalWeakLinkage() ||
530 Dest->hasAvailableExternallyLinkage() ||
531 (Dest->hasLinkOnceLinkage() &&
532 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
534 LT = Src->getLinkage();
537 LT = Dest->getLinkage();
539 } else if (Dest->isWeakForLinker()) {
540 // At this point we know that Src has External* or DLL* linkage.
541 if (Src->hasExternalWeakLinkage()) {
543 LT = Dest->getLinkage();
546 LT = GlobalValue::ExternalLinkage;
549 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
550 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
551 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
552 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
553 "Unexpected linkage type!");
554 return emitError("Linking globals named '" + Src->getName() +
555 "': symbol multiply defined!");
558 // Compute the visibility. We follow the rules in the System V Application
560 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
561 Dest->getVisibility() : Src->getVisibility();
565 /// computeTypeMapping - Loop over all of the linked values to compute type
566 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
567 /// we have two struct types 'Foo' but one got renamed when the module was
568 /// loaded into the same LLVMContext.
569 void ModuleLinker::computeTypeMapping() {
570 // Incorporate globals.
571 for (Module::global_iterator I = SrcM->global_begin(),
572 E = SrcM->global_end(); I != E; ++I) {
573 GlobalValue *DGV = getLinkedToGlobal(I);
574 if (DGV == 0) continue;
576 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
577 TypeMap.addTypeMapping(DGV->getType(), I->getType());
581 // Unify the element type of appending arrays.
582 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
583 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
584 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
587 // Incorporate functions.
588 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
589 if (GlobalValue *DGV = getLinkedToGlobal(I))
590 TypeMap.addTypeMapping(DGV->getType(), I->getType());
593 // Incorporate types by name, scanning all the types in the source module.
594 // At this point, the destination module may have a type "%foo = { i32 }" for
595 // example. When the source module got loaded into the same LLVMContext, if
596 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
597 TypeFinder SrcStructTypes;
598 SrcStructTypes.run(*SrcM, true);
599 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
600 SrcStructTypes.end());
602 TypeFinder DstStructTypes;
603 DstStructTypes.run(*DstM, true);
604 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
605 DstStructTypes.end());
607 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
608 StructType *ST = SrcStructTypes[i];
609 if (!ST->hasName()) continue;
611 // Check to see if there is a dot in the name followed by a digit.
612 size_t DotPos = ST->getName().rfind('.');
613 if (DotPos == 0 || DotPos == StringRef::npos ||
614 ST->getName().back() == '.' ||
615 !isdigit(static_cast<unsigned char>(ST->getName()[DotPos+1])))
618 // Check to see if the destination module has a struct with the prefix name.
619 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
620 // Don't use it if this actually came from the source module. They're in
621 // the same LLVMContext after all. Also don't use it unless the type is
622 // actually used in the destination module. This can happen in situations
627 // %Z = type { %A } %B = type { %C.1 }
628 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
629 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
630 // %C = type { i8* } %B.3 = type { %C.1 }
632 // When we link Module B with Module A, the '%B' in Module B is
633 // used. However, that would then use '%C.1'. But when we process '%C.1',
634 // we prefer to take the '%C' version. So we are then left with both
635 // '%C.1' and '%C' being used for the same types. This leads to some
636 // variables using one type and some using the other.
637 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
638 TypeMap.addTypeMapping(DST, ST);
641 // Don't bother incorporating aliases, they aren't generally typed well.
643 // Now that we have discovered all of the type equivalences, get a body for
644 // any 'opaque' types in the dest module that are now resolved.
645 TypeMap.linkDefinedTypeBodies();
648 /// linkAppendingVarProto - If there were any appending global variables, link
649 /// them together now. Return true on error.
650 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
651 GlobalVariable *SrcGV) {
653 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
654 return emitError("Linking globals named '" + SrcGV->getName() +
655 "': can only link appending global with another appending global!");
657 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
659 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
660 Type *EltTy = DstTy->getElementType();
662 // Check to see that they two arrays agree on type.
663 if (EltTy != SrcTy->getElementType())
664 return emitError("Appending variables with different element types!");
665 if (DstGV->isConstant() != SrcGV->isConstant())
666 return emitError("Appending variables linked with different const'ness!");
668 if (DstGV->getAlignment() != SrcGV->getAlignment())
670 "Appending variables with different alignment need to be linked!");
672 if (DstGV->getVisibility() != SrcGV->getVisibility())
674 "Appending variables with different visibility need to be linked!");
676 if (DstGV->getSection() != SrcGV->getSection())
678 "Appending variables with different section name need to be linked!");
680 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
681 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
683 // Create the new global variable.
685 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
686 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
687 DstGV->getThreadLocalMode(),
688 DstGV->getType()->getAddressSpace());
690 // Propagate alignment, visibility and section info.
691 copyGVAttributes(NG, DstGV);
693 AppendingVarInfo AVI;
695 AVI.DstInit = DstGV->getInitializer();
696 AVI.SrcInit = SrcGV->getInitializer();
697 AppendingVars.push_back(AVI);
699 // Replace any uses of the two global variables with uses of the new
701 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
703 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
704 DstGV->eraseFromParent();
706 // Track the source variable so we don't try to link it.
707 DoNotLinkFromSource.insert(SrcGV);
712 /// linkGlobalProto - Loop through the global variables in the src module and
713 /// merge them into the dest module.
714 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
715 GlobalValue *DGV = getLinkedToGlobal(SGV);
716 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
719 // Concatenation of appending linkage variables is magic and handled later.
720 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
721 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
723 // Determine whether linkage of these two globals follows the source
724 // module's definition or the destination module's definition.
725 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
726 GlobalValue::VisibilityTypes NV;
727 bool LinkFromSrc = false;
728 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
732 // If we're not linking from the source, then keep the definition that we
735 // Special case for const propagation.
736 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
737 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
738 DGVar->setConstant(true);
740 // Set calculated linkage and visibility.
741 DGV->setLinkage(NewLinkage);
742 DGV->setVisibility(*NewVisibility);
744 // Make sure to remember this mapping.
745 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
747 // Track the source global so that we don't attempt to copy it over when
748 // processing global initializers.
749 DoNotLinkFromSource.insert(SGV);
755 // No linking to be performed or linking from the source: simply create an
756 // identical version of the symbol over in the dest module... the
757 // initializer will be filled in later by LinkGlobalInits.
758 GlobalVariable *NewDGV =
759 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
760 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
761 SGV->getName(), /*insertbefore*/0,
762 SGV->getThreadLocalMode(),
763 SGV->getType()->getAddressSpace());
764 // Propagate alignment, visibility and section info.
765 copyGVAttributes(NewDGV, SGV);
767 NewDGV->setVisibility(*NewVisibility);
770 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
771 DGV->eraseFromParent();
774 // Make sure to remember this mapping.
775 ValueMap[SGV] = NewDGV;
779 /// linkFunctionProto - Link the function in the source module into the
780 /// destination module if needed, setting up mapping information.
781 bool ModuleLinker::linkFunctionProto(Function *SF) {
782 GlobalValue *DGV = getLinkedToGlobal(SF);
783 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
786 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
787 bool LinkFromSrc = false;
788 GlobalValue::VisibilityTypes NV;
789 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
794 // Set calculated linkage
795 DGV->setLinkage(NewLinkage);
796 DGV->setVisibility(*NewVisibility);
798 // Make sure to remember this mapping.
799 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
801 // Track the function from the source module so we don't attempt to remap
803 DoNotLinkFromSource.insert(SF);
809 // If the function is to be lazily linked, don't create it just yet.
810 // Instead, remember its current set of uses to diff against later.
811 if (!DGV && (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
812 SF->hasAvailableExternallyLinkage())) {
815 LLE.Uses.insert(SF->use_begin(), SF->use_end());
816 LazilyLinkFunctions.push_back(LLE);
817 DoNotLinkFromSource.insert(SF);
821 // If there is no linkage to be performed or we are linking from the source,
823 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
824 SF->getLinkage(), SF->getName(), DstM);
825 copyGVAttributes(NewDF, SF);
827 NewDF->setVisibility(*NewVisibility);
830 // Any uses of DF need to change to NewDF, with cast.
831 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
832 DGV->eraseFromParent();
835 ValueMap[SF] = NewDF;
839 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
841 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
842 GlobalValue *DGV = getLinkedToGlobal(SGA);
843 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
846 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
847 GlobalValue::VisibilityTypes NV;
848 bool LinkFromSrc = false;
849 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
854 // Set calculated linkage.
855 DGV->setLinkage(NewLinkage);
856 DGV->setVisibility(*NewVisibility);
858 // Make sure to remember this mapping.
859 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
861 // Track the alias from the source module so we don't attempt to remap it.
862 DoNotLinkFromSource.insert(SGA);
868 // If there is no linkage to be performed or we're linking from the source,
870 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
871 SGA->getLinkage(), SGA->getName(),
873 copyGVAttributes(NewDA, SGA);
875 NewDA->setVisibility(*NewVisibility);
878 // Any uses of DGV need to change to NewDA, with cast.
879 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
880 DGV->eraseFromParent();
883 ValueMap[SGA] = NewDA;
887 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
888 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
890 for (unsigned i = 0; i != NumElements; ++i)
891 Dest.push_back(C->getAggregateElement(i));
894 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
895 // Merge the initializer.
896 SmallVector<Constant*, 16> Elements;
897 getArrayElements(AVI.DstInit, Elements);
899 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
900 getArrayElements(SrcInit, Elements);
902 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
903 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
906 /// linkGlobalInits - Update the initializers in the Dest module now that all
907 /// globals that may be referenced are in Dest.
908 void ModuleLinker::linkGlobalInits() {
909 // Loop over all of the globals in the src module, mapping them over as we go
910 for (Module::const_global_iterator I = SrcM->global_begin(),
911 E = SrcM->global_end(); I != E; ++I) {
913 // Only process initialized GV's or ones not already in dest.
914 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
916 // Grab destination global variable.
917 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
918 // Figure out what the initializer looks like in the dest module.
919 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
924 /// linkFunctionBody - Copy the source function over into the dest function and
925 /// fix up references to values. At this point we know that Dest is an external
926 /// function, and that Src is not.
927 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
928 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
930 // Go through and convert function arguments over, remembering the mapping.
931 Function::arg_iterator DI = Dst->arg_begin();
932 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
934 DI->setName(I->getName()); // Copy the name over.
936 // Add a mapping to our mapping.
940 if (Mode == Linker::DestroySource) {
941 // Splice the body of the source function into the dest function.
942 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
944 // At this point, all of the instructions and values of the function are now
945 // copied over. The only problem is that they are still referencing values in
946 // the Source function as operands. Loop through all of the operands of the
947 // functions and patch them up to point to the local versions.
948 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
949 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
950 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
953 // Clone the body of the function into the dest function.
954 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
955 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
958 // There is no need to map the arguments anymore.
959 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
965 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
966 void ModuleLinker::linkAliasBodies() {
967 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
969 if (DoNotLinkFromSource.count(I))
971 if (Constant *Aliasee = I->getAliasee()) {
972 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
973 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
978 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
980 void ModuleLinker::linkNamedMDNodes() {
981 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
982 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
983 E = SrcM->named_metadata_end(); I != E; ++I) {
984 // Don't link module flags here. Do them separately.
985 if (&*I == SrcModFlags) continue;
986 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
987 // Add Src elements into Dest node.
988 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
989 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
994 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
996 bool ModuleLinker::linkModuleFlagsMetadata() {
997 // If the source module has no module flags, we are done.
998 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
999 if (!SrcModFlags) return false;
1001 // If the destination module doesn't have module flags yet, then just copy
1002 // over the source module's flags.
1003 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1004 if (DstModFlags->getNumOperands() == 0) {
1005 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1006 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1011 // First build a map of the existing module flags and requirements.
1012 DenseMap<MDString*, MDNode*> Flags;
1013 SmallSetVector<MDNode*, 16> Requirements;
1014 for (unsigned I = 0, E = DstModFlags->getNumOperands(); I != E; ++I) {
1015 MDNode *Op = DstModFlags->getOperand(I);
1016 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1017 MDString *ID = cast<MDString>(Op->getOperand(1));
1019 if (Behavior->getZExtValue() == Module::Require) {
1020 Requirements.insert(cast<MDNode>(Op->getOperand(2)));
1026 // Merge in the flags from the source module, and also collect its set of
1028 bool HasErr = false;
1029 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I) {
1030 MDNode *SrcOp = SrcModFlags->getOperand(I);
1031 ConstantInt *SrcBehavior = cast<ConstantInt>(SrcOp->getOperand(0));
1032 MDString *ID = cast<MDString>(SrcOp->getOperand(1));
1033 MDNode *DstOp = Flags.lookup(ID);
1034 unsigned SrcBehaviorValue = SrcBehavior->getZExtValue();
1036 // If this is a requirement, add it and continue.
1037 if (SrcBehaviorValue == Module::Require) {
1038 // If the destination module does not already have this requirement, add
1040 if (Requirements.insert(cast<MDNode>(SrcOp->getOperand(2)))) {
1041 DstModFlags->addOperand(SrcOp);
1046 // If there is no existing flag with this ID, just add it.
1049 DstModFlags->addOperand(SrcOp);
1053 // Otherwise, perform a merge.
1054 ConstantInt *DstBehavior = cast<ConstantInt>(DstOp->getOperand(0));
1055 unsigned DstBehaviorValue = DstBehavior->getZExtValue();
1057 // If either flag has override behavior, handle it first.
1058 if (DstBehaviorValue == Module::Override) {
1059 // Diagnose inconsistent flags which both have override behavior.
1060 if (SrcBehaviorValue == Module::Override &&
1061 SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1062 HasErr |= emitError("linking module flags '" + ID->getString() +
1063 "': IDs have conflicting override values");
1066 } else if (SrcBehaviorValue == Module::Override) {
1067 // Update the destination flag to that of the source.
1068 DstOp->replaceOperandWith(0, SrcBehavior);
1069 DstOp->replaceOperandWith(2, SrcOp->getOperand(2));
1073 // Diagnose inconsistent merge behavior types.
1074 if (SrcBehaviorValue != DstBehaviorValue) {
1075 HasErr |= emitError("linking module flags '" + ID->getString() +
1076 "': IDs have conflicting behaviors");
1080 // Perform the merge for standard behavior types.
1081 switch (SrcBehaviorValue) {
1082 case Module::Require:
1083 case Module::Override: assert(0 && "not possible"); break;
1084 case Module::Error: {
1085 // Emit an error if the values differ.
1086 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1087 HasErr |= emitError("linking module flags '" + ID->getString() +
1088 "': IDs have conflicting values");
1092 case Module::Warning: {
1093 // Emit a warning if the values differ.
1094 if (SrcOp->getOperand(2) != DstOp->getOperand(2)) {
1095 errs() << "WARNING: linking module flags '" << ID->getString()
1096 << "': IDs have conflicting values";
1100 case Module::Append: {
1101 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1102 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1103 unsigned NumOps = DstValue->getNumOperands() + SrcValue->getNumOperands();
1104 Value **VP, **Values = VP = new Value*[NumOps];
1105 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i, ++VP)
1106 *VP = DstValue->getOperand(i);
1107 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i, ++VP)
1108 *VP = SrcValue->getOperand(i);
1109 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1110 ArrayRef<Value*>(Values,
1115 case Module::AppendUnique: {
1116 SmallSetVector<Value*, 16> Elts;
1117 MDNode *DstValue = cast<MDNode>(DstOp->getOperand(2));
1118 MDNode *SrcValue = cast<MDNode>(SrcOp->getOperand(2));
1119 for (unsigned i = 0, e = DstValue->getNumOperands(); i != e; ++i)
1120 Elts.insert(DstValue->getOperand(i));
1121 for (unsigned i = 0, e = SrcValue->getNumOperands(); i != e; ++i)
1122 Elts.insert(SrcValue->getOperand(i));
1123 DstOp->replaceOperandWith(2, MDNode::get(DstM->getContext(),
1124 ArrayRef<Value*>(Elts.begin(),
1131 // Check all of the requirements.
1132 for (unsigned I = 0, E = Requirements.size(); I != E; ++I) {
1133 MDNode *Requirement = Requirements[I];
1134 MDString *Flag = cast<MDString>(Requirement->getOperand(0));
1135 Value *ReqValue = Requirement->getOperand(1);
1137 MDNode *Op = Flags[Flag];
1138 if (!Op || Op->getOperand(2) != ReqValue) {
1139 HasErr |= emitError("linking module flags '" + Flag->getString() +
1140 "': does not have the required value");
1148 bool ModuleLinker::run() {
1149 assert(DstM && "Null destination module");
1150 assert(SrcM && "Null source module");
1152 // Inherit the target data from the source module if the destination module
1153 // doesn't have one already.
1154 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1155 DstM->setDataLayout(SrcM->getDataLayout());
1157 // Copy the target triple from the source to dest if the dest's is empty.
1158 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1159 DstM->setTargetTriple(SrcM->getTargetTriple());
1161 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1162 SrcM->getDataLayout() != DstM->getDataLayout())
1163 errs() << "WARNING: Linking two modules of different data layouts!\n";
1164 if (!SrcM->getTargetTriple().empty() &&
1165 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1166 errs() << "WARNING: Linking two modules of different target triples: ";
1167 if (!SrcM->getModuleIdentifier().empty())
1168 errs() << SrcM->getModuleIdentifier() << ": ";
1169 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1170 << DstM->getTargetTriple() << "'\n";
1173 // Append the module inline asm string.
1174 if (!SrcM->getModuleInlineAsm().empty()) {
1175 if (DstM->getModuleInlineAsm().empty())
1176 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1178 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1179 SrcM->getModuleInlineAsm());
1182 // Loop over all of the linked values to compute type mappings.
1183 computeTypeMapping();
1185 // Insert all of the globals in src into the DstM module... without linking
1186 // initializers (which could refer to functions not yet mapped over).
1187 for (Module::global_iterator I = SrcM->global_begin(),
1188 E = SrcM->global_end(); I != E; ++I)
1189 if (linkGlobalProto(I))
1192 // Link the functions together between the two modules, without doing function
1193 // bodies... this just adds external function prototypes to the DstM
1194 // function... We do this so that when we begin processing function bodies,
1195 // all of the global values that may be referenced are available in our
1197 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1198 if (linkFunctionProto(I))
1201 // If there were any aliases, link them now.
1202 for (Module::alias_iterator I = SrcM->alias_begin(),
1203 E = SrcM->alias_end(); I != E; ++I)
1204 if (linkAliasProto(I))
1207 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1208 linkAppendingVarInit(AppendingVars[i]);
1210 // Update the initializers in the DstM module now that all globals that may
1211 // be referenced are in DstM.
1214 // Link in the function bodies that are defined in the source module into
1216 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1217 // Skip if not linking from source.
1218 if (DoNotLinkFromSource.count(SF)) continue;
1220 // Skip if no body (function is external) or materialize.
1221 if (SF->isDeclaration()) {
1222 if (!SF->isMaterializable())
1224 if (SF->Materialize(&ErrorMsg))
1228 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1229 SF->Dematerialize();
1232 // Resolve all uses of aliases with aliasees.
1235 // Remap all of the named MDNodes in Src into the DstM module. We do this
1236 // after linking GlobalValues so that MDNodes that reference GlobalValues
1237 // are properly remapped.
1240 // Merge the module flags into the DstM module.
1241 if (linkModuleFlagsMetadata())
1244 // Process vector of lazily linked in functions.
1245 bool LinkedInAnyFunctions;
1247 LinkedInAnyFunctions = false;
1249 for(std::vector<LazyLinkEntry>::iterator I = LazilyLinkFunctions.begin(),
1250 E = LazilyLinkFunctions.end(); I != E; ++I) {
1251 Function *SF = I->Fn;
1255 // If the number of uses of this function is the same as it was at the
1256 // start of the link, it is not used in this link.
1257 if (SF->getNumUses() != I->Uses.size()) {
1258 Function *DF = Function::Create(TypeMap.get(SF->getFunctionType()),
1259 SF->getLinkage(), SF->getName(), DstM);
1260 copyGVAttributes(DF, SF);
1262 // Now, copy over any uses of SF that were from DstM to DF.
1263 for (Function::use_iterator UI = SF->use_begin(), UE = SF->use_end();
1265 if (I->Uses.count(*UI) == 0) {
1266 Use &U = UI.getUse();
1267 // Increment UI before performing the set to ensure the iterator
1276 // Materialize if necessary.
1277 if (SF->isDeclaration()) {
1278 if (!SF->isMaterializable())
1280 if (SF->Materialize(&ErrorMsg))
1284 // Link in function body.
1285 linkFunctionBody(DF, SF);
1286 SF->Dematerialize();
1288 // "Remove" from vector by setting the element to 0.
1291 // Set flag to indicate we may have more functions to lazily link in
1292 // since we linked in a function.
1293 LinkedInAnyFunctions = true;
1296 } while (LinkedInAnyFunctions);
1298 // Now that all of the types from the source are used, resolve any structs
1299 // copied over to the dest that didn't exist there.
1300 TypeMap.linkDefinedTypeBodies();
1305 //===----------------------------------------------------------------------===//
1306 // LinkModules entrypoint.
1307 //===----------------------------------------------------------------------===//
1309 /// LinkModules - This function links two modules together, with the resulting
1310 /// Dest module modified to be the composite of the two input modules. If an
1311 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1312 /// the problem. Upon failure, the Dest module could be in a modified state,
1313 /// and shouldn't be relied on to be consistent.
1314 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1315 std::string *ErrorMsg) {
1316 ModuleLinker TheLinker(Dest, Src, Mode);
1317 if (TheLinker.run()) {
1318 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
1325 //===----------------------------------------------------------------------===//
1327 //===----------------------------------------------------------------------===//
1329 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1330 LLVMLinkerMode Mode, char **OutMessages) {
1331 std::string Messages;
1332 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1333 Mode, OutMessages? &Messages : 0);
1335 *OutMessages = strdup(Messages.c_str());