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 // Specifically, this:
13 // * Merges global variables between the two modules
14 // * Uninit + Uninit = Init, Init + Uninit = Init, Init + Init = Error if !=
15 // * Merges functions between two modules
17 //===----------------------------------------------------------------------===//
19 #include "llvm/Linker.h"
20 #include "llvm/Constants.h"
21 #include "llvm/DerivedTypes.h"
22 #include "llvm/Module.h"
23 #include "llvm/TypeSymbolTable.h"
24 #include "llvm/ValueSymbolTable.h"
25 #include "llvm/Instructions.h"
26 #include "llvm/Assembly/Writer.h"
27 #include "llvm/Support/Streams.h"
28 #include "llvm/System/Path.h"
29 #include "llvm/ADT/DenseMap.h"
33 // Error - Simple wrapper function to conditionally assign to E and return true.
34 // This just makes error return conditions a little bit simpler...
35 static inline bool Error(std::string *E, const std::string &Message) {
40 // ToStr - Simple wrapper function to convert a type to a string.
41 static std::string ToStr(const Type *Ty, const Module *M) {
42 std::ostringstream OS;
43 WriteTypeSymbolic(OS, Ty, M);
48 // Function: ResolveTypes()
51 // Attempt to link the two specified types together.
54 // DestTy - The type to which we wish to resolve.
55 // SrcTy - The original type which we want to resolve.
58 // DestST - The symbol table in which the new type should be placed.
61 // true - There is an error and the types cannot yet be linked.
64 static bool ResolveTypes(const Type *DestTy, const Type *SrcTy) {
65 if (DestTy == SrcTy) return false; // If already equal, noop
66 assert(DestTy && SrcTy && "Can't handle null types");
68 if (const OpaqueType *OT = dyn_cast<OpaqueType>(DestTy)) {
69 // Type _is_ in module, just opaque...
70 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(SrcTy);
71 } else if (const OpaqueType *OT = dyn_cast<OpaqueType>(SrcTy)) {
72 const_cast<OpaqueType*>(OT)->refineAbstractTypeTo(DestTy);
74 return true; // Cannot link types... not-equal and neither is opaque.
79 /// LinkerTypeMap - This implements a map of types that is stable
80 /// even if types are resolved/refined to other types. This is not a general
81 /// purpose map, it is specific to the linker's use.
83 class LinkerTypeMap : public AbstractTypeUser {
84 typedef DenseMap<const Type*, PATypeHolder> TheMapTy;
87 LinkerTypeMap(const LinkerTypeMap&); // DO NOT IMPLEMENT
88 void operator=(const LinkerTypeMap&); // DO NOT IMPLEMENT
92 for (DenseMap<const Type*, PATypeHolder>::iterator I = TheMap.begin(),
93 E = TheMap.end(); I != E; ++I)
94 I->first->removeAbstractTypeUser(this);
97 /// lookup - Return the value for the specified type or null if it doesn't
99 const Type *lookup(const Type *Ty) const {
100 TheMapTy::const_iterator I = TheMap.find(Ty);
101 if (I != TheMap.end()) return I->second;
105 /// erase - Remove the specified type, returning true if it was in the set.
106 bool erase(const Type *Ty) {
107 if (!TheMap.erase(Ty))
109 if (Ty->isAbstract())
110 Ty->removeAbstractTypeUser(this);
114 /// insert - This returns true if the pointer was new to the set, false if it
115 /// was already in the set.
116 bool insert(const Type *Src, const Type *Dst) {
117 if (!TheMap.insert(std::make_pair(Src, PATypeHolder(Dst))))
118 return false; // Already in map.
119 if (Src->isAbstract())
120 Src->addAbstractTypeUser(this);
125 /// refineAbstractType - The callback method invoked when an abstract type is
126 /// resolved to another type. An object must override this method to update
127 /// its internal state to reference NewType instead of OldType.
129 virtual void refineAbstractType(const DerivedType *OldTy,
131 TheMapTy::iterator I = TheMap.find(OldTy);
132 const Type *DstTy = I->second;
135 if (OldTy->isAbstract())
136 OldTy->removeAbstractTypeUser(this);
138 // Don't reinsert into the map if the key is concrete now.
139 if (NewTy->isAbstract())
140 insert(NewTy, DstTy);
143 /// The other case which AbstractTypeUsers must be aware of is when a type
144 /// makes the transition from being abstract (where it has clients on it's
145 /// AbstractTypeUsers list) to concrete (where it does not). This method
146 /// notifies ATU's when this occurs for a type.
147 virtual void typeBecameConcrete(const DerivedType *AbsTy) {
149 AbsTy->removeAbstractTypeUser(this);
153 virtual void dump() const {
154 cerr << "AbstractTypeSet!\n";
160 // RecursiveResolveTypes - This is just like ResolveTypes, except that it
161 // recurses down into derived types, merging the used types if the parent types
163 static bool RecursiveResolveTypesI(const Type *DstTy, const Type *SrcTy,
164 LinkerTypeMap &Pointers) {
165 if (DstTy == SrcTy) return false; // If already equal, noop
167 // If we found our opaque type, resolve it now!
168 if (isa<OpaqueType>(DstTy) || isa<OpaqueType>(SrcTy))
169 return ResolveTypes(DstTy, SrcTy);
171 // Two types cannot be resolved together if they are of different primitive
172 // type. For example, we cannot resolve an int to a float.
173 if (DstTy->getTypeID() != SrcTy->getTypeID()) return true;
175 // If neither type is abstract, then they really are just different types.
176 if (!DstTy->isAbstract() && !SrcTy->isAbstract())
179 // Otherwise, resolve the used type used by this derived type...
180 switch (DstTy->getTypeID()) {
183 case Type::FunctionTyID: {
184 const FunctionType *DstFT = cast<FunctionType>(DstTy);
185 const FunctionType *SrcFT = cast<FunctionType>(SrcTy);
186 if (DstFT->isVarArg() != SrcFT->isVarArg() ||
187 DstFT->getNumContainedTypes() != SrcFT->getNumContainedTypes())
190 // Use TypeHolder's so recursive resolution won't break us.
191 PATypeHolder ST(SrcFT), DT(DstFT);
192 for (unsigned i = 0, e = DstFT->getNumContainedTypes(); i != e; ++i) {
193 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
194 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
199 case Type::StructTyID: {
200 const StructType *DstST = cast<StructType>(DstTy);
201 const StructType *SrcST = cast<StructType>(SrcTy);
202 if (DstST->getNumContainedTypes() != SrcST->getNumContainedTypes())
205 PATypeHolder ST(SrcST), DT(DstST);
206 for (unsigned i = 0, e = DstST->getNumContainedTypes(); i != e; ++i) {
207 const Type *SE = ST->getContainedType(i), *DE = DT->getContainedType(i);
208 if (SE != DE && RecursiveResolveTypesI(DE, SE, Pointers))
213 case Type::ArrayTyID: {
214 const ArrayType *DAT = cast<ArrayType>(DstTy);
215 const ArrayType *SAT = cast<ArrayType>(SrcTy);
216 if (DAT->getNumElements() != SAT->getNumElements()) return true;
217 return RecursiveResolveTypesI(DAT->getElementType(), SAT->getElementType(),
220 case Type::VectorTyID: {
221 const VectorType *DVT = cast<VectorType>(DstTy);
222 const VectorType *SVT = cast<VectorType>(SrcTy);
223 if (DVT->getNumElements() != SVT->getNumElements()) return true;
224 return RecursiveResolveTypesI(DVT->getElementType(), SVT->getElementType(),
227 case Type::PointerTyID: {
228 const PointerType *DstPT = cast<PointerType>(DstTy);
229 const PointerType *SrcPT = cast<PointerType>(SrcTy);
231 if (DstPT->getAddressSpace() != SrcPT->getAddressSpace())
234 // If this is a pointer type, check to see if we have already seen it. If
235 // so, we are in a recursive branch. Cut off the search now. We cannot use
236 // an associative container for this search, because the type pointers (keys
237 // in the container) change whenever types get resolved.
238 if (SrcPT->isAbstract())
239 if (const Type *ExistingDestTy = Pointers.lookup(SrcPT))
240 return ExistingDestTy != DstPT;
242 if (DstPT->isAbstract())
243 if (const Type *ExistingSrcTy = Pointers.lookup(DstPT))
244 return ExistingSrcTy != SrcPT;
245 // Otherwise, add the current pointers to the vector to stop recursion on
247 if (DstPT->isAbstract())
248 Pointers.insert(DstPT, SrcPT);
249 if (SrcPT->isAbstract())
250 Pointers.insert(SrcPT, DstPT);
252 return RecursiveResolveTypesI(DstPT->getElementType(),
253 SrcPT->getElementType(), Pointers);
258 static bool RecursiveResolveTypes(const Type *DestTy, const Type *SrcTy) {
259 LinkerTypeMap PointerTypes;
260 return RecursiveResolveTypesI(DestTy, SrcTy, PointerTypes);
264 // LinkTypes - Go through the symbol table of the Src module and see if any
265 // types are named in the src module that are not named in the Dst module.
266 // Make sure there are no type name conflicts.
267 static bool LinkTypes(Module *Dest, const Module *Src, std::string *Err) {
268 TypeSymbolTable *DestST = &Dest->getTypeSymbolTable();
269 const TypeSymbolTable *SrcST = &Src->getTypeSymbolTable();
271 // Look for a type plane for Type's...
272 TypeSymbolTable::const_iterator TI = SrcST->begin();
273 TypeSymbolTable::const_iterator TE = SrcST->end();
274 if (TI == TE) return false; // No named types, do nothing.
276 // Some types cannot be resolved immediately because they depend on other
277 // types being resolved to each other first. This contains a list of types we
278 // are waiting to recheck.
279 std::vector<std::string> DelayedTypesToResolve;
281 for ( ; TI != TE; ++TI ) {
282 const std::string &Name = TI->first;
283 const Type *RHS = TI->second;
285 // Check to see if this type name is already in the dest module.
286 Type *Entry = DestST->lookup(Name);
288 // If the name is just in the source module, bring it over to the dest.
291 DestST->insert(Name, const_cast<Type*>(RHS));
292 } else if (ResolveTypes(Entry, RHS)) {
293 // They look different, save the types 'till later to resolve.
294 DelayedTypesToResolve.push_back(Name);
298 // Iteratively resolve types while we can...
299 while (!DelayedTypesToResolve.empty()) {
300 // Loop over all of the types, attempting to resolve them if possible...
301 unsigned OldSize = DelayedTypesToResolve.size();
303 // Try direct resolution by name...
304 for (unsigned i = 0; i != DelayedTypesToResolve.size(); ++i) {
305 const std::string &Name = DelayedTypesToResolve[i];
306 Type *T1 = SrcST->lookup(Name);
307 Type *T2 = DestST->lookup(Name);
308 if (!ResolveTypes(T2, T1)) {
309 // We are making progress!
310 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
315 // Did we not eliminate any types?
316 if (DelayedTypesToResolve.size() == OldSize) {
317 // Attempt to resolve subelements of types. This allows us to merge these
318 // two types: { int* } and { opaque* }
319 for (unsigned i = 0, e = DelayedTypesToResolve.size(); i != e; ++i) {
320 const std::string &Name = DelayedTypesToResolve[i];
321 if (!RecursiveResolveTypes(SrcST->lookup(Name), DestST->lookup(Name))) {
322 // We are making progress!
323 DelayedTypesToResolve.erase(DelayedTypesToResolve.begin()+i);
325 // Go back to the main loop, perhaps we can resolve directly by name
331 // If we STILL cannot resolve the types, then there is something wrong.
332 if (DelayedTypesToResolve.size() == OldSize) {
333 // Remove the symbol name from the destination.
334 DelayedTypesToResolve.pop_back();
343 static void PrintMap(const std::map<const Value*, Value*> &M) {
344 for (std::map<const Value*, Value*>::const_iterator I = M.begin(), E =M.end();
346 cerr << " Fr: " << (void*)I->first << " ";
348 cerr << " To: " << (void*)I->second << " ";
355 // RemapOperand - Use ValueMap to convert constants from one module to another.
356 static Value *RemapOperand(const Value *In,
357 std::map<const Value*, Value*> &ValueMap) {
358 std::map<const Value*,Value*>::const_iterator I = ValueMap.find(In);
359 if (I != ValueMap.end())
362 // Check to see if it's a constant that we are interested in transforming.
364 if (const Constant *CPV = dyn_cast<Constant>(In)) {
365 if ((!isa<DerivedType>(CPV->getType()) && !isa<ConstantExpr>(CPV)) ||
366 isa<ConstantInt>(CPV) || isa<ConstantAggregateZero>(CPV))
367 return const_cast<Constant*>(CPV); // Simple constants stay identical.
369 if (const ConstantArray *CPA = dyn_cast<ConstantArray>(CPV)) {
370 std::vector<Constant*> Operands(CPA->getNumOperands());
371 for (unsigned i = 0, e = CPA->getNumOperands(); i != e; ++i)
372 Operands[i] =cast<Constant>(RemapOperand(CPA->getOperand(i), ValueMap));
373 Result = ConstantArray::get(cast<ArrayType>(CPA->getType()), Operands);
374 } else if (const ConstantStruct *CPS = dyn_cast<ConstantStruct>(CPV)) {
375 std::vector<Constant*> Operands(CPS->getNumOperands());
376 for (unsigned i = 0, e = CPS->getNumOperands(); i != e; ++i)
377 Operands[i] =cast<Constant>(RemapOperand(CPS->getOperand(i), ValueMap));
378 Result = ConstantStruct::get(cast<StructType>(CPS->getType()), Operands);
379 } else if (isa<ConstantPointerNull>(CPV) || isa<UndefValue>(CPV)) {
380 Result = const_cast<Constant*>(CPV);
381 } else if (const ConstantVector *CP = dyn_cast<ConstantVector>(CPV)) {
382 std::vector<Constant*> Operands(CP->getNumOperands());
383 for (unsigned i = 0, e = CP->getNumOperands(); i != e; ++i)
384 Operands[i] = cast<Constant>(RemapOperand(CP->getOperand(i), ValueMap));
385 Result = ConstantVector::get(Operands);
386 } else if (const ConstantExpr *CE = dyn_cast<ConstantExpr>(CPV)) {
387 std::vector<Constant*> Ops;
388 for (unsigned i = 0, e = CE->getNumOperands(); i != e; ++i)
389 Ops.push_back(cast<Constant>(RemapOperand(CE->getOperand(i),ValueMap)));
390 Result = CE->getWithOperands(Ops);
391 } else if (isa<GlobalValue>(CPV)) {
392 assert(0 && "Unmapped global?");
394 assert(0 && "Unknown type of derived type constant value!");
396 } else if (isa<InlineAsm>(In)) {
397 Result = const_cast<Value*>(In);
400 // Cache the mapping in our local map structure
402 ValueMap[In] = Result;
407 cerr << "LinkModules ValueMap: \n";
410 cerr << "Couldn't remap value: " << (void*)In << " " << *In << "\n";
411 assert(0 && "Couldn't remap value!");
415 /// ForceRenaming - The LLVM SymbolTable class autorenames globals that conflict
416 /// in the symbol table. This is good for all clients except for us. Go
417 /// through the trouble to force this back.
418 static void ForceRenaming(GlobalValue *GV, const std::string &Name) {
419 assert(GV->getName() != Name && "Can't force rename to self");
420 ValueSymbolTable &ST = GV->getParent()->getValueSymbolTable();
422 // If there is a conflict, rename the conflict.
423 if (GlobalValue *ConflictGV = cast_or_null<GlobalValue>(ST.lookup(Name))) {
424 assert(ConflictGV->hasInternalLinkage() &&
425 "Not conflicting with a static global, should link instead!");
426 GV->takeName(ConflictGV);
427 ConflictGV->setName(Name); // This will cause ConflictGV to get renamed
428 assert(ConflictGV->getName() != Name && "ForceRenaming didn't work");
430 GV->setName(Name); // Force the name back
434 /// CopyGVAttributes - copy additional attributes (those not needed to construct
435 /// a GlobalValue) from the SrcGV to the DestGV.
436 static void CopyGVAttributes(GlobalValue *DestGV, const GlobalValue *SrcGV) {
437 // Use the maximum alignment, rather than just copying the alignment of SrcGV.
438 unsigned Alignment = std::max(DestGV->getAlignment(), SrcGV->getAlignment());
439 DestGV->copyAttributesFrom(SrcGV);
440 DestGV->setAlignment(Alignment);
443 /// GetLinkageResult - This analyzes the two global values and determines what
444 /// the result will look like in the destination module. In particular, it
445 /// computes the resultant linkage type, computes whether the global in the
446 /// source should be copied over to the destination (replacing the existing
447 /// one), and computes whether this linkage is an error or not. It also performs
448 /// visibility checks: we cannot link together two symbols with different
450 static bool GetLinkageResult(GlobalValue *Dest, const GlobalValue *Src,
451 GlobalValue::LinkageTypes <, bool &LinkFromSrc,
453 assert((!Dest || !Src->hasInternalLinkage()) &&
454 "If Src has internal linkage, Dest shouldn't be set!");
456 // Linking something to nothing.
458 LT = Src->getLinkage();
459 } else if (Src->isDeclaration()) {
460 // If Src is external or if both Src & Dest are external.. Just link the
461 // external globals, we aren't adding anything.
462 if (Src->hasDLLImportLinkage()) {
463 // If one of GVs has DLLImport linkage, result should be dllimport'ed.
464 if (Dest->isDeclaration()) {
466 LT = Src->getLinkage();
468 } else if (Dest->hasExternalWeakLinkage()) {
469 //If the Dest is weak, use the source linkage
471 LT = Src->getLinkage();
474 LT = Dest->getLinkage();
476 } else if (Dest->isDeclaration() && !Dest->hasDLLImportLinkage()) {
477 // If Dest is external but Src is not:
479 LT = Src->getLinkage();
480 } else if (Src->hasAppendingLinkage() || Dest->hasAppendingLinkage()) {
481 if (Src->getLinkage() != Dest->getLinkage())
482 return Error(Err, "Linking globals named '" + Src->getName() +
483 "': can only link appending global with another appending global!");
484 LinkFromSrc = true; // Special cased.
485 LT = Src->getLinkage();
486 } else if (Src->hasWeakLinkage() || Src->hasLinkOnceLinkage() ||
487 Src->hasCommonLinkage()) {
488 // At this point we know that Dest has LinkOnce, External*, Weak, Common,
490 if ((Dest->hasLinkOnceLinkage() &&
491 (Src->hasWeakLinkage() || Src->hasCommonLinkage())) ||
492 Dest->hasExternalWeakLinkage()) {
494 LT = Src->getLinkage();
497 LT = Dest->getLinkage();
499 } else if (Dest->hasWeakLinkage() || Dest->hasLinkOnceLinkage() ||
500 Dest->hasCommonLinkage()) {
501 // At this point we know that Src has External* or DLL* linkage.
502 if (Src->hasExternalWeakLinkage()) {
504 LT = Dest->getLinkage();
507 LT = GlobalValue::ExternalLinkage;
510 assert((Dest->hasExternalLinkage() ||
511 Dest->hasDLLImportLinkage() ||
512 Dest->hasDLLExportLinkage() ||
513 Dest->hasExternalWeakLinkage()) &&
514 (Src->hasExternalLinkage() ||
515 Src->hasDLLImportLinkage() ||
516 Src->hasDLLExportLinkage() ||
517 Src->hasExternalWeakLinkage()) &&
518 "Unexpected linkage type!");
519 return Error(Err, "Linking globals named '" + Src->getName() +
520 "': symbol multiply defined!");
524 if (Dest && Src->getVisibility() != Dest->getVisibility())
525 if (!Src->isDeclaration() && !Dest->isDeclaration())
526 return Error(Err, "Linking globals named '" + Src->getName() +
527 "': symbols have different visibilities!");
531 // LinkGlobals - Loop through the global variables in the src module and merge
532 // them into the dest module.
533 static bool LinkGlobals(Module *Dest, const Module *Src,
534 std::map<const Value*, Value*> &ValueMap,
535 std::multimap<std::string, GlobalVariable *> &AppendingVars,
537 // Loop over all of the globals in the src module, mapping them over as we go
538 for (Module::const_global_iterator I = Src->global_begin(), E = Src->global_end();
540 const GlobalVariable *SGV = I;
541 GlobalValue *DGV = 0;
543 // Check to see if may have to link the global with the global
544 if (SGV->hasName() && !SGV->hasInternalLinkage()) {
545 DGV = Dest->getGlobalVariable(SGV->getName());
546 if (DGV && DGV->getType() != SGV->getType())
547 // If types don't agree due to opaque types, try to resolve them.
548 RecursiveResolveTypes(SGV->getType(), DGV->getType());
551 // Check to see if may have to link the global with the alias
552 if (!DGV && SGV->hasName() && !SGV->hasInternalLinkage()) {
553 DGV = Dest->getNamedAlias(SGV->getName());
554 if (DGV && DGV->getType() != SGV->getType())
555 // If types don't agree due to opaque types, try to resolve them.
556 RecursiveResolveTypes(SGV->getType(), DGV->getType());
559 if (DGV && DGV->hasInternalLinkage())
562 assert((SGV->hasInitializer() || SGV->hasExternalWeakLinkage() ||
563 SGV->hasExternalLinkage() || SGV->hasDLLImportLinkage()) &&
564 "Global must either be external or have an initializer!");
566 GlobalValue::LinkageTypes NewLinkage = GlobalValue::InternalLinkage;
567 bool LinkFromSrc = false;
568 if (GetLinkageResult(DGV, SGV, NewLinkage, LinkFromSrc, Err))
572 // No linking to be performed, simply create an identical version of the
573 // symbol over in the dest module... the initializer will be filled in
574 // later by LinkGlobalInits...
575 GlobalVariable *NewDGV =
576 new GlobalVariable(SGV->getType()->getElementType(),
577 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
578 SGV->getName(), Dest);
579 // Propagate alignment, visibility and section info.
580 CopyGVAttributes(NewDGV, SGV);
582 // If the LLVM runtime renamed the global, but it is an externally visible
583 // symbol, DGV must be an existing global with internal linkage. Rename
585 if (NewDGV->getName() != SGV->getName() && !NewDGV->hasInternalLinkage())
586 ForceRenaming(NewDGV, SGV->getName());
588 // Make sure to remember this mapping...
589 ValueMap[SGV] = NewDGV;
591 if (SGV->hasAppendingLinkage())
592 // Keep track that this is an appending variable...
593 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
594 } else if (DGV->hasAppendingLinkage()) {
595 // No linking is performed yet. Just insert a new copy of the global, and
596 // keep track of the fact that it is an appending variable in the
597 // AppendingVars map. The name is cleared out so that no linkage is
599 GlobalVariable *NewDGV =
600 new GlobalVariable(SGV->getType()->getElementType(),
601 SGV->isConstant(), SGV->getLinkage(), /*init*/0,
604 // Set alignment allowing CopyGVAttributes merge it with alignment of SGV.
605 NewDGV->setAlignment(DGV->getAlignment());
606 // Propagate alignment, section and visibility info.
607 CopyGVAttributes(NewDGV, SGV);
609 // Make sure to remember this mapping...
610 ValueMap[SGV] = NewDGV;
612 // Keep track that this is an appending variable...
613 AppendingVars.insert(std::make_pair(SGV->getName(), NewDGV));
614 } else if (GlobalAlias *DGA = dyn_cast<GlobalAlias>(DGV)) {
615 // SGV is global, but DGV is alias. The only valid mapping is when SGV is
616 // external declaration, which is effectively a no-op. Also make sure
617 // linkage calculation was correct.
618 if (SGV->isDeclaration() && !LinkFromSrc) {
619 // Make sure to remember this mapping...
622 return Error(Err, "Global-Alias Collision on '" + SGV->getName() +
623 "': symbol multiple defined");
624 } else if (GlobalVariable *DGVar = dyn_cast<GlobalVariable>(DGV)) {
625 // Otherwise, perform the global-global mapping as instructed by
628 // Propagate alignment, section, and visibility info.
629 CopyGVAttributes(DGVar, SGV);
631 // If the types don't match, and if we are to link from the source, nuke
632 // DGV and create a new one of the appropriate type.
633 if (SGV->getType() != DGVar->getType()) {
634 GlobalVariable *NewDGV =
635 new GlobalVariable(SGV->getType()->getElementType(),
636 DGVar->isConstant(), DGVar->getLinkage(),
637 /*init*/0, DGVar->getName(), Dest);
638 CopyGVAttributes(NewDGV, DGVar);
639 DGV->replaceAllUsesWith(ConstantExpr::getBitCast(NewDGV,
641 // DGVar will conflict with NewDGV because they both had the same
642 // name. We must erase this now so ForceRenaming doesn't assert
643 // because DGV might not have internal linkage.
644 DGVar->eraseFromParent();
646 // If the symbol table renamed the global, but it is an externally
647 // visible symbol, DGV must be an existing global with internal
648 // linkage. Rename it.
649 if (NewDGV->getName() != SGV->getName() &&
650 !NewDGV->hasInternalLinkage())
651 ForceRenaming(NewDGV, SGV->getName());
656 // Inherit const as appropriate
657 DGVar->setConstant(SGV->isConstant());
659 // Set initializer to zero, so we can link the stuff later
660 DGVar->setInitializer(0);
662 // Special case for const propagation
663 if (DGVar->isDeclaration() && SGV->isConstant() && !DGVar->isConstant())
664 DGVar->setConstant(true);
667 // Set calculated linkage
668 DGVar->setLinkage(NewLinkage);
670 // Make sure to remember this mapping...
671 ValueMap[SGV] = ConstantExpr::getBitCast(DGVar, SGV->getType());
677 static GlobalValue::LinkageTypes
678 CalculateAliasLinkage(const GlobalValue *SGV, const GlobalValue *DGV) {
679 if (SGV->hasExternalLinkage() || DGV->hasExternalLinkage())
680 return GlobalValue::ExternalLinkage;
681 else if (SGV->hasWeakLinkage() || DGV->hasWeakLinkage())
682 return GlobalValue::WeakLinkage;
684 assert(SGV->hasInternalLinkage() && DGV->hasInternalLinkage() &&
685 "Unexpected linkage type");
686 return GlobalValue::InternalLinkage;
690 // LinkAlias - Loop through the alias in the src module and link them into the
691 // dest module. We're assuming, that all functions/global variables were already
693 static bool LinkAlias(Module *Dest, const Module *Src,
694 std::map<const Value*, Value*> &ValueMap,
696 // Loop over all alias in the src module
697 for (Module::const_alias_iterator I = Src->alias_begin(),
698 E = Src->alias_end(); I != E; ++I) {
699 const GlobalAlias *SGA = I;
700 const GlobalValue *SAliasee = SGA->getAliasedGlobal();
701 GlobalAlias *NewGA = NULL;
703 // Globals were already linked, thus we can just query ValueMap for variant
704 // of SAliasee in Dest.
705 std::map<const Value*,Value*>::const_iterator VMI = ValueMap.find(SAliasee);
706 assert(VMI != ValueMap.end() && "Aliasee not linked");
707 GlobalValue* DAliasee = cast<GlobalValue>(VMI->second);
708 GlobalValue* DGV = NULL;
710 // Try to find something 'similar' to SGA in destination module.
711 if (!DGV && !SGA->hasInternalLinkage()) {
712 DGV = Dest->getNamedAlias(SGA->getName());
714 // If types don't agree due to opaque types, try to resolve them.
715 if (DGV && DGV->getType() != SGA->getType())
716 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
717 return Error(Err, "Alias Collision on '" + SGA->getName()+
718 "': aliases have different types");
721 if (!DGV && !SGA->hasInternalLinkage()) {
722 DGV = Dest->getGlobalVariable(SGA->getName());
724 // If types don't agree due to opaque types, try to resolve them.
725 if (DGV && DGV->getType() != SGA->getType())
726 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
727 return Error(Err, "Alias Collision on '" + SGA->getName()+
728 "': aliases have different types");
731 if (!DGV && !SGA->hasInternalLinkage()) {
732 DGV = Dest->getFunction(SGA->getName());
734 // If types don't agree due to opaque types, try to resolve them.
735 if (DGV && DGV->getType() != SGA->getType())
736 if (RecursiveResolveTypes(SGA->getType(), DGV->getType()))
737 return Error(Err, "Alias Collision on '" + SGA->getName()+
738 "': aliases have different types");
741 // No linking to be performed on internal stuff.
742 if (DGV && DGV->hasInternalLinkage())
745 if (GlobalAlias *DGA = dyn_cast_or_null<GlobalAlias>(DGV)) {
746 // Types are known to be the same, check whether aliasees equal. As
747 // globals are already linked we just need query ValueMap to find the
749 if (DAliasee == DGA->getAliasedGlobal()) {
750 // This is just two copies of the same alias. Propagate linkage, if
752 DGA->setLinkage(CalculateAliasLinkage(SGA, DGA));
755 // Proceed to 'common' steps
757 return Error(Err, "Alias Collision on '" + SGA->getName()+
758 "': aliases have different aliasees");
759 } else if (GlobalVariable *DGVar = dyn_cast_or_null<GlobalVariable>(DGV)) {
760 // The only allowed way is to link alias with external declaration.
761 if (DGVar->isDeclaration()) {
762 // But only if aliasee is global too...
763 if (!isa<GlobalVariable>(DAliasee))
764 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
765 "': aliasee is not global variable");
767 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
768 SGA->getName(), DAliasee, Dest);
769 CopyGVAttributes(NewGA, SGA);
771 // Any uses of DGV need to change to NewGA, with cast, if needed.
772 if (SGA->getType() != DGVar->getType())
773 DGVar->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
776 DGVar->replaceAllUsesWith(NewGA);
778 // DGVar will conflict with NewGA because they both had the same
779 // name. We must erase this now so ForceRenaming doesn't assert
780 // because DGV might not have internal linkage.
781 DGVar->eraseFromParent();
783 // Proceed to 'common' steps
785 return Error(Err, "Global-Alias Collision on '" + SGA->getName() +
786 "': symbol multiple defined");
787 } else if (Function *DF = dyn_cast_or_null<Function>(DGV)) {
788 // The only allowed way is to link alias with external declaration.
789 if (DF->isDeclaration()) {
790 // But only if aliasee is function too...
791 if (!isa<Function>(DAliasee))
792 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
793 "': aliasee is not function");
795 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
796 SGA->getName(), DAliasee, Dest);
797 CopyGVAttributes(NewGA, SGA);
799 // Any uses of DF need to change to NewGA, with cast, if needed.
800 if (SGA->getType() != DF->getType())
801 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewGA,
804 DF->replaceAllUsesWith(NewGA);
806 // DF will conflict with NewGA because they both had the same
807 // name. We must erase this now so ForceRenaming doesn't assert
808 // because DF might not have internal linkage.
809 DF->eraseFromParent();
811 // Proceed to 'common' steps
813 return Error(Err, "Function-Alias Collision on '" + SGA->getName() +
814 "': symbol multiple defined");
816 // No linking to be performed, simply create an identical version of the
817 // alias over in the dest module...
819 NewGA = new GlobalAlias(SGA->getType(), SGA->getLinkage(),
820 SGA->getName(), DAliasee, Dest);
821 CopyGVAttributes(NewGA, SGA);
823 // Proceed to 'common' steps
826 assert(NewGA && "No alias was created in destination module!");
828 // If the symbol table renamed the alias, but it is an externally visible
829 // symbol, DGA must be an global value with internal linkage. Rename it.
830 if (NewGA->getName() != SGA->getName() &&
831 !NewGA->hasInternalLinkage())
832 ForceRenaming(NewGA, SGA->getName());
834 // Remember this mapping so uses in the source module get remapped
835 // later by RemapOperand.
836 ValueMap[SGA] = NewGA;
843 // LinkGlobalInits - Update the initializers in the Dest module now that all
844 // globals that may be referenced are in Dest.
845 static bool LinkGlobalInits(Module *Dest, const Module *Src,
846 std::map<const Value*, Value*> &ValueMap,
849 // Loop over all of the globals in the src module, mapping them over as we go
850 for (Module::const_global_iterator I = Src->global_begin(),
851 E = Src->global_end(); I != E; ++I) {
852 const GlobalVariable *SGV = I;
854 if (SGV->hasInitializer()) { // Only process initialized GV's
855 // Figure out what the initializer looks like in the dest module...
857 cast<Constant>(RemapOperand(SGV->getInitializer(), ValueMap));
859 GlobalVariable *DGV =
860 cast<GlobalVariable>(ValueMap[SGV]->stripPointerCasts());
861 if (DGV->hasInitializer()) {
862 if (SGV->hasExternalLinkage()) {
863 if (DGV->getInitializer() != SInit)
864 return Error(Err, "Global Variable Collision on '" + SGV->getName() +
865 "': global variables have different initializers");
866 } else if (DGV->hasLinkOnceLinkage() || DGV->hasWeakLinkage() ||
867 DGV->hasCommonLinkage()) {
868 // Nothing is required, mapped values will take the new global
870 } else if (SGV->hasLinkOnceLinkage() || SGV->hasWeakLinkage() ||
871 SGV->hasCommonLinkage()) {
872 // Nothing is required, mapped values will take the new global
874 } else if (DGV->hasAppendingLinkage()) {
875 assert(0 && "Appending linkage unimplemented!");
877 assert(0 && "Unknown linkage!");
880 // Copy the initializer over now...
881 DGV->setInitializer(SInit);
888 // LinkFunctionProtos - Link the functions together between the two modules,
889 // without doing function bodies... this just adds external function prototypes
890 // to the Dest function...
892 static bool LinkFunctionProtos(Module *Dest, const Module *Src,
893 std::map<const Value*, Value*> &ValueMap,
895 // Loop over all of the functions in the src module, mapping them over
896 for (Module::const_iterator I = Src->begin(), E = Src->end(); I != E; ++I) {
897 const Function *SF = I; // SrcFunction
902 // If this function is internal or has no name, it doesn't participate in
904 if (SF->hasName() && !SF->hasInternalLinkage()) {
905 // Check to see if may have to link the function.
906 DF = Dest->getFunction(SF->getName());
907 if (DF && DF->hasInternalLinkage())
911 // If there is no linkage to be performed, just bring over SF without
914 // Function does not already exist, simply insert an function signature
915 // identical to SF into the dest module.
916 Function *NewDF = Function::Create(SF->getFunctionType(),
918 SF->getName(), Dest);
919 CopyGVAttributes(NewDF, SF);
921 // If the LLVM runtime renamed the function, but it is an externally
922 // visible symbol, DF must be an existing function with internal linkage.
924 if (!NewDF->hasInternalLinkage() && NewDF->getName() != SF->getName())
925 ForceRenaming(NewDF, SF->getName());
927 // ... and remember this mapping...
928 ValueMap[SF] = NewDF;
933 // If types don't agree because of opaque, try to resolve them.
934 if (SF->getType() != DF->getType())
935 RecursiveResolveTypes(SF->getType(), DF->getType());
937 // Check visibility, merging if a definition overrides a prototype.
938 if (SF->getVisibility() != DF->getVisibility()) {
939 // If one is a prototype, ignore its visibility. Prototypes are always
940 // overridden by the definition.
941 if (!SF->isDeclaration() && !DF->isDeclaration())
942 return Error(Err, "Linking functions named '" + SF->getName() +
943 "': symbols have different visibilities!");
945 // Otherwise, replace the visibility of DF if DF is a prototype.
946 if (DF->isDeclaration())
947 DF->setVisibility(SF->getVisibility());
950 if (DF->getType() != SF->getType()) {
951 if (DF->isDeclaration() && !SF->isDeclaration()) {
952 // We have a definition of the same name but different type in the
953 // source module. Copy the prototype to the destination and replace
954 // uses of the destination's prototype with the new prototype.
955 Function *NewDF = Function::Create(SF->getFunctionType(),
957 SF->getName(), Dest);
958 CopyGVAttributes(NewDF, SF);
960 // Any uses of DF need to change to NewDF, with cast
961 DF->replaceAllUsesWith(ConstantExpr::getBitCast(NewDF, DF->getType()));
963 // DF will conflict with NewDF because they both had the same. We must
964 // erase this now so ForceRenaming doesn't assert because DF might
965 // not have internal linkage.
966 DF->eraseFromParent();
968 // If the symbol table renamed the function, but it is an externally
969 // visible symbol, DF must be an existing function with internal
970 // linkage. Rename it.
971 if (NewDF->getName() != SF->getName() && !NewDF->hasInternalLinkage())
972 ForceRenaming(NewDF, SF->getName());
974 // Remember this mapping so uses in the source module get remapped
975 // later by RemapOperand.
976 ValueMap[SF] = NewDF;
979 // We have two functions of the same name but different type. Any use
980 // of the source must be mapped to the destination, with a cast.
981 MappedDF = ConstantExpr::getBitCast(DF, SF->getType());
987 if (SF->isDeclaration()) {
988 // If SF is a declaration or if both SF & DF are declarations, just link
989 // the declarations, we aren't adding anything.
990 if (SF->hasDLLImportLinkage()) {
991 if (DF->isDeclaration()) {
992 ValueMap[SF] = MappedDF;
993 DF->setLinkage(SF->getLinkage());
996 ValueMap[SF] = MappedDF;
1001 // If DF is external but SF is not, link the external functions, update
1002 // linkage qualifiers.
1003 if (DF->isDeclaration() && !DF->hasDLLImportLinkage()) {
1004 ValueMap.insert(std::make_pair(SF, MappedDF));
1005 DF->setLinkage(SF->getLinkage());
1009 // At this point we know that DF has LinkOnce, Weak, or External* linkage.
1010 if (SF->hasWeakLinkage() || SF->hasLinkOnceLinkage() ||
1011 SF->hasCommonLinkage()) {
1012 ValueMap[SF] = MappedDF;
1014 // Linkonce+Weak = Weak
1015 // *+External Weak = *
1016 if ((DF->hasLinkOnceLinkage() &&
1017 (SF->hasWeakLinkage() || SF->hasCommonLinkage())) ||
1018 DF->hasExternalWeakLinkage())
1019 DF->setLinkage(SF->getLinkage());
1023 if (DF->hasWeakLinkage() || DF->hasLinkOnceLinkage() ||
1024 DF->hasCommonLinkage()) {
1025 // At this point we know that SF has LinkOnce or External* linkage.
1026 ValueMap[SF] = MappedDF;
1028 // If the source function has stronger linkage than the destination,
1029 // its body and linkage should override ours.
1030 if (!SF->hasLinkOnceLinkage() && !SF->hasExternalWeakLinkage()) {
1031 // Don't inherit linkonce & external weak linkage.
1032 DF->setLinkage(SF->getLinkage());
1038 if (SF->getLinkage() != DF->getLinkage())
1039 return Error(Err, "Functions named '" + SF->getName() +
1040 "' have different linkage specifiers!");
1042 // The function is defined identically in both modules!
1043 if (SF->hasExternalLinkage())
1044 return Error(Err, "Function '" +
1045 ToStr(SF->getFunctionType(), Src) + "':\"" +
1046 SF->getName() + "\" - Function is already defined!");
1047 assert(0 && "Unknown linkage configuration found!");
1052 // LinkFunctionBody - Copy the source function over into the dest function and
1053 // fix up references to values. At this point we know that Dest is an external
1054 // function, and that Src is not.
1055 static bool LinkFunctionBody(Function *Dest, Function *Src,
1056 std::map<const Value*, Value*> &ValueMap,
1058 assert(Src && Dest && Dest->isDeclaration() && !Src->isDeclaration());
1060 // Go through and convert function arguments over, remembering the mapping.
1061 Function::arg_iterator DI = Dest->arg_begin();
1062 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1063 I != E; ++I, ++DI) {
1064 DI->setName(I->getName()); // Copy the name information over...
1066 // Add a mapping to our local map
1070 // Splice the body of the source function into the dest function.
1071 Dest->getBasicBlockList().splice(Dest->end(), Src->getBasicBlockList());
1073 // At this point, all of the instructions and values of the function are now
1074 // copied over. The only problem is that they are still referencing values in
1075 // the Source function as operands. Loop through all of the operands of the
1076 // functions and patch them up to point to the local versions...
1078 for (Function::iterator BB = Dest->begin(), BE = Dest->end(); BB != BE; ++BB)
1079 for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
1080 for (Instruction::op_iterator OI = I->op_begin(), OE = I->op_end();
1082 if (!isa<Instruction>(*OI) && !isa<BasicBlock>(*OI))
1083 *OI = RemapOperand(*OI, ValueMap);
1085 // There is no need to map the arguments anymore.
1086 for (Function::arg_iterator I = Src->arg_begin(), E = Src->arg_end();
1094 // LinkFunctionBodies - Link in the function bodies that are defined in the
1095 // source module into the DestModule. This consists basically of copying the
1096 // function over and fixing up references to values.
1097 static bool LinkFunctionBodies(Module *Dest, Module *Src,
1098 std::map<const Value*, Value*> &ValueMap,
1101 // Loop over all of the functions in the src module, mapping them over as we
1103 for (Module::iterator SF = Src->begin(), E = Src->end(); SF != E; ++SF) {
1104 if (!SF->isDeclaration()) { // No body if function is external
1105 Function *DF = dyn_cast<Function>(ValueMap[SF]); // Destination function
1107 // DF not external SF external?
1108 if (DF && DF->isDeclaration())
1109 // Only provide the function body if there isn't one already.
1110 if (LinkFunctionBody(DF, SF, ValueMap, Err))
1117 // LinkAppendingVars - If there were any appending global variables, link them
1118 // together now. Return true on error.
1119 static bool LinkAppendingVars(Module *M,
1120 std::multimap<std::string, GlobalVariable *> &AppendingVars,
1121 std::string *ErrorMsg) {
1122 if (AppendingVars.empty()) return false; // Nothing to do.
1124 // Loop over the multimap of appending vars, processing any variables with the
1125 // same name, forming a new appending global variable with both of the
1126 // initializers merged together, then rewrite references to the old variables
1128 std::vector<Constant*> Inits;
1129 while (AppendingVars.size() > 1) {
1130 // Get the first two elements in the map...
1131 std::multimap<std::string,
1132 GlobalVariable*>::iterator Second = AppendingVars.begin(), First=Second++;
1134 // If the first two elements are for different names, there is no pair...
1135 // Otherwise there is a pair, so link them together...
1136 if (First->first == Second->first) {
1137 GlobalVariable *G1 = First->second, *G2 = Second->second;
1138 const ArrayType *T1 = cast<ArrayType>(G1->getType()->getElementType());
1139 const ArrayType *T2 = cast<ArrayType>(G2->getType()->getElementType());
1141 // Check to see that they two arrays agree on type...
1142 if (T1->getElementType() != T2->getElementType())
1143 return Error(ErrorMsg,
1144 "Appending variables with different element types need to be linked!");
1145 if (G1->isConstant() != G2->isConstant())
1146 return Error(ErrorMsg,
1147 "Appending variables linked with different const'ness!");
1149 if (G1->getAlignment() != G2->getAlignment())
1150 return Error(ErrorMsg,
1151 "Appending variables with different alignment need to be linked!");
1153 if (G1->getVisibility() != G2->getVisibility())
1154 return Error(ErrorMsg,
1155 "Appending variables with different visibility need to be linked!");
1157 if (G1->getSection() != G2->getSection())
1158 return Error(ErrorMsg,
1159 "Appending variables with different section name need to be linked!");
1161 unsigned NewSize = T1->getNumElements() + T2->getNumElements();
1162 ArrayType *NewType = ArrayType::get(T1->getElementType(), NewSize);
1164 G1->setName(""); // Clear G1's name in case of a conflict!
1166 // Create the new global variable...
1167 GlobalVariable *NG =
1168 new GlobalVariable(NewType, G1->isConstant(), G1->getLinkage(),
1169 /*init*/0, First->first, M, G1->isThreadLocal());
1171 // Propagate alignment, visibility and section info.
1172 CopyGVAttributes(NG, G1);
1174 // Merge the initializer...
1175 Inits.reserve(NewSize);
1176 if (ConstantArray *I = dyn_cast<ConstantArray>(G1->getInitializer())) {
1177 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1178 Inits.push_back(I->getOperand(i));
1180 assert(isa<ConstantAggregateZero>(G1->getInitializer()));
1181 Constant *CV = Constant::getNullValue(T1->getElementType());
1182 for (unsigned i = 0, e = T1->getNumElements(); i != e; ++i)
1183 Inits.push_back(CV);
1185 if (ConstantArray *I = dyn_cast<ConstantArray>(G2->getInitializer())) {
1186 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1187 Inits.push_back(I->getOperand(i));
1189 assert(isa<ConstantAggregateZero>(G2->getInitializer()));
1190 Constant *CV = Constant::getNullValue(T2->getElementType());
1191 for (unsigned i = 0, e = T2->getNumElements(); i != e; ++i)
1192 Inits.push_back(CV);
1194 NG->setInitializer(ConstantArray::get(NewType, Inits));
1197 // Replace any uses of the two global variables with uses of the new
1200 // FIXME: This should rewrite simple/straight-forward uses such as
1201 // getelementptr instructions to not use the Cast!
1202 G1->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G1->getType()));
1203 G2->replaceAllUsesWith(ConstantExpr::getBitCast(NG, G2->getType()));
1205 // Remove the two globals from the module now...
1206 M->getGlobalList().erase(G1);
1207 M->getGlobalList().erase(G2);
1209 // Put the new global into the AppendingVars map so that we can handle
1210 // linking of more than two vars...
1211 Second->second = NG;
1213 AppendingVars.erase(First);
1219 static bool ResolveAliases(Module *Dest) {
1220 for (Module::alias_iterator I = Dest->alias_begin(), E = Dest->alias_end();
1222 if (const GlobalValue *GV = I->resolveAliasedGlobal())
1223 if (!GV->isDeclaration())
1224 I->replaceAllUsesWith(const_cast<GlobalValue*>(GV));
1229 // LinkModules - This function links two modules together, with the resulting
1230 // left module modified to be the composite of the two input modules. If an
1231 // error occurs, true is returned and ErrorMsg (if not null) is set to indicate
1232 // the problem. Upon failure, the Dest module could be in a modified state, and
1233 // shouldn't be relied on to be consistent.
1235 Linker::LinkModules(Module *Dest, Module *Src, std::string *ErrorMsg) {
1236 assert(Dest != 0 && "Invalid Destination module");
1237 assert(Src != 0 && "Invalid Source Module");
1239 if (Dest->getDataLayout().empty()) {
1240 if (!Src->getDataLayout().empty()) {
1241 Dest->setDataLayout(Src->getDataLayout());
1243 std::string DataLayout;
1245 if (Dest->getEndianness() == Module::AnyEndianness) {
1246 if (Src->getEndianness() == Module::BigEndian)
1247 DataLayout.append("E");
1248 else if (Src->getEndianness() == Module::LittleEndian)
1249 DataLayout.append("e");
1252 if (Dest->getPointerSize() == Module::AnyPointerSize) {
1253 if (Src->getPointerSize() == Module::Pointer64)
1254 DataLayout.append(DataLayout.length() == 0 ? "p:64:64" : "-p:64:64");
1255 else if (Src->getPointerSize() == Module::Pointer32)
1256 DataLayout.append(DataLayout.length() == 0 ? "p:32:32" : "-p:32:32");
1258 Dest->setDataLayout(DataLayout);
1262 // Copy the target triple from the source to dest if the dest's is empty.
1263 if (Dest->getTargetTriple().empty() && !Src->getTargetTriple().empty())
1264 Dest->setTargetTriple(Src->getTargetTriple());
1266 if (!Src->getDataLayout().empty() && !Dest->getDataLayout().empty() &&
1267 Src->getDataLayout() != Dest->getDataLayout())
1268 cerr << "WARNING: Linking two modules of different data layouts!\n";
1269 if (!Src->getTargetTriple().empty() &&
1270 Dest->getTargetTriple() != Src->getTargetTriple())
1271 cerr << "WARNING: Linking two modules of different target triples!\n";
1273 // Append the module inline asm string.
1274 if (!Src->getModuleInlineAsm().empty()) {
1275 if (Dest->getModuleInlineAsm().empty())
1276 Dest->setModuleInlineAsm(Src->getModuleInlineAsm());
1278 Dest->setModuleInlineAsm(Dest->getModuleInlineAsm()+"\n"+
1279 Src->getModuleInlineAsm());
1282 // Update the destination module's dependent libraries list with the libraries
1283 // from the source module. There's no opportunity for duplicates here as the
1284 // Module ensures that duplicate insertions are discarded.
1285 for (Module::lib_iterator SI = Src->lib_begin(), SE = Src->lib_end();
1287 Dest->addLibrary(*SI);
1289 // LinkTypes - Go through the symbol table of the Src module and see if any
1290 // types are named in the src module that are not named in the Dst module.
1291 // Make sure there are no type name conflicts.
1292 if (LinkTypes(Dest, Src, ErrorMsg))
1295 // ValueMap - Mapping of values from what they used to be in Src, to what they
1297 std::map<const Value*, Value*> ValueMap;
1299 // AppendingVars - Keep track of global variables in the destination module
1300 // with appending linkage. After the module is linked together, they are
1301 // appended and the module is rewritten.
1302 std::multimap<std::string, GlobalVariable *> AppendingVars;
1303 for (Module::global_iterator I = Dest->global_begin(), E = Dest->global_end();
1305 // Add all of the appending globals already in the Dest module to
1307 if (I->hasAppendingLinkage())
1308 AppendingVars.insert(std::make_pair(I->getName(), I));
1311 // Insert all of the globals in src into the Dest module... without linking
1312 // initializers (which could refer to functions not yet mapped over).
1313 if (LinkGlobals(Dest, Src, ValueMap, AppendingVars, ErrorMsg))
1316 // Link the functions together between the two modules, without doing function
1317 // bodies... this just adds external function prototypes to the Dest
1318 // function... We do this so that when we begin processing function bodies,
1319 // all of the global values that may be referenced are available in our
1321 if (LinkFunctionProtos(Dest, Src, ValueMap, ErrorMsg))
1324 // If there were any alias, link them now. We really need to do this now,
1325 // because all of the aliases that may be referenced need to be available in
1327 if (LinkAlias(Dest, Src, ValueMap, ErrorMsg)) return true;
1329 // Update the initializers in the Dest module now that all globals that may
1330 // be referenced are in Dest.
1331 if (LinkGlobalInits(Dest, Src, ValueMap, ErrorMsg)) return true;
1333 // Link in the function bodies that are defined in the source module into the
1334 // DestModule. This consists basically of copying the function over and
1335 // fixing up references to values.
1336 if (LinkFunctionBodies(Dest, Src, ValueMap, ErrorMsg)) return true;
1338 // If there were any appending global variables, link them together now.
1339 if (LinkAppendingVars(Dest, AppendingVars, ErrorMsg)) return true;
1341 // Resolve all uses of aliases with aliasees
1342 if (ResolveAliases(Dest)) return true;
1344 // If the source library's module id is in the dependent library list of the
1345 // destination library, remove it since that module is now linked in.
1347 modId.set(Src->getModuleIdentifier());
1348 if (!modId.isEmpty())
1349 Dest->removeLibrary(modId.getBasename());