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/IR/Constants.h"
21 #include "llvm/IR/DerivedTypes.h"
22 #include "llvm/IR/Instructions.h"
23 #include "llvm/IR/Module.h"
24 #include "llvm/IR/TypeFinder.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Path.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 // Set of items not to link in from source.
374 SmallPtrSet<const Value*, 16> DoNotLinkFromSource;
376 // Vector of functions to lazily link in.
377 std::vector<Function*> LazilyLinkFunctions;
380 std::string ErrorMsg;
382 ModuleLinker(Module *dstM, Module *srcM, unsigned mode)
383 : DstM(dstM), SrcM(srcM), Mode(mode) { }
388 /// emitError - Helper method for setting a message and returning an error
390 bool emitError(const Twine &Message) {
391 ErrorMsg = Message.str();
395 /// getLinkageResult - This analyzes the two global values and determines
396 /// what the result will look like in the destination module.
397 bool getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
398 GlobalValue::LinkageTypes <,
399 GlobalValue::VisibilityTypes &Vis,
402 /// getLinkedToGlobal - Given a global in the source module, return the
403 /// global in the destination module that is being linked to, if any.
404 GlobalValue *getLinkedToGlobal(GlobalValue *SrcGV) {
405 // If the source has no name it can't link. If it has local linkage,
406 // there is no name match-up going on.
407 if (!SrcGV->hasName() || SrcGV->hasLocalLinkage())
410 // Otherwise see if we have a match in the destination module's symtab.
411 GlobalValue *DGV = DstM->getNamedValue(SrcGV->getName());
412 if (DGV == 0) return 0;
414 // If we found a global with the same name in the dest module, but it has
415 // internal linkage, we are really not doing any linkage here.
416 if (DGV->hasLocalLinkage())
419 // Otherwise, we do in fact link to the destination global.
423 void computeTypeMapping();
424 bool categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
425 DenseMap<MDString*, MDNode*> &ErrorNode,
426 DenseMap<MDString*, MDNode*> &WarningNode,
427 DenseMap<MDString*, MDNode*> &OverrideNode,
429 SmallSetVector<MDNode*, 8> > &RequireNodes,
430 SmallSetVector<MDString*, 16> &SeenIDs);
432 bool linkAppendingVarProto(GlobalVariable *DstGV, GlobalVariable *SrcGV);
433 bool linkGlobalProto(GlobalVariable *SrcGV);
434 bool linkFunctionProto(Function *SrcF);
435 bool linkAliasProto(GlobalAlias *SrcA);
436 bool linkModuleFlagsMetadata();
438 void linkAppendingVarInit(const AppendingVarInfo &AVI);
439 void linkGlobalInits();
440 void linkFunctionBody(Function *Dst, Function *Src);
441 void linkAliasBodies();
442 void linkNamedMDNodes();
446 /// forceRenaming - The LLVM SymbolTable class autorenames globals that conflict
447 /// in the symbol table. This is good for all clients except for us. Go
448 /// through the trouble to force this back.
449 static void forceRenaming(GlobalValue *GV, StringRef Name) {
450 // If the global doesn't force its name or if it already has the right name,
451 // there is nothing for us to do.
452 if (GV->hasLocalLinkage() || GV->getName() == Name)
455 Module *M = GV->getParent();
457 // If there is a conflict, rename the conflict.
458 if (GlobalValue *ConflictGV = M->getNamedValue(Name)) {
459 GV->takeName(ConflictGV);
460 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
461 assert(ConflictGV->getName() != Name && "forceRenaming didn't work");
463 GV->setName(Name); // Force the name back
467 /// copyGVAttributes - copy additional attributes (those not needed to construct
468 /// a GlobalValue) from the SrcGV to the DestGV.
469 static void copyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
470 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
471 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
472 DestGV->copyAttributesFrom(SrcGV);
473 DestGV->setAlignment(Alignment);
475 forceRenaming(DestGV, SrcGV->getName());
478 static bool isLessConstraining(GlobalValue::VisibilityTypes a,
479 GlobalValue::VisibilityTypes b) {
480 if (a == GlobalValue::HiddenVisibility)
482 if (b == GlobalValue::HiddenVisibility)
484 if (a == GlobalValue::ProtectedVisibility)
486 if (b == GlobalValue::ProtectedVisibility)
491 /// getLinkageResult - This analyzes the two global values and determines what
492 /// the result will look like in the destination module. In particular, it
493 /// computes the resultant linkage type and visibility, computes whether the
494 /// global in the source should be copied over to the destination (replacing
495 /// the existing one), and computes whether this linkage is an error or not.
496 bool ModuleLinker::getLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
497 GlobalValue::LinkageTypes <,
498 GlobalValue::VisibilityTypes &Vis,
500 assert(Dest && "Must have two globals being queried");
501 assert(!Src->hasLocalLinkage() &&
502 "If Src has internal linkage, Dest shouldn't be set!");
504 bool SrcIsDeclaration = Src->isDeclaration() && !Src->isMaterializable();
505 bool DestIsDeclaration = Dest->isDeclaration();
507 if (SrcIsDeclaration) {
508 // If Src is external or if both Src & Dest are external.. Just link the
509 // external globals, we aren't adding anything.
510 if (Src->hasDLLImportLinkage()) {
511 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
512 if (DestIsDeclaration) {
514 LT = Src->getLinkage();
516 } else if (Dest->hasExternalWeakLinkage()) {
517 // If the Dest is weak, use the source linkage.
519 LT = Src->getLinkage();
522 LT = Dest->getLinkage();
524 } else if (DestIsDeclaration && !Dest->hasDLLImportLinkage()) {
525 // If Dest is external but Src is not:
527 LT = Src->getLinkage();
528 } else if (Src->isWeakForLinker()) {
529 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
531 if (Dest->hasExternalWeakLinkage() ||
532 Dest->hasAvailableExternallyLinkage() ||
533 (Dest->hasLinkOnceLinkage() &&
534 (Src->hasWeakLinkage() || Src->hasCommonLinkage()))) {
536 LT = Src->getLinkage();
539 LT = Dest->getLinkage();
541 } else if (Dest->isWeakForLinker()) {
542 // At this point we know that Src has External* or DLL* linkage.
543 if (Src->hasExternalWeakLinkage()) {
545 LT = Dest->getLinkage();
548 LT = GlobalValue::ExternalLinkage;
551 assert((Dest->hasExternalLinkage() || Dest->hasDLLImportLinkage() ||
552 Dest->hasDLLExportLinkage() || Dest->hasExternalWeakLinkage()) &&
553 (Src->hasExternalLinkage() || Src->hasDLLImportLinkage() ||
554 Src->hasDLLExportLinkage() || Src->hasExternalWeakLinkage()) &&
555 "Unexpected linkage type!");
556 return emitError("Linking globals named '" + Src->getName() +
557 "': symbol multiply defined!");
560 // Compute the visibility. We follow the rules in the System V Application
562 Vis = isLessConstraining(Src->getVisibility(), Dest->getVisibility()) ?
563 Dest->getVisibility() : Src->getVisibility();
567 /// computeTypeMapping - Loop over all of the linked values to compute type
568 /// mappings. For example, if we link "extern Foo *x" and "Foo *x = NULL", then
569 /// we have two struct types 'Foo' but one got renamed when the module was
570 /// loaded into the same LLVMContext.
571 void ModuleLinker::computeTypeMapping() {
572 // Incorporate globals.
573 for (Module::global_iterator I = SrcM->global_begin(),
574 E = SrcM->global_end(); I != E; ++I) {
575 GlobalValue *DGV = getLinkedToGlobal(I);
576 if (DGV == 0) continue;
578 if (!DGV->hasAppendingLinkage() || !I->hasAppendingLinkage()) {
579 TypeMap.addTypeMapping(DGV->getType(), I->getType());
583 // Unify the element type of appending arrays.
584 ArrayType *DAT = cast<ArrayType>(DGV->getType()->getElementType());
585 ArrayType *SAT = cast<ArrayType>(I->getType()->getElementType());
586 TypeMap.addTypeMapping(DAT->getElementType(), SAT->getElementType());
589 // Incorporate functions.
590 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I) {
591 if (GlobalValue *DGV = getLinkedToGlobal(I))
592 TypeMap.addTypeMapping(DGV->getType(), I->getType());
595 // Incorporate types by name, scanning all the types in the source module.
596 // At this point, the destination module may have a type "%foo = { i32 }" for
597 // example. When the source module got loaded into the same LLVMContext, if
598 // it had the same type, it would have been renamed to "%foo.42 = { i32 }".
599 TypeFinder SrcStructTypes;
600 SrcStructTypes.run(*SrcM, true);
601 SmallPtrSet<StructType*, 32> SrcStructTypesSet(SrcStructTypes.begin(),
602 SrcStructTypes.end());
604 TypeFinder DstStructTypes;
605 DstStructTypes.run(*DstM, true);
606 SmallPtrSet<StructType*, 32> DstStructTypesSet(DstStructTypes.begin(),
607 DstStructTypes.end());
609 for (unsigned i = 0, e = SrcStructTypes.size(); i != e; ++i) {
610 StructType *ST = SrcStructTypes[i];
611 if (!ST->hasName()) continue;
613 // Check to see if there is a dot in the name followed by a digit.
614 size_t DotPos = ST->getName().rfind('.');
615 if (DotPos == 0 || DotPos == StringRef::npos ||
616 ST->getName().back() == '.' || !isdigit(ST->getName()[DotPos+1]))
619 // Check to see if the destination module has a struct with the prefix name.
620 if (StructType *DST = DstM->getTypeByName(ST->getName().substr(0, DotPos)))
621 // Don't use it if this actually came from the source module. They're in
622 // the same LLVMContext after all. Also don't use it unless the type is
623 // actually used in the destination module. This can happen in situations
628 // %Z = type { %A } %B = type { %C.1 }
629 // %A = type { %B.1, [7 x i8] } %C.1 = type { i8* }
630 // %B.1 = type { %C } %A.2 = type { %B.3, [5 x i8] }
631 // %C = type { i8* } %B.3 = type { %C.1 }
633 // When we link Module B with Module A, the '%B' in Module B is
634 // used. However, that would then use '%C.1'. But when we process '%C.1',
635 // we prefer to take the '%C' version. So we are then left with both
636 // '%C.1' and '%C' being used for the same types. This leads to some
637 // variables using one type and some using the other.
638 if (!SrcStructTypesSet.count(DST) && DstStructTypesSet.count(DST))
639 TypeMap.addTypeMapping(DST, ST);
642 // Don't bother incorporating aliases, they aren't generally typed well.
644 // Now that we have discovered all of the type equivalences, get a body for
645 // any 'opaque' types in the dest module that are now resolved.
646 TypeMap.linkDefinedTypeBodies();
649 /// linkAppendingVarProto - If there were any appending global variables, link
650 /// them together now. Return true on error.
651 bool ModuleLinker::linkAppendingVarProto(GlobalVariable *DstGV,
652 GlobalVariable *SrcGV) {
654 if (!SrcGV->hasAppendingLinkage() || !DstGV->hasAppendingLinkage())
655 return emitError("Linking globals named '" + SrcGV->getName() +
656 "': can only link appending global with another appending global!");
658 ArrayType *DstTy = cast<ArrayType>(DstGV->getType()->getElementType());
660 cast<ArrayType>(TypeMap.get(SrcGV->getType()->getElementType()));
661 Type *EltTy = DstTy->getElementType();
663 // Check to see that they two arrays agree on type.
664 if (EltTy != SrcTy->getElementType())
665 return emitError("Appending variables with different element types!");
666 if (DstGV->isConstant() != SrcGV->isConstant())
667 return emitError("Appending variables linked with different const'ness!");
669 if (DstGV->getAlignment() != SrcGV->getAlignment())
671 "Appending variables with different alignment need to be linked!");
673 if (DstGV->getVisibility() != SrcGV->getVisibility())
675 "Appending variables with different visibility need to be linked!");
677 if (DstGV->getSection() != SrcGV->getSection())
679 "Appending variables with different section name need to be linked!");
681 uint64_t NewSize = DstTy->getNumElements() + SrcTy->getNumElements();
682 ArrayType *NewType = ArrayType::get(EltTy, NewSize);
684 // Create the new global variable.
686 new GlobalVariable(*DstGV->getParent(), NewType, SrcGV->isConstant(),
687 DstGV->getLinkage(), /*init*/0, /*name*/"", DstGV,
688 DstGV->getThreadLocalMode(),
689 DstGV->getType()->getAddressSpace());
691 // Propagate alignment, visibility and section info.
692 copyGVAttributes(NG, DstGV);
694 AppendingVarInfo AVI;
696 AVI.DstInit = DstGV->getInitializer();
697 AVI.SrcInit = SrcGV->getInitializer();
698 AppendingVars.push_back(AVI);
700 // Replace any uses of the two global variables with uses of the new
702 ValueMap[SrcGV] = ConstantExpr::getBitCast(NG, TypeMap.get(SrcGV->getType()));
704 DstGV->replaceAllUsesWith(ConstantExpr::getBitCast(NG, DstGV->getType()));
705 DstGV->eraseFromParent();
707 // Track the source variable so we don't try to link it.
708 DoNotLinkFromSource.insert(SrcGV);
713 /// linkGlobalProto - Loop through the global variables in the src module and
714 /// merge them into the dest module.
715 bool ModuleLinker::linkGlobalProto(GlobalVariable *SGV) {
716 GlobalValue *DGV = getLinkedToGlobal(SGV);
717 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
720 // Concatenation of appending linkage variables is magic and handled later.
721 if (DGV->hasAppendingLinkage() || SGV->hasAppendingLinkage())
722 return linkAppendingVarProto(cast<GlobalVariable>(DGV), SGV);
724 // Determine whether linkage of these two globals follows the source
725 // module's definition or the destination module's definition.
726 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
727 GlobalValue::VisibilityTypes NV;
728 bool LinkFromSrc = false;
729 if (getLinkageResult(DGV, SGV, NewLinkage, NV, LinkFromSrc))
733 // If we're not linking from the source, then keep the definition that we
736 // Special case for const propagation.
737 if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV))
738 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
739 DGVar->setConstant(true);
741 // Set calculated linkage and visibility.
742 DGV->setLinkage(NewLinkage);
743 DGV->setVisibility(*NewVisibility);
745 // Make sure to remember this mapping.
746 ValueMap[SGV] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGV->getType()));
748 // Track the source global so that we don't attempt to copy it over when
749 // processing global initializers.
750 DoNotLinkFromSource.insert(SGV);
756 // No linking to be performed or linking from the source: simply create an
757 // identical version of the symbol over in the dest module... the
758 // initializer will be filled in later by LinkGlobalInits.
759 GlobalVariable *NewDGV =
760 new GlobalVariable(*DstM, TypeMap.get(SGV->getType()->getElementType()),
761 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
762 SGV->getName(), /*insertbefore*/0,
763 SGV->getThreadLocalMode(),
764 SGV->getType()->getAddressSpace());
765 // Propagate alignment, visibility and section info.
766 copyGVAttributes(NewDGV, SGV);
768 NewDGV->setVisibility(*NewVisibility);
771 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV, DGV->getType()));
772 DGV->eraseFromParent();
775 // Make sure to remember this mapping.
776 ValueMap[SGV] = NewDGV;
780 /// linkFunctionProto - Link the function in the source module into the
781 /// destination module if needed, setting up mapping information.
782 bool ModuleLinker::linkFunctionProto(Function *SF) {
783 GlobalValue *DGV = getLinkedToGlobal(SF);
784 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
787 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
788 bool LinkFromSrc = false;
789 GlobalValue::VisibilityTypes NV;
790 if (getLinkageResult(DGV, SF, NewLinkage, NV, LinkFromSrc))
795 // Set calculated linkage
796 DGV->setLinkage(NewLinkage);
797 DGV->setVisibility(*NewVisibility);
799 // Make sure to remember this mapping.
800 ValueMap[SF] = ConstantExpr::getBitCast(DGV, TypeMap.get(SF->getType()));
802 // Track the function from the source module so we don't attempt to remap
804 DoNotLinkFromSource.insert(SF);
810 // If there is no linkage to be performed or we are linking from the source,
812 Function *NewDF = Function::Create(TypeMap.get(SF->getFunctionType()),
813 SF->getLinkage(), SF->getName(), DstM);
814 copyGVAttributes(NewDF, SF);
816 NewDF->setVisibility(*NewVisibility);
819 // Any uses of DF need to change to NewDF, with cast.
820 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DGV->getType()));
821 DGV->eraseFromParent();
823 // Internal, LO_ODR, or LO linkage - stick in set to ignore and lazily link.
824 if (SF->hasLocalLinkage() || SF->hasLinkOnceLinkage() ||
825 SF->hasAvailableExternallyLinkage()) {
826 DoNotLinkFromSource.insert(SF);
827 LazilyLinkFunctions.push_back(SF);
831 ValueMap[SF] = NewDF;
835 /// LinkAliasProto - Set up prototypes for any aliases that come over from the
837 bool ModuleLinker::linkAliasProto(GlobalAlias *SGA) {
838 GlobalValue *DGV = getLinkedToGlobal(SGA);
839 llvm::Optional<GlobalValue::VisibilityTypes> NewVisibility;
842 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
843 GlobalValue::VisibilityTypes NV;
844 bool LinkFromSrc = false;
845 if (getLinkageResult(DGV, SGA, NewLinkage, NV, LinkFromSrc))
850 // Set calculated linkage.
851 DGV->setLinkage(NewLinkage);
852 DGV->setVisibility(*NewVisibility);
854 // Make sure to remember this mapping.
855 ValueMap[SGA] = ConstantExpr::getBitCast(DGV,TypeMap.get(SGA->getType()));
857 // Track the alias from the source module so we don't attempt to remap it.
858 DoNotLinkFromSource.insert(SGA);
864 // If there is no linkage to be performed or we're linking from the source,
866 GlobalAlias *NewDA = new GlobalAlias(TypeMap.get(SGA->getType()),
867 SGA->getLinkage(), SGA->getName(),
869 copyGVAttributes(NewDA, SGA);
871 NewDA->setVisibility(*NewVisibility);
874 // Any uses of DGV need to change to NewDA, with cast.
875 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDA, DGV->getType()));
876 DGV->eraseFromParent();
879 ValueMap[SGA] = NewDA;
883 static void getArrayElements(Constant *C, SmallVectorImpl<Constant*> &Dest) {
884 unsigned NumElements = cast<ArrayType>(C->getType())->getNumElements();
886 for (unsigned i = 0; i != NumElements; ++i)
887 Dest.push_back(C->getAggregateElement(i));
890 void ModuleLinker::linkAppendingVarInit(const AppendingVarInfo &AVI) {
891 // Merge the initializer.
892 SmallVector<Constant*, 16> Elements;
893 getArrayElements(AVI.DstInit, Elements);
895 Constant *SrcInit = MapValue(AVI.SrcInit, ValueMap, RF_None, &TypeMap);
896 getArrayElements(SrcInit, Elements);
898 ArrayType *NewType = cast<ArrayType>(AVI.NewGV->getType()->getElementType());
899 AVI.NewGV->setInitializer(ConstantArray::get(NewType, Elements));
902 /// linkGlobalInits - Update the initializers in the Dest module now that all
903 /// globals that may be referenced are in Dest.
904 void ModuleLinker::linkGlobalInits() {
905 // Loop over all of the globals in the src module, mapping them over as we go
906 for (Module::const_global_iterator I = SrcM->global_begin(),
907 E = SrcM->global_end(); I != E; ++I) {
909 // Only process initialized GV's or ones not already in dest.
910 if (!I->hasInitializer() || DoNotLinkFromSource.count(I)) continue;
912 // Grab destination global variable.
913 GlobalVariable *DGV = cast<GlobalVariable>(ValueMap[I]);
914 // Figure out what the initializer looks like in the dest module.
915 DGV->setInitializer(MapValue(I->getInitializer(), ValueMap,
920 /// linkFunctionBody - Copy the source function over into the dest function and
921 /// fix up references to values. At this point we know that Dest is an external
922 /// function, and that Src is not.
923 void ModuleLinker::linkFunctionBody(Function *Dst, Function *Src) {
924 assert(Src && Dst && Dst->isDeclaration() && !Src->isDeclaration());
926 // Go through and convert function arguments over, remembering the mapping.
927 Function::arg_iterator DI = Dst->arg_begin();
928 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
930 DI->setName(I->getName()); // Copy the name over.
932 // Add a mapping to our mapping.
936 if (Mode == Linker::DestroySource) {
937 // Splice the body of the source function into the dest function.
938 Dst->getBasicBlockList().splice(Dst->end(), Src->getBasicBlockList());
940 // At this point, all of the instructions and values of the function are now
941 // copied over. The only problem is that they are still referencing values in
942 // the Source function as operands. Loop through all of the operands of the
943 // functions and patch them up to point to the local versions.
944 for (Function::iterator BB = Dst->begin(), BE = Dst->end(); BB != BE; ++BB)
945 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
946 RemapInstruction(I, ValueMap, RF_IgnoreMissingEntries, &TypeMap);
949 // Clone the body of the function into the dest function.
950 SmallVector<ReturnInst*, 8> Returns; // Ignore returns.
951 CloneFunctionInto(Dst, Src, ValueMap, false, Returns, "", NULL, &TypeMap);
954 // There is no need to map the arguments anymore.
955 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
961 /// linkAliasBodies - Insert all of the aliases in Src into the Dest module.
962 void ModuleLinker::linkAliasBodies() {
963 for (Module::alias_iterator I = SrcM->alias_begin(), E = SrcM->alias_end();
965 if (DoNotLinkFromSource.count(I))
967 if (Constant *Aliasee = I->getAliasee()) {
968 GlobalAlias *DA = cast<GlobalAlias>(ValueMap[I]);
969 DA->setAliasee(MapValue(Aliasee, ValueMap, RF_None, &TypeMap));
974 /// linkNamedMDNodes - Insert all of the named MDNodes in Src into the Dest
976 void ModuleLinker::linkNamedMDNodes() {
977 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
978 for (Module::const_named_metadata_iterator I = SrcM->named_metadata_begin(),
979 E = SrcM->named_metadata_end(); I != E; ++I) {
980 // Don't link module flags here. Do them separately.
981 if (&*I == SrcModFlags) continue;
982 NamedMDNode *DestNMD = DstM->getOrInsertNamedMetadata(I->getName());
983 // Add Src elements into Dest node.
984 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
985 DestNMD->addOperand(MapValue(I->getOperand(i), ValueMap,
990 /// categorizeModuleFlagNodes - Categorize the module flags according to their
991 /// type: Error, Warning, Override, and Require.
993 categorizeModuleFlagNodes(const NamedMDNode *ModFlags,
994 DenseMap<MDString*, MDNode*> &ErrorNode,
995 DenseMap<MDString*, MDNode*> &WarningNode,
996 DenseMap<MDString*, MDNode*> &OverrideNode,
998 SmallSetVector<MDNode*, 8> > &RequireNodes,
999 SmallSetVector<MDString*, 16> &SeenIDs) {
1000 bool HasErr = false;
1002 for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
1003 MDNode *Op = ModFlags->getOperand(I);
1004 ConstantInt *Behavior = cast<ConstantInt>(Op->getOperand(0));
1005 MDString *ID = cast<MDString>(Op->getOperand(1));
1006 Value *Val = Op->getOperand(2);
1007 switch (Behavior->getZExtValue()) {
1008 case Module::Error: {
1009 MDNode *&ErrNode = ErrorNode[ID];
1010 if (!ErrNode) ErrNode = Op;
1011 if (ErrNode->getOperand(2) != Val)
1012 HasErr = emitError("linking module flags '" + ID->getString() +
1013 "': IDs have conflicting values");
1016 case Module::Warning: {
1017 MDNode *&WarnNode = WarningNode[ID];
1018 if (!WarnNode) WarnNode = Op;
1019 if (WarnNode->getOperand(2) != Val)
1020 errs() << "WARNING: linking module flags '" << ID->getString()
1021 << "': IDs have conflicting values";
1024 case Module::Require: RequireNodes[ID].insert(Op); break;
1025 case Module::Override: {
1026 MDNode *&OvrNode = OverrideNode[ID];
1027 if (!OvrNode) OvrNode = Op;
1028 if (OvrNode->getOperand(2) != Val)
1029 HasErr = emitError("linking module flags '" + ID->getString() +
1030 "': IDs have conflicting override values");
1041 /// linkModuleFlagsMetadata - Merge the linker flags in Src into the Dest
1043 bool ModuleLinker::linkModuleFlagsMetadata() {
1044 const NamedMDNode *SrcModFlags = SrcM->getModuleFlagsMetadata();
1045 if (!SrcModFlags) return false;
1047 NamedMDNode *DstModFlags = DstM->getOrInsertModuleFlagsMetadata();
1049 // If the destination module doesn't have module flags yet, then just copy
1050 // over the source module's flags.
1051 if (DstModFlags->getNumOperands() == 0) {
1052 for (unsigned I = 0, E = SrcModFlags->getNumOperands(); I != E; ++I)
1053 DstModFlags->addOperand(SrcModFlags->getOperand(I));
1058 bool HasErr = false;
1060 // Otherwise, we have to merge them based on their behaviors. First,
1061 // categorize all of the nodes in the modules' module flags. If an error or
1062 // warning occurs, then emit the appropriate message(s).
1063 DenseMap<MDString*, MDNode*> ErrorNode;
1064 DenseMap<MDString*, MDNode*> WarningNode;
1065 DenseMap<MDString*, MDNode*> OverrideNode;
1066 DenseMap<MDString*, SmallSetVector<MDNode*, 8> > RequireNodes;
1067 SmallSetVector<MDString*, 16> SeenIDs;
1069 HasErr |= categorizeModuleFlagNodes(SrcModFlags, ErrorNode, WarningNode,
1070 OverrideNode, RequireNodes, SeenIDs);
1071 HasErr |= categorizeModuleFlagNodes(DstModFlags, ErrorNode, WarningNode,
1072 OverrideNode, RequireNodes, SeenIDs);
1074 // Check that there isn't both an error and warning node for a flag.
1075 for (SmallSetVector<MDString*, 16>::iterator
1076 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1078 if (ErrorNode[ID] && WarningNode[ID])
1079 HasErr = emitError("linking module flags '" + ID->getString() +
1080 "': IDs have conflicting behaviors");
1083 // Early exit if we had an error.
1084 if (HasErr) return true;
1086 // Get the destination's module flags ready for new operands.
1087 DstModFlags->dropAllReferences();
1089 // Add all of the module flags to the destination module.
1090 DenseMap<MDString*, SmallVector<MDNode*, 4> > AddedNodes;
1091 for (SmallSetVector<MDString*, 16>::iterator
1092 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1094 if (OverrideNode[ID]) {
1095 DstModFlags->addOperand(OverrideNode[ID]);
1096 AddedNodes[ID].push_back(OverrideNode[ID]);
1097 } else if (ErrorNode[ID]) {
1098 DstModFlags->addOperand(ErrorNode[ID]);
1099 AddedNodes[ID].push_back(ErrorNode[ID]);
1100 } else if (WarningNode[ID]) {
1101 DstModFlags->addOperand(WarningNode[ID]);
1102 AddedNodes[ID].push_back(WarningNode[ID]);
1105 for (SmallSetVector<MDNode*, 8>::iterator
1106 II = RequireNodes[ID].begin(), IE = RequireNodes[ID].end();
1108 DstModFlags->addOperand(*II);
1111 // Now check that all of the requirements have been satisfied.
1112 for (SmallSetVector<MDString*, 16>::iterator
1113 I = SeenIDs.begin(), E = SeenIDs.end(); I != E; ++I) {
1115 SmallSetVector<MDNode*, 8> &Set = RequireNodes[ID];
1117 for (SmallSetVector<MDNode*, 8>::iterator
1118 II = Set.begin(), IE = Set.end(); II != IE; ++II) {
1120 MDNode *Val = cast<MDNode>(Node->getOperand(2));
1122 MDString *ReqID = cast<MDString>(Val->getOperand(0));
1123 Value *ReqVal = Val->getOperand(1);
1125 bool HasValue = false;
1126 for (SmallVectorImpl<MDNode*>::iterator
1127 RI = AddedNodes[ReqID].begin(), RE = AddedNodes[ReqID].end();
1129 MDNode *ReqNode = *RI;
1130 if (ReqNode->getOperand(2) == ReqVal) {
1137 HasErr = emitError("linking module flags '" + ReqID->getString() +
1138 "': does not have the required value");
1145 bool ModuleLinker::run() {
1146 assert(DstM && "Null destination module");
1147 assert(SrcM && "Null source module");
1149 // Inherit the target data from the source module if the destination module
1150 // doesn't have one already.
1151 if (DstM->getDataLayout().empty() && !SrcM->getDataLayout().empty())
1152 DstM->setDataLayout(SrcM->getDataLayout());
1154 // Copy the target triple from the source to dest if the dest's is empty.
1155 if (DstM->getTargetTriple().empty() && !SrcM->getTargetTriple().empty())
1156 DstM->setTargetTriple(SrcM->getTargetTriple());
1158 if (!SrcM->getDataLayout().empty() && !DstM->getDataLayout().empty() &&
1159 SrcM->getDataLayout() != DstM->getDataLayout())
1160 errs() << "WARNING: Linking two modules of different data layouts!\n";
1161 if (!SrcM->getTargetTriple().empty() &&
1162 DstM->getTargetTriple() != SrcM->getTargetTriple()) {
1163 errs() << "WARNING: Linking two modules of different target triples: ";
1164 if (!SrcM->getModuleIdentifier().empty())
1165 errs() << SrcM->getModuleIdentifier() << ": ";
1166 errs() << "'" << SrcM->getTargetTriple() << "' and '"
1167 << DstM->getTargetTriple() << "'\n";
1170 // Append the module inline asm string.
1171 if (!SrcM->getModuleInlineAsm().empty()) {
1172 if (DstM->getModuleInlineAsm().empty())
1173 DstM->setModuleInlineAsm(SrcM->getModuleInlineAsm());
1175 DstM->setModuleInlineAsm(DstM->getModuleInlineAsm()+"\n"+
1176 SrcM->getModuleInlineAsm());
1179 // Loop over all of the linked values to compute type mappings.
1180 computeTypeMapping();
1182 // Insert all of the globals in src into the DstM module... without linking
1183 // initializers (which could refer to functions not yet mapped over).
1184 for (Module::global_iterator I = SrcM->global_begin(),
1185 E = SrcM->global_end(); I != E; ++I)
1186 if (linkGlobalProto(I))
1189 // Link the functions together between the two modules, without doing function
1190 // bodies... this just adds external function prototypes to the DstM
1191 // function... We do this so that when we begin processing function bodies,
1192 // all of the global values that may be referenced are available in our
1194 for (Module::iterator I = SrcM->begin(), E = SrcM->end(); I != E; ++I)
1195 if (linkFunctionProto(I))
1198 // If there were any aliases, link them now.
1199 for (Module::alias_iterator I = SrcM->alias_begin(),
1200 E = SrcM->alias_end(); I != E; ++I)
1201 if (linkAliasProto(I))
1204 for (unsigned i = 0, e = AppendingVars.size(); i != e; ++i)
1205 linkAppendingVarInit(AppendingVars[i]);
1207 // Update the initializers in the DstM module now that all globals that may
1208 // be referenced are in DstM.
1211 // Link in the function bodies that are defined in the source module into
1213 for (Module::iterator SF = SrcM->begin(), E = SrcM->end(); SF != E; ++SF) {
1214 // Skip if not linking from source.
1215 if (DoNotLinkFromSource.count(SF)) continue;
1217 // Skip if no body (function is external) or materialize.
1218 if (SF->isDeclaration()) {
1219 if (!SF->isMaterializable())
1221 if (SF->Materialize(&ErrorMsg))
1225 linkFunctionBody(cast<Function>(ValueMap[SF]), SF);
1226 SF->Dematerialize();
1229 // Resolve all uses of aliases with aliasees.
1232 // Remap all of the named MDNodes in Src into the DstM module. We do this
1233 // after linking GlobalValues so that MDNodes that reference GlobalValues
1234 // are properly remapped.
1237 // Merge the module flags into the DstM module.
1238 if (linkModuleFlagsMetadata())
1241 // Process vector of lazily linked in functions.
1242 bool LinkedInAnyFunctions;
1244 LinkedInAnyFunctions = false;
1246 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1247 E = LazilyLinkFunctions.end(); I != E; ++I) {
1252 Function *DF = cast<Function>(ValueMap[SF]);
1254 if (!DF->use_empty()) {
1256 // Materialize if necessary.
1257 if (SF->isDeclaration()) {
1258 if (!SF->isMaterializable())
1260 if (SF->Materialize(&ErrorMsg))
1264 // Link in function body.
1265 linkFunctionBody(DF, SF);
1266 SF->Dematerialize();
1268 // "Remove" from vector by setting the element to 0.
1271 // Set flag to indicate we may have more functions to lazily link in
1272 // since we linked in a function.
1273 LinkedInAnyFunctions = true;
1276 } while (LinkedInAnyFunctions);
1278 // Remove any prototypes of functions that were not actually linked in.
1279 for(std::vector<Function*>::iterator I = LazilyLinkFunctions.begin(),
1280 E = LazilyLinkFunctions.end(); I != E; ++I) {
1285 Function *DF = cast<Function>(ValueMap[SF]);
1286 if (DF->use_empty())
1287 DF->eraseFromParent();
1290 // Now that all of the types from the source are used, resolve any structs
1291 // copied over to the dest that didn't exist there.
1292 TypeMap.linkDefinedTypeBodies();
1297 //===----------------------------------------------------------------------===//
1298 // LinkModules entrypoint.
1299 //===----------------------------------------------------------------------===//
1301 /// LinkModules - This function links two modules together, with the resulting
1302 /// left module modified to be the composite of the two input modules. If an
1303 /// error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1304 /// the problem. Upon failure, the Dest module could be in a modified state,
1305 /// and shouldn't be relied on to be consistent.
1306 bool Linker::LinkModules(Module *Dest, Module *Src, unsigned Mode,
1307 std::string *ErrorMsg) {
1308 ModuleLinker TheLinker(Dest, Src, Mode);
1309 if (TheLinker.run()) {
1310 if (ErrorMsg) *ErrorMsg = TheLinker.ErrorMsg;
1317 //===----------------------------------------------------------------------===//
1319 //===----------------------------------------------------------------------===//
1321 LLVMBool LLVMLinkModules(LLVMModuleRef Dest, LLVMModuleRef Src,
1322 LLVMLinkerMode Mode, char **OutMessages) {
1323 std::string Messages;
1324 LLVMBool Result = Linker::LinkModules(unwrap(Dest), unwrap(Src),
1325 Mode, OutMessages? &Messages : 0);
1327 *OutMessages = strdup(Messages.c_str());